query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
TestExecute feeds input to the CLI and validates results. scan() is implicitly tested here.
func TestExecute(t *testing.T) { fmt.Println("TestExecute start") var inputSource *bytes.Buffer ipTest := []IPTest{ {"127.0.0.1", "9999", 1, 1}, {"8.8.8.8", "443", 1, 0}, {"::1", "9999", 1, 1}, {"127.0.0.1 ::1", "9999", 2, 2}} for _, v := range ipTest { inputSource = bytes.NewBuffer([]byte(fmt.Sprintf("setport %s\n", v.port))) runCLI(inputSource) inputSource = bytes.NewBuffer([]byte("setips " + v.ips + "\n")) runCLI(inputSource) inputSource = bytes.NewBuffer([]byte("execute\n")) runCLI(inputSource) inputSource = bytes.NewBuffer([]byte("results\n")) runCLI(inputSource) errors := 0 for j := 0; j < len(results); j++ { if results[j].Error != nil && *results[j].Error != scan.NoError { errors++ } } if len(results) != v.expectedResults || errors != v.expectedErrors { t.Errorf("Unexpected scan results for IPs: %s, results: %+v", v.ips, results) } } fmt.Println("TestExecute done") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *testComamnd) Execute() {\n\n\t// Parse subcommand args first.\n\tif len(os.Args) < 4 {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\n\tserviceRef := os.Args[2]\n\ttestEndpoint := os.Args[3]\n\trunnerType := os.Args[4]\n\n\t// Validate presence and values of args.\n\tif &serviceRef == nil || strings.HasPrefix(serviceRef, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif &testEndpoint == nil || strings.HasPrefix(testEndpoint, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif &runnerType == nil || strings.HasPrefix(runnerType, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif _, validChoice := runnerChoices[runnerType]; !validChoice {\n\t\tfmt.Println(\"<runner> should be one of: HTTP, SOAP, SOAP_UI, POSTMAN, OPEN_API_SCHEMA, ASYNC_API_SCHEMA, GRPC_PROTOBUF, GRAPHQL_SCHEMA\")\n\t\tos.Exit(1)\n\t}\n\n\t// Then parse flags.\n\ttestCmd := flag.NewFlagSet(\"test\", flag.ExitOnError)\n\n\tvar microcksURL string\n\tvar keycloakURL string\n\tvar keycloakClientID string\n\tvar keycloakClientSecret string\n\tvar waitFor string\n\tvar secretName string\n\tvar filteredOperations string\n\tvar operationsHeaders string\n\tvar insecureTLS bool\n\tvar caCertPaths string\n\tvar verbose bool\n\n\ttestCmd.StringVar(&microcksURL, \"microcksURL\", \"\", \"Microcks API URL\")\n\ttestCmd.StringVar(&keycloakClientID, \"keycloakClientId\", \"\", \"Keycloak Realm Service Account ClientId\")\n\ttestCmd.StringVar(&keycloakClientSecret, \"keycloakClientSecret\", \"\", \"Keycloak Realm Service Account ClientSecret\")\n\ttestCmd.StringVar(&waitFor, \"waitFor\", \"5sec\", \"Time to wait for test to finish\")\n\ttestCmd.StringVar(&secretName, \"secretName\", \"\", \"Secret to use for connecting test endpoint\")\n\ttestCmd.StringVar(&filteredOperations, \"filteredOperations\", \"\", \"List of operations to launch a test for\")\n\ttestCmd.StringVar(&operationsHeaders, \"operationsHeaders\", \"\", \"Override of operations headers as JSON string\")\n\ttestCmd.BoolVar(&insecureTLS, \"insecure\", false, \"Whether to accept insecure HTTPS connection\")\n\ttestCmd.StringVar(&caCertPaths, \"caCerts\", \"\", \"Comma separated paths of CRT files to add to Root CAs\")\n\ttestCmd.BoolVar(&verbose, \"verbose\", false, \"Produce dumps of HTTP exchanges\")\n\ttestCmd.Parse(os.Args[5:])\n\n\t// Validate presence and values of flags.\n\tif len(microcksURL) == 0 {\n\t\tfmt.Println(\"--microcksURL flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif len(keycloakClientID) == 0 {\n\t\tfmt.Println(\"--keycloakClientId flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif len(keycloakClientSecret) == 0 {\n\t\tfmt.Println(\"--keycloakClientSecret flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif &waitFor == nil || (!strings.HasSuffix(waitFor, \"milli\") && !strings.HasSuffix(waitFor, \"sec\") && !strings.HasSuffix(waitFor, \"min\")) {\n\t\tfmt.Println(\"--waitFor format is wrong. Applying default 5sec\")\n\t\twaitFor = \"5sec\"\n\t}\n\n\t// Collect optional HTTPS transport flags.\n\tif insecureTLS {\n\t\tconfig.InsecureTLS = true\n\t}\n\tif len(caCertPaths) > 0 {\n\t\tconfig.CaCertPaths = caCertPaths\n\t}\n\tif verbose {\n\t\tconfig.Verbose = true\n\t}\n\n\t// Compute time to wait in milliseconds.\n\tvar waitForMilliseconds int64 = 5000\n\tif strings.HasSuffix(waitFor, \"milli\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-5], 0, 64)\n\t} else if strings.HasSuffix(waitFor, \"sec\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64)\n\t\twaitForMilliseconds = waitForMilliseconds * 1000\n\t} else if strings.HasSuffix(waitFor, \"min\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64)\n\t\twaitForMilliseconds = waitForMilliseconds * 60 * 1000\n\t}\n\n\t// Now we seems to be good ...\n\t// First - retrieve the Keycloak URL from Microcks configuration.\n\tmc := connectors.NewMicrocksClient(microcksURL)\n\tkeycloakURL, err := mc.GetKeycloakURL()\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when invoking Microcks client retrieving config: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tvar oauthToken string = \"unauthentifed-token\"\n\tif keycloakURL != \"null\" {\n\t\t// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.\n\t\tkc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret)\n\n\t\toauthToken, err = kc.ConnectAndGetToken()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Got error when invoking Keycloack client: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\t//fmt.Printf(\"Retrieve OAuthToken: %s\", oauthToken)\n\t}\n\n\t// Then - launch the test on Microcks Server.\n\tmc.SetOAuthToken(oauthToken)\n\n\tvar testResultID string\n\ttestResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders)\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when invoking Microcks client creating Test: %s\", err)\n\t\tos.Exit(1)\n\t}\n\t//fmt.Printf(\"Retrieve TestResult ID: %s\", testResultID)\n\n\t// Finally - wait before checking and loop for some time\n\ttime.Sleep(1 * time.Second)\n\n\t// Add 10.000ms to wait time as it's now representing the server timeout.\n\tnow := nowInMilliseconds()\n\tfuture := now + waitForMilliseconds + 10000\n\n\tvar success = false\n\tfor nowInMilliseconds() < future {\n\t\ttestResultSummary, err := mc.GetTestResult(testResultID)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Got error when invoking Microcks client check TestResult: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tsuccess = testResultSummary.Success\n\t\tinProgress := testResultSummary.InProgress\n\t\tfmt.Printf(\"MicrocksClient got status for test \\\"%s\\\" - success: %s, inProgress: %s \\n\", testResultID, fmt.Sprint(success), fmt.Sprint(inProgress))\n\n\t\tif !inProgress {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Println(\"MicrocksTester waiting for 2 seconds before checking again or exiting.\")\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tfmt.Printf(\"Full TestResult details are available here: %s/#/tests/%s \\n\", strings.Split(microcksURL, \"/api\")[0], testResultID)\n\n\tif !success {\n\t\tos.Exit(1)\n\t}\n}", "func TestPrepForExecute(t *testing.T) {\n\n\t// Start by messing things up so that we can tell that PrepForExecute(..) did something\n\tunitTesting = false\n\texecuteError = errors.New(\"this error should get cleared\")\n\n\t// Call our target function with some parameters that nothing else uses\n\tbuf := PrepForExecute(\"TestPrepForExecute\")\n\n\t// Execute the command, collecting output in our buffer\n\tExecute()\n\n\t// Convert the buffer to a string\n\toutput := buf.String()\n\n\t// Check everything out\n\trequire.NotNil(t, executeError, \"there should have been an error\")\n\trequire.Condition(t, func() bool {\n\t\treturn checkForExpectedSTSCallFailure(executeError)\n\t}, \"Error should have complained about nonexistent credentials file or invalid MFA token length\")\n\trequire.Empty(t, output, \"Output for an error condition should have been empty\")\n}", "func Test(t *testing.T, p prog.Program, cases ...Case) {\n\tt.Helper()\n\tfor _, c := range cases {\n\t\tt.Run(strings.Join(c.args, \" \"), func(t *testing.T) {\n\t\t\tt.Helper()\n\t\t\tr := run(p, c.args, c.stdin)\n\t\t\tif r.exitCode != c.want.exitCode {\n\t\t\t\tt.Errorf(\"got exit code %v, want %v\", r.exitCode, c.want.exitCode)\n\t\t\t}\n\t\t\tif !matchOutput(r.stdout, c.want.stdout) {\n\t\t\t\tt.Errorf(\"got stdout %v, want %v\", r.stdout, c.want.stdout)\n\t\t\t}\n\t\t\tif !matchOutput(r.stderr, c.want.stderr) {\n\t\t\t\tt.Errorf(\"got stderr %v, want %v\", r.stderr, c.want.stderr)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestTestComand_Exec_Value(t *testing.T) {\n\t// com := NewTestCommand()\n\n}", "func TestCLI(t *testing.T) {\n\t// parse configuration file 'solar-conf.yaml' in local directory\n\t_, err := util.ReadConfiguration()\n\tif err != nil {\n\t\tfmt.Println(\"unable to read the configuration file\")\n\t\tfmt.Println(err)\n\t}\n\n\t// initialise command line options\n\tutil.ParseCommandLineOptions()\n\n\t// create model\n\tm := model.GetModel()\n \n\t// start the main event loop\n\tengine.StartDispatcher(m)\n\n\t// get the command line interface\n\tshell := cli.Shell(m)\n\n\t// load commands from a file\n\tcmds, err := LoadCommands()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tfmt.Println(\"Executing tests:\")\n\tfmt.Println(\"Nr. Command\")\n\tfmt.Println(\"------------------------------------------------------------\")\n\tfor index, cmd := range cmds {\n\t\t// skip empty command lines\n\t\tif cmd[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// construct command line string\n\t\tcmdline := strings.Join(cmd, \" \")\n\n\t\t// log the command line\n\t\tfmt.Printf(\"%03d %s\\n\", index, cmdline)\n\n\t\t// process\n\t\terr = shell.Process(cmd...)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Command failed: %s\\n%s\", cmdline, err)\n\t\t}\n\t}\n}", "func TestExecuteCmdReader(t *testing.T) {\n\tshell := CmdShell{}\n\tif invalidOutput, _, err := shell.ExecuteCmdReader(invalidCmd); invalidOutput != nil && err == nil {\n\t\tt.Errorf(\"CmdReader didn't error on invalid cmd\")\n\t}\n\n\toutput, _, err := shell.ExecuteCmdReader(validReaderCmd)\n\tif err != nil {\n\t\tt.Errorf(\"Valid CmdReader cmd error'd out %v\", err)\n\t}\n\n\tstdout, stderr := output[0], output[1]\n\n\tstdoutScanner := bufio.NewScanner(stdout)\n\tgo func() {\n\t\tfor stdoutScanner.Scan() {\n\t\t\tif line := stdoutScanner.Text(); line != \"stdout\" {\n\t\t\t\tt.Errorf(\"CmdReader failed, expected %v, got %v\", \"stdout\", line)\n\t\t\t}\n\t\t}\n\t}()\n\n\tstderrScanner := bufio.NewScanner(stderr)\n\tgo func() {\n\t\tfor stderrScanner.Scan() {\n\t\t\tif line := stderrScanner.Text(); line != \"stderr\" {\n\t\t\t\tt.Errorf(\"CmdReader failed, expected %v, got %v\", \"stderr\", line)\n\t\t\t}\n\t\t}\n\t}()\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 (t testCommand) Run() error {\n\tif t.shouldFail {\n\t\treturn errors.New(\"I AM ERROR\")\n\t}\n\treturn nil\n}", "func TestMain(t *testing.T) {\n\tif *systemTestFlag {\n\t\tos.Stdin.Close() // interpreter exits on EOF\n\t\tmain()\n\t}\n}", "func TestRunCommand(t *testing.T) {\n\t// Override execCommand with our fake version\n\texecCommand = fakeExecCommand\n\tdefer func() { execCommand = origExec }()\n\n\t// Define our test command and arguments\n\ttestCommand := \"echo\"\n\ttestArgs := []string{\"pizza\", \"sushi\"}\n\ttestCmd := append([]string{testCommand}, testArgs...)\n\texpectedCmd := fmt.Sprint(testCmd)\n\n\tactualCmd, _ := runCommand(testCommand, testArgs)\n\n\t// Compare the result with our expectations\n\tstructsMatch := reflect.DeepEqual(expectedCmd, actualCmd)\n\n\tif !structsMatch {\n\t\tt.Errorf(\"\\nExpected: %#v\\nReceived: %#v\", expectedCmd, actualCmd)\n\t}\n}", "func TestExecute(t *testing.T) {\n\t// execute := RootCmd.Execute\n\texited := false\n\t// RootCmd.Execute = func(*cobra.Command) error {\n\t// \treturn errors.New(\"mock\")\n\t// }\n\tosExit = func(int) {\n\t\texited = true\n\t}\n\n\tdefer func() {\n\t\t// RootCmd.Execute = execute\n\t\tosExit = os.Exit\n\t}()\n\n\toutErr := new(bytes.Buffer)\n\tRootCmd.SetErr(outErr)\n\tRootCmd.SetArgs([]string{\"--option-that-will-never-be-used\"})\n\tExecute()\n\n\tif !exited {\n\t\tt.Errorf(`Would not have exited on RootCmd execution error`)\n\t}\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 (s *Spec) ExecuteTest(testPath string) []Test {\n\tvar tests []Test\n\n\tswitch s.Entry {\n\tcase \"argv\":\n\t\tif testPath == \"\" {\n\t\t\tpanic(\"Test path is empty\")\n\t\t}\n\t\ttests = s.execArgv(testPath)\n\tcase \"http\":\n\t\ttests = s.execHTTP()\n\tdefault:\n\t\tpanic(fmt.Errorf(\"cannot run test entry through: '%v'\", s.Entry))\n\t}\n\n\treturn tests\n}", "func runTest(test TestCase) TestResult {\n\t// cut = command under test\n\tcut := cmd.NewCommand(test.Command.Cmd)\n\tcut.SetTimeout(test.Command.Timeout)\n\tcut.Dir = test.Command.Dir\n\tfor k, v := range test.Command.Env {\n\t\tcut.AddEnv(k, v)\n\t}\n\n\tif err := cut.Execute(); err != nil {\n\t\tlog.Println(test.Title, \" failed \", err.Error())\n\t\ttest.Result = CommandResult{\n\t\t\tError: err,\n\t\t}\n\n\t\treturn TestResult{\n\t\t\tTestCase: test,\n\t\t}\n\t}\n\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" Command: \", cut.Cmd)\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" Directory: \", cut.Dir)\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" Env: \", cut.Env)\n\n\t// Write test result\n\ttest.Result = CommandResult{\n\t\tExitCode: cut.ExitCode(),\n\t\tStdout: strings.Replace(cut.Stdout(), \"\\r\\n\", \"\\n\", -1),\n\t\tStderr: strings.Replace(cut.Stderr(), \"\\r\\n\", \"\\n\", -1),\n\t}\n\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" ExitCode: \", test.Result.ExitCode)\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" Stdout: \", test.Result.Stdout)\n\tlog.Println(\"title: '\"+test.Title+\"'\", \" Stderr: \", test.Result.Stderr)\n\n\treturn Validate(test)\n}", "func TestExecuteCommand(t *testing.T) {\n\n\tcases := []testCase{\n\t\t{\"message to bee replaced\", \"s/bee/be\", \"\", `message to be replaced`, false},\n\t\t{\"message to bee replaced\", \"s/bee/be\", \"123\", `message to be replaced`, false},\n\t\t{\"what if I typ the word typical\", \"s/typ/type\", \"\", `what if I type the word typical`, true},\n\t\t{\"baaad input\", \"s/bad\", \"\", usage, true},\n\t\t{\"more baaad input\", \"s/baaad/\", \"\", usage, true},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.command, func(t *testing.T) {\n\n\t\t\tc := &plugin.Context{}\n\t\t\tpost := &model.Post{\n\t\t\t\tUserId: \"testUserId\",\n\t\t\t\tMessage: tc.command,\n\t\t\t\tChannelId: \"testChannelId\",\n\t\t\t}\n\n\t\t\tapi := &plugintest.API{}\n\n\t\t\tdefer api.AssertExpectations(t)\n\n\t\t\tconfig := &testAPIConfig{\n\t\t\t\tUser: &model.User{},\n\t\t\t\tPosts: []*model.Post{&model.Post{}},\n\t\t\t\tPost: &model.Post{},\n\t\t\t\tChannel: &model.Channel{},\n\t\t\t}\n\n\t\t\t//needs to test input before setting API expectations\n\t\t\tif _, err := splitAndValidateInput(tc.command); err != nil && tc.shouldFail {\n\t\t\t\tassert.NotNil(t, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsetupAPI(api, config)\n\n\t\t\tp := setupTestPlugin(t, api)\n\n\t\t\tp.OnActivate()\n\n\t\t\treturnedPost, err := p.MessageWillBePosted(c, post)\n\t\t\tassert.Nil(t, returnedPost)\n\t\t\tassert.Equal(t, err, \"plugin.message_will_be_posted.dismiss_post\")\n\t\t})\n\t\tt.Run(tc.command+\" - Replace\", func(t *testing.T) {\n\t\t\toldAndNew, err := splitAndValidateInput(tc.command)\n\t\t\tif err != nil && tc.shouldFail {\n\t\t\t\tassert.NotNil(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.Equal(t, tc.expectedMessage, replace(tc.message, oldAndNew[0], oldAndNew[1]))\n\t\t})\n\t}\n}", "func TestExecute(t *testing.T) {\n\tctx := context.Background()\n\n\t// Clear pre-existing golden files to avoid leaving stale ones around.\n\tif *updateGoldens {\n\t\tfiles, err := filepath.Glob(filepath.Join(*goldensDir, \"*.golden.json\"))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfor _, f := range files {\n\t\t\tif err := os.Remove(f); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\n\ttestCases := []struct {\n\t\tname string\n\t\tflags testsharderFlags\n\t\ttestSpecs []build.TestSpec\n\t\ttestDurations []build.TestDuration\n\t\ttestList []build.TestListEntry\n\t\tmodifiers []testsharder.TestModifier\n\t\tpackageRepos []build.PackageRepo\n\t\taffectedTests []string\n\t}{\n\t\t{\n\t\t\tname: \"no tests\",\n\t\t},\n\t\t{\n\t\t\tname: \"mixed device types\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\thostTestSpec(\"bar\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: 5,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tTotalRuns: 50,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Millisecond,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"affected tests\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic\"),\n\t\t\t\tfuchsiaTestSpec(\"not-affected\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic\", true),\n\t\t\t\ttestListEntry(\"not-affected\", false),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected-hermetic\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"affected nonhermetic tests\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic\"),\n\t\t\t\tfuchsiaTestSpec(\"not-affected\"),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected-nonhermetic\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"target test count\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetTestCount: 2,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo1\"),\n\t\t\t\tfuchsiaTestSpec(\"foo2\"),\n\t\t\t\tfuchsiaTestSpec(\"foo3\"),\n\t\t\t\tfuchsiaTestSpec(\"foo4\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"sharding by time\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: int((4 * time.Minute).Seconds()),\n\t\t\t\tperTestTimeoutSecs: int((10 * time.Minute).Seconds()),\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"slow\"),\n\t\t\t\tfuchsiaTestSpec(\"fast1\"),\n\t\t\t\tfuchsiaTestSpec(\"fast2\"),\n\t\t\t\tfuchsiaTestSpec(\"fast3\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: 2 * time.Second,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: packageURL(\"slow\"),\n\t\t\t\t\tMedianDuration: 5 * time.Minute,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"max shards per env\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\t// Given expected test durations of 4 minutes for each test it's\n\t\t\t\t// impossible to satisfy both the target shard duration and the\n\t\t\t\t// max shards per environment, so the target shard duration\n\t\t\t\t// should effectively be ignored.\n\t\t\t\ttargetDurationSecs: int((5 * time.Minute).Seconds()),\n\t\t\t\tmaxShardsPerEnvironment: 2,\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected1\"),\n\t\t\t\tfuchsiaTestSpec(\"affected2\"),\n\t\t\t\tfuchsiaTestSpec(\"affected3\"),\n\t\t\t\tfuchsiaTestSpec(\"affected4\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected1\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected2\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic1\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic2\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: 4 * time.Minute,\n\t\t\t\t},\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected1\"),\n\t\t\t\tpackageURL(\"affected2\"),\n\t\t\t\tpackageURL(\"affected3\"),\n\t\t\t\tpackageURL(\"affected4\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected1\", true),\n\t\t\t\ttestListEntry(\"affected2\", true),\n\t\t\t\ttestListEntry(\"affected3\", true),\n\t\t\t\ttestListEntry(\"affected4\", true),\n\t\t\t\ttestListEntry(\"unaffected1\", true),\n\t\t\t\ttestListEntry(\"unaffected2\", true),\n\t\t\t\ttestListEntry(\"nonhermetic1\", false),\n\t\t\t\ttestListEntry(\"nonhermetic2\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"hermetic deps\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\thermeticDeps: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t\tpackageRepos: []build.PackageRepo{\n\t\t\t\t{\n\t\t\t\t\tPath: \"pkg_repo1\",\n\t\t\t\t\tBlobs: filepath.Join(\"pkg_repo1\", \"blobs\"),\n\t\t\t\t\tTargets: filepath.Join(\"pkg_repo1\", \"targets.json\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ffx deps\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tffxDeps: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply affected test\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\taffectedTestsMultiplyThreshold: 3,\n\t\t\t\ttargetDurationSecs: int(2 * time.Minute.Seconds()),\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"multiplied-affected-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-test\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Second,\n\t\t\t\t},\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"multiplied-affected-test\"),\n\t\t\t\tpackageURL(\"affected-test\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"multiplied-affected-test\",\n\t\t\t\t\tTotalRuns: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"test list with tags\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"hermetic-test\", true),\n\t\t\t\ttestListEntry(\"nonhermetic-test\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"skip unaffected tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-nonhermetic-test\", false),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\").Name,\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\").Name,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"run all tests if no affected tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-nonhermetic-test\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply unaffected hermetic tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-multiplied-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-multiplied-test\", true),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\").Name,\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"unaffected-hermetic-multiplied-test\",\n\t\t\t\t\tTotalRuns: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"various modifiers\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: 5,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t// default modifier\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 2,\n\t\t\t\t},\n\t\t\t\t// multiplier\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t\t// change maxAttempts (but multiplier takes precedence)\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t\t// change maxAttempts, set affected\n\t\t\t\t{\n\t\t\t\t\tName: \"bar\",\n\t\t\t\t\tAffected: true,\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"foo\", false),\n\t\t\t\ttestListEntry(\"bar\", true),\n\t\t\t\ttestListEntry(\"baz\", false),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Millisecond,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgoldenBasename := strings.ReplaceAll(tc.name, \" \", \"_\") + \".golden.json\"\n\t\t\tgoldenFile := filepath.Join(*goldensDir, goldenBasename)\n\n\t\t\tif *updateGoldens {\n\t\t\t\ttc.flags.outputFile = goldenFile\n\t\t\t} else {\n\t\t\t\ttc.flags.outputFile = filepath.Join(t.TempDir(), goldenBasename)\n\t\t\t}\n\n\t\t\ttc.flags.buildDir = t.TempDir()\n\t\t\tif len(tc.modifiers) > 0 {\n\t\t\t\ttc.flags.modifiersPath = writeTempJSONFile(t, tc.modifiers)\n\t\t\t}\n\t\t\tif len(tc.affectedTests) > 0 {\n\t\t\t\t// Add a newline to the end of the file to test that it still calculates the\n\t\t\t\t// correct number of affected tests even with extra whitespace.\n\t\t\t\ttc.flags.affectedTestsPath = writeTempFile(t, strings.Join(tc.affectedTests, \"\\n\")+\"\\n\")\n\t\t\t}\n\t\t\tif tc.flags.ffxDeps {\n\t\t\t\tsdkManifest := map[string]interface{}{\n\t\t\t\t\t\"atoms\": []interface{}{},\n\t\t\t\t}\n\t\t\t\tsdkManifestPath := filepath.Join(tc.flags.buildDir, \"sdk\", \"manifest\", \"core\")\n\t\t\t\tif err := os.MkdirAll(filepath.Dir(sdkManifestPath), os.ModePerm); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tif err := jsonutil.WriteToFile(sdkManifestPath, sdkManifest); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Write test-list.json.\n\t\t\tif err := jsonutil.WriteToFile(\n\t\t\t\tfilepath.Join(tc.flags.buildDir, testListPath),\n\t\t\t\tbuild.TestList{Data: tc.testList, SchemaID: \"experimental\"},\n\t\t\t); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\twriteDepFiles(t, tc.flags.buildDir, tc.testSpecs)\n\t\t\tfor _, repo := range tc.packageRepos {\n\t\t\t\tif err := os.MkdirAll(filepath.Join(tc.flags.buildDir, repo.Path), 0o700); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm := &fakeModules{\n\t\t\t\ttestSpecs: tc.testSpecs,\n\t\t\t\ttestDurations: tc.testDurations,\n\t\t\t\tpackageRepositories: tc.packageRepos,\n\t\t\t}\n\t\t\tif err := execute(ctx, tc.flags, m); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif !*updateGoldens {\n\t\t\t\twant := readShards(t, goldenFile)\n\t\t\t\tgot := readShards(t, tc.flags.outputFile)\n\t\t\t\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\t\t\t\tt.Errorf(strings.Join([]string{\n\t\t\t\t\t\t\"Golden file mismatch!\",\n\t\t\t\t\t\t\"To fix, run `tools/integration/testsharder/update_goldens.sh\",\n\t\t\t\t\t\tdiff,\n\t\t\t\t\t}, \"\\n\"))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\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}", "func main() {\n cmd.Execute ()\n}", "func (t TestCases) Run(fn func(string) (string, string), hideInput bool) {\n\tfor _, test := range t {\n\t\tpart1, part2 := fn(test.Input)\n\t\tpassedPart1 := part1 == test.ExpectedPart1 || test.ExpectedPart1 == \"\"\n\t\tpassedPart2 := part2 == test.ExpectedPart2 || test.ExpectedPart2 == \"\"\n\t\tpassed := passedPart1 && passedPart2\n\n\t\tif !passed && !hideInput {\n\t\t\tfmt.Println(\"Input \", test.Input)\n\t\t}\n\t\tif !passedPart1 {\n\t\t\tfmt.Println(\" - PART1: \", part1, \" but expected \", test.ExpectedPart1)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif !passedPart2 {\n\t\t\tfmt.Println(\" - PART2: \", part2, \" but expected \", test.ExpectedPart2)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (s *SpecFile) Execute(args []string) error {\n\tinput, err := loadSpec(string(s.Input))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswspec, err := scan.Application(s.BasePath, input, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn writeToFile(swspec, string(s.Output))\n}", "func TestExecute(t *testing.T) {\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\tsc := server.NewMockScheduler(mockCtrl)\n\tsc.EXPECT().ScheduleJob(gomock.Any()).Return(\"testJobID\", nil)\n\n\ts := executionServer{scheduler: sc, stat: stats.NilStatsReceiver()}\n\n\tfs := &fakeExecServer{}\n\n\ta := &remoteexecution.Action{}\n\tactionSha, actionLen, err := scootproto.GetSha256(a)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get sha: %v\", err)\n\t}\n\n\tactionDigest := &remoteexecution.Digest{Hash: actionSha, SizeBytes: actionLen}\n\n\treq := remoteexecution.ExecuteRequest{\n\t\tInstanceName: \"test\",\n\t\tSkipCacheLookup: true,\n\t\tActionDigest: actionDigest,\n\t}\n\n\terr = s.Execute(&req, fs)\n\tif err != nil {\n\t\tt.Fatalf(\"Non-nil error from Execute: %v\", err)\n\t}\n}", "func NewTestCommand(osExit func(int), getOutputManager func() OutputManager) *cobra.Command {\n\n\tctx := context.Background()\n\tcmd := &cobra.Command{\n\t\tUse: \"test <file> [file...]\",\n\t\tShort: \"Test your configuration files using Open Policy Agent\",\n\t\tVersion: fmt.Sprintf(\"Version: %s\\nCommit: %s\\nDate: %s\\n\", constants.Version, constants.Commit, constants.Date),\n\n\t\tRun: func(cmd *cobra.Command, fileList []string) {\n\t\t\tout := getOutputManager()\n\t\t\tif len(fileList) < 1 {\n\t\t\t\tcmd.SilenceErrors = true\n\t\t\t\tlog.G(ctx).Fatal(\"The first argument should be a file\")\n\t\t\t}\n\n\t\t\tif viper.GetBool(\"update\") {\n\t\t\t\tupdate.NewUpdateCommand().Run(cmd, fileList)\n\t\t\t}\n\n\t\t\tcompiler, err := buildCompiler(viper.GetString(\"policy\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.G(ctx).Fatalf(\"Problem building rego compiler: %s\", err)\n\t\t\t}\n\t\t\tfoundFailures := false\n\t\t\tvar configFiles []parser.ConfigDoc\n\t\t\tvar fileType string\n\t\t\tfor _, fileName := range fileList {\n\t\t\t\tvar err error\n\t\t\t\tvar config io.ReadCloser\n\t\t\t\tfileType, err = getFileType(viper.GetString(\"input\"), fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.G(ctx).Errorf(\"Unable to get file type: %v\", err)\n\t\t\t\t\tosExit(1)\n\t\t\t\t}\n\t\t\t\tconfig, err = getConfig(fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.G(ctx).Errorf(\"Unable to open file or read from stdin %s\", err)\n\t\t\t\t\tosExit(1)\n\t\t\t\t}\n\t\t\t\tconfigFiles = append(configFiles, parser.ConfigDoc{\n\t\t\t\t\tReadCloser: config,\n\t\t\t\t\tFilepath: fileName,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconfigManager := parser.NewConfigManager(fileType)\n\t\t\tconfigurations, err := configManager.BulkUnmarshal(configFiles)\n\t\t\tif err != nil {\n\t\t\t\tlog.G(ctx).Errorf(\"Unable to BulkUnmarshal your config files: %v\", err)\n\t\t\t\tosExit(1)\n\t\t\t}\n\n\t\t\tvar res CheckResult\n\t\t\tif viper.GetBool(CombineConfigFlagName) {\n\t\t\t\tres, err = processData(ctx, configurations, compiler)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.G(ctx).Fatalf(\"Problem processing data: %s\", err)\n\t\t\t\t}\n\t\t\t\terr = out.Put(\"Combined-configs (multi-file)\", res)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.G(ctx).Fatalf(\"Problem generating output: %s\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor fileName, config := range configurations {\n\t\t\t\t\tres, err = processData(ctx, config, compiler)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.G(ctx).Fatalf(\"Problem processing data: %s\", err)\n\t\t\t\t\t}\n\t\t\t\t\terr = out.Put(fileName, res)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.G(ctx).Fatalf(\"Problem generating output: %s\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(res.Failures) > 0 || (len(res.Warnings) > 0 && viper.GetBool(\"fail-on-warn\")) {\n\t\t\t\tfoundFailures = true\n\t\t\t}\n\n\t\t\terr = out.Flush()\n\t\t\tif err != nil {\n\t\t\t\tlog.G(ctx).Fatal(err)\n\t\t\t}\n\n\t\t\tif foundFailures {\n\t\t\t\tosExit(1)\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.Flags().BoolP(\"fail-on-warn\", \"\", false, \"return a non-zero exit code if only warnings are found\")\n\tcmd.Flags().BoolP(\"update\", \"\", false, \"update any policies before running the tests\")\n\tcmd.Flags().BoolP(CombineConfigFlagName, \"\", false, \"combine all given config files to be evaluated together\")\n\n\tcmd.Flags().StringP(\"output\", \"o\", \"\", fmt.Sprintf(\"output format for conftest results - valid options are: %s\", validOutputs()))\n\tcmd.Flags().StringP(\"input\", \"i\", \"\", fmt.Sprintf(\"input type for given source, especially useful when using conftest with stdin, valid options are: %s\", parser.ValidInputs()))\n\n\tvar err error\n\tflagNames := []string{\"fail-on-warn\", \"update\", CombineConfigFlagName, \"output\", \"input\"}\n\tfor _, name := range flagNames {\n\t\terr = viper.BindPFlag(name, cmd.Flags().Lookup(name))\n\t\tif err != nil {\n\t\t\tlog.G(ctx).Fatal(\"Failed to bind argument:\", err)\n\t\t}\n\t}\n\n\treturn cmd\n}", "func TestParseInput(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput []string\n\t\texpected []uci.Command\n\t}{\n\t\t{\n\t\t\t\"quit before uci\",\n\t\t\t[]string{\"quit\"},\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t\"uci\",\n\t\t\t[]string{\"uci\", \"quit\"},\n\t\t\t[]uci.Command{uci.CommandUCI{}},\n\t\t},\n\t\t{\n\t\t\t\"isready\",\n\t\t\t[]string{\"uci\", \"isready\", \"quit\"},\n\t\t\t[]uci.Command{uci.CommandUCI{}, uci.CommandIsReady{}},\n\t\t},\n\t\t{\n\t\t\t\"ucinewgame\",\n\t\t\t[]string{\"uci\", \"ucinewgame\", \"quit\"},\n\t\t\t[]uci.Command{uci.CommandUCI{}, uci.CommandNewGame{}},\n\t\t},\n\t\t{\n\t\t\t\"position fen\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\",\n\t\t\t\t\"position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\",\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{},\n\t\t\t\tuci.CommandNewGame{},\n\t\t\t\t&uci.CommandSetPositionFEN{\n\t\t\t\t\tFEN: \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\",\n\t\t\t\t\tMoves: nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"position startpos\",\n\t\t\t[]string{\"uci\", \"ucinewgame\", \"position startpos\", \"quit\"},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{}, &uci.CommandSetStartingPosition{},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"position startpos moves\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\",\n\t\t\t\t\"position startpos moves e2e4 e7e5 g1f3 b8c6 f1b5\", // Ruy López\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{},\n\t\t\t\t&uci.CommandSetStartingPosition{\n\t\t\t\t\tMoves: []chess.FromToPromoter{\n\t\t\t\t\t\tmustParseMove(\"e2e4\"),\n\t\t\t\t\t\tmustParseMove(\"e7e5\"),\n\t\t\t\t\t\tmustParseMove(\"g1f3\"),\n\t\t\t\t\t\tmustParseMove(\"b8c6\"),\n\t\t\t\t\t\tmustParseMove(\"f1b5\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"go depth\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\", \"position startpos\",\n\t\t\t\t\"go depth 123\",\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{}, &uci.CommandSetStartingPosition{},\n\t\t\t\tuci.CommandGoDepth{Plies: 123},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"go nodes\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\", \"position startpos\",\n\t\t\t\t\"go nodes 456\",\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{}, &uci.CommandSetStartingPosition{},\n\t\t\t\tuci.CommandGoNodes{Nodes: 456},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"go time\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\", \"position startpos\",\n\t\t\t\t\"go wtime 60000 btime 120000 winc 1000 binc 2000\",\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{}, &uci.CommandSetStartingPosition{},\n\t\t\t\tuci.CommandGoTime{\n\t\t\t\t\tuci.TimeControl{\n\t\t\t\t\t\tWhiteTime: 1 * time.Minute,\n\t\t\t\t\t\tBlackTime: 2 * time.Minute,\n\t\t\t\t\t\tWhiteIncrement: 1 * time.Second,\n\t\t\t\t\t\tBlackIncrement: 2 * time.Second,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"go infinite\",\n\t\t\t[]string{\n\t\t\t\t\"uci\", \"ucinewgame\", \"position startpos\",\n\t\t\t\t\"go infinite\",\n\t\t\t\t\"quit\",\n\t\t\t},\n\t\t\t[]uci.Command{\n\t\t\t\tuci.CommandUCI{}, uci.CommandNewGame{}, &uci.CommandSetStartingPosition{},\n\t\t\t\tuci.CommandGoInfinite{},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpiper, pipew := io.Pipe()\n\n\t\t\tp, commandch, stopch := uci.NewParser(piper, os.Stdout)\n\t\t\trequire.NotNil(t, p)\n\t\t\trequire.NotNil(t, commandch)\n\t\t\trequire.NotNil(t, stopch)\n\n\t\t\tgo p.ParseInput()\n\n\t\t\tvar commands []uci.Command\n\t\t\tgo func() {\n\t\t\t\tfor cmd := range commandch {\n\t\t\t\t\tcommands = append(commands, cmd)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor _, str := range tt.input {\n\t\t\t\tpipew.Write([]byte(str + \"\\n\"))\n\t\t\t\ttime.Sleep(processing)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.expected, commands)\n\n\t\t\t// should be no more commands, and the channel should be closed\n\t\t\tselect {\n\t\t\tcase cmd, open := <-commandch:\n\t\t\t\tassert.Equal(t, nil, cmd)\n\t\t\t\tassert.False(t, open)\n\t\t\tdefault:\n\t\t\t\tt.Errorf(\"channel is still open\") // closed channel wouldn't block\n\t\t\t}\n\t\t})\n\t}\n}", "func executeGoTestRunner(t *testing.T, expectedLogs []string, unexpectedLogs []string) {\n\tout, _ := exec.Command(\n\t\tpath.Join(runtime.GOROOT(), \"bin\", \"go\"),\n\t\t\"test\",\n\t\t\"../_supervised_in_test/\",\n\t\t\"-v\",\n\t\t\"-run\",\n\t\t\"^(\"+t.Name()+\")$\").CombinedOutput()\n\n\tgoTestOutput := string(out)\n\tribbon := \"------------------ EXTERNAL TEST OUTPUT (\" + t.Name() + \") ------------------\"\n\tdebugMsgOutput := fmt.Sprintln(ribbon, \"\\n\", goTestOutput, \"\\n\", ribbon)\n\n\tfor _, logLine := range expectedLogs {\n\t\trequire.Truef(t, strings.Contains(goTestOutput, logLine), \"log should contain: '%s'\\n\\n%s\", logLine, debugMsgOutput)\n\t}\n\tfor _, logLine := range unexpectedLogs {\n\t\trequire.Falsef(t, strings.Contains(goTestOutput, logLine), \"log should not contain: '%s'\\n\\n%s\", logLine, debugMsgOutput)\n\t}\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 Test_ExecuteVersion(t *testing.T) {\n\tfor _, v := range versiontests {\n\t\tt.Run(v.desc, func(t *testing.T) {\n\t\t\t// fakeout the output for the tests\n\t\t\tout := &testhelpers.FakeOut{}\n\t\t\tcommonOpts := opts.NewCommonOptionsWithTerm(clients.NewFactory(), os.Stdin, out, os.Stderr)\n\n\t\t\t// Set batchmode to true for tests\n\t\t\tcommonOpts.BatchMode = true\n\t\t\tcommand := version.NewCmdVersion(commonOpts)\n\n\t\t\tswitch v.short {\n\t\t\tcase true:\n\t\t\t\tcommand.SetArgs([]string{\"--short\"})\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Git tree state\")\n\t\t\tdefault:\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Git tree state\")\n\t\t\t}\n\t\t})\n\t}\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should load custom secrets rules from provided path [E2E-CLI-048]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-secret.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"fixtures/samples/secrets/regex_rules_48_valid.json\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-secret.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"fixtures/samples/secrets/regex_rules_48_valid.json\",\n\t\t\t\t\t\"--exclude-queries\", \"487f4be7-3fd9-4506-a07a-eae252180c08\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-secret.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"fixtures/samples/secrets/regex_rules_48_empty.json\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform-secret.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"fixtures/samples/secrets/regex_rules_48_invalid_regex.json\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"not-exists-folder\"},\n\n\t\t\t\t[]string{\"scan\", \"--silent\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform.tf\",\n\t\t\t\t\t\"--secrets-regexes-path\", \"samples\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{50, 40, 40, 126, 126, 126},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func Test() {\n\tcom := NewCommands()\n\tf := func() os.Error { \n\t\tprintln(\"Test is successful\")\n\t\treturn nil\n\t}\n\tfb := func(args []string) os.Error { \n\t\tprintln(\"Facebook Friends:\")\n\t\tfor _, t := range args {\n\t\t\tprintln(\"~\"+t)\n\t\t}\n\t\treturn nil\n\t}\n\tcom.AddCommand(\"test\", f)\n\tcom.AddInputCommand(\"fb\", fb)\n\tcom.Parseln(\"test\")\n\tcom.Parseln(\"test:\")\n\tcom.Parseln(\"fb: Steve Brunwasser, Kristen Mills\")\n\tprintln(com.Parseln(\"will fail\").String())\n\tprintln(com.Parseln(\"test: will fail\").String())\n\tprintln(com.Parseln(\"fb:\").String() + \" <-no arguments\")\n\n}", "func TestEmptyInputs(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tvar flagValue int\n\tc.Flags().IntVarP(&flagValue, \"intf\", \"i\", -1, \"\")\n\n\toutput, err := executeCommand(c, \"\", \"-i7\", \"\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif flagValue != 7 {\n\t\tt.Errorf(\"flagValue expected: %v, got %v\", 7, flagValue)\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 TestSubprocessExample_UseWithCommandCollector(t *testing.T) {\n\tres := td.RunTestSteps(t, false, func(ctx context.Context) error {\n\t\tmock := exec.CommandCollector{}\n\t\t// In other code, this would be exec.NewContext(ctx, mock.Run), but that doesn't work with\n\t\t// task driver's setup.\n\t\t// TODO(borenet) Could this be done automatically by teaching taskdriver about RunFn?\n\t\tctx = td.WithExecRunFn(ctx, mock.Run)\n\t\terr := subprocessExample(ctx)\n\t\tif err != nil {\n\t\t\tassert.NoError(t, err)\n\t\t\treturn err\n\t\t}\n\t\trequire.Len(t, mock.Commands(), 2)\n\t\tcmd := mock.Commands()[0]\n\t\tassert.Equal(t, \"llamasay\", cmd.Name)\n\t\tassert.Equal(t, []string{\"hello\", \"world\"}, cmd.Args)\n\n\t\tcmd = mock.Commands()[1]\n\t\tassert.Equal(t, \"bearsay\", cmd.Name)\n\t\tassert.Equal(t, []string{\"good\", \"night\", \"moon\"}, cmd.Args)\n\t\treturn nil\n\t})\n\trequire.Empty(t, res.Errors)\n\trequire.Empty(t, res.Exceptions)\n}", "func ExecTest() {\n\tHelloTest()\n\n\tVarTest()\n\tEnumTest()\n\n\tOpTestArithmetic()\n\tOpTestRelation()\n\tOpTestBoolean()\n\tOpTestBit()\n\tOpTestAssign()\n\tOpTestPriority()\n\tOpTestOther()\n\n\tLoopTest()\n\n\tArrayOneDimTest()\n\tArrayTwoDimTest()\n\n\tPointerTest()\n\tPtrArrayTest()\n\tPtr2PtrTest()\n\tPtrParamTest()\n\n\tFuncTest()\n\tFuncArrayParamTest()\n\tFuncMultiReturnTest()\n\tFuncRecurTest()\n\tFuncClosureTest()\n\n\tRangeTest()\n\tStructTest()\n\tSliceTest()\n\tTypeCastTest()\n\tMapTest()\n\n\tInterfaceTest()\n\n\tMethodTest()\n\tErrorTest()\n}", "func Execute() {\n\t// cfg contains tenant related information, e.g. `travel0-dev`,\n\t// `travel0-prod`. some of its information can be sourced via:\n\t// 1. env var (e.g. AUTH0_API_KEY)\n\t// 2. global flag (e.g. --api-key)\n\t// 3. JSON file (e.g. api_key = \"...\" in ~/.config/auth0/config.json)\n\tcli := &cli{\n\t\trenderer: display.NewRenderer(),\n\t\ttracker: analytics.NewTracker(),\n\t}\n\n\trootCmd := buildRootCmd(cli)\n\n\trootCmd.SetUsageTemplate(namespaceUsageTemplate())\n\taddPersistentFlags(rootCmd, cli)\n\taddSubcommands(rootCmd, cli)\n\n\t// TODO(cyx): backport this later on using latest auth0/v5.\n\t// rootCmd.AddCommand(actionsCmd(cli))\n\t// rootCmd.AddCommand(triggersCmd(cli))\n\n\tdefer func() {\n\t\tif v := recover(); v != nil {\n\t\t\terr := fmt.Errorf(\"panic: %v\", v)\n\n\t\t\t// If we're in development mode, we should throw the\n\t\t\t// panic for so we have less surprises. For\n\t\t\t// non-developers, we'll swallow the panics.\n\t\t\tif instrumentation.ReportException(err) {\n\t\t\t\tfmt.Println(panicMessage)\n\t\t\t} else {\n\t\t\t\tpanic(v)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// platform specific terminal initialization:\n\t// this should run for all commands,\n\t// for most of the architectures there's no requirements:\n\tansi.InitConsole()\n\n\tcancelCtx := contextWithCancel()\n\tif err := rootCmd.ExecuteContext(cancelCtx); err != nil {\n\t\tcli.renderer.Heading(\"error\")\n\t\tcli.renderer.Errorf(err.Error())\n\n\t\tinstrumentation.ReportException(err)\n\t\tos.Exit(1)\n\t}\n\n\ttimeoutCtx, cancel := context.WithTimeout(cancelCtx, 3*time.Second)\n\t// defers are executed in LIFO order\n\tdefer cancel()\n\tdefer cli.tracker.Wait(timeoutCtx) // No event should be tracked after this has run, or it will panic e.g. in earlier deferred functions\n}", "func Command() *cobra.Command {\n\tvar cmd *cobra.Command\n\tvar testCase string\n\tvar fileName, gitBranch string\n\tvar registryAccess, failOnly, removeColor, manifestValidate, manifestMutate, detailedResults bool\n\tcmd = &cobra.Command{\n\t\tUse: \"test <path_to_folder_Containing_test.yamls> [flags]\\n kyverno test <path_to_gitRepository_with_dir> --git-branch <branchName>\\n kyverno test --manifest-mutate > kyverno-test.yaml\\n kyverno test --manifest-validate > kyverno-test.yaml\",\n\t\t// Args: cobra.ExactArgs(1),\n\t\tShort: \"Run tests from directory.\",\n\t\tLong: longHelp,\n\t\tExample: exampleHelp,\n\t\tRunE: func(cmd *cobra.Command, dirPath []string) (err error) {\n\t\t\tcolor.InitColors(removeColor)\n\t\t\tdefer func() {\n\t\t\t\tif err != nil {\n\t\t\t\t\tif !sanitizederror.IsErrorSanitized(err) {\n\t\t\t\t\t\tlog.Log.Error(err, \"failed to sanitize\")\n\t\t\t\t\t\terr = fmt.Errorf(\"internal error\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif manifestMutate {\n\t\t\t\tmanifest.PrintMutate()\n\t\t\t} else if manifestValidate {\n\t\t\t\tmanifest.PrintValidate()\n\t\t\t} else {\n\t\t\t\tstore.SetRegistryAccess(registryAccess)\n\t\t\t\t_, err = testCommandExecute(dirPath, fileName, gitBranch, testCase, failOnly, false, detailedResults)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Log.V(3).Info(\"a directory is required\")\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().StringVarP(&fileName, \"file-name\", \"f\", \"kyverno-test.yaml\", \"test filename\")\n\tcmd.Flags().StringVarP(&gitBranch, \"git-branch\", \"b\", \"\", \"test github repository branch\")\n\tcmd.Flags().StringVarP(&testCase, \"test-case-selector\", \"t\", \"\", `run some specific test cases by passing a string argument in double quotes to this flag like - \"policy=<policy_name>, rule=<rule_name>, resource=<resource_name\". The argument could be any combination of policy, rule and resource.`)\n\tcmd.Flags().BoolVar(&manifestMutate, \"manifest-mutate\", false, \"prints out a template test manifest for a mutate policy\")\n\tcmd.Flags().BoolVar(&manifestValidate, \"manifest-validate\", false, \"prints out a template test manifest for a validate policy\")\n\tcmd.Flags().BoolVar(&registryAccess, \"registry\", false, \"If set to true, access the image registry using local docker credentials to populate external data\")\n\tcmd.Flags().BoolVar(&failOnly, \"fail-only\", false, \"If set to true, display all the failing test only as output for the test command\")\n\tcmd.Flags().BoolVar(&removeColor, \"remove-color\", false, \"Remove any color from output\")\n\tcmd.Flags().BoolVar(&detailedResults, \"detailed-results\", false, \"If set to true, display detailed results\")\n\treturn cmd\n}", "func (t *Test) Run() error {\n\tfor _, cmd := range t.cmds {\n\t\t// TODO(fabxc): aggregate command errors, yield diffs for result\n\t\t// comparison errors.\n\t\tif err := t.exec(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func testScan() {\n\tlog.Println(\"Starting...\")\n\tp := rc.NewProcess(\"127.0.0.1:8081\")\n\tif err := p.Start(syncthingBin, \"-home\", homeDir, \"-no-browser\"); err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer p.Stop()\n\n\twallTime := awaitScanComplete(p)\n\n\treport(p, wallTime)\n}", "func init() { //nolint\n\ttestSample := TestCase{\n\t\tName: \"should hide the progress bar in the CLI [E2E-CLI-009]\",\n\t\tArgs: args{\n\t\t\tArgs: []cmdArgs{\n\t\t\t\t[]string{\"scan\", \"-q\", \"../assets/queries\", \"-p\", \"fixtures/samples/terraform.tf\", \"--no-progress\"},\n\t\t\t},\n\t\t},\n\t\tWantStatus: []int{50},\n\t\tValidation: func(outputText string) bool {\n\t\t\tgetProgressRegex := \"Executing queries:\"\n\t\t\tmatch, _ := regexp.MatchString(getProgressRegex, outputText)\n\t\t\t// if not found -> the the test was successful\n\t\t\treturn !match\n\t\t},\n\t}\n\n\tTests = append(Tests, testSample)\n}", "func (e *bombardExecutor) ExecuteTest() error {\n\tgenesisClient := e.normalClients[0]\n\tsecondaryClients := make([]*helpers.RPCWorkFlowRunner, len(e.normalClients)-1)\n\txChainAddrs := make([]string, len(e.normalClients)-1)\n\tfor i, client := range e.normalClients[1:] {\n\t\tsecondaryClients[i] = helpers.NewRPCWorkFlowRunner(\n\t\t\tclient,\n\t\t\tapi.UserPass{Username: createRandomString(), Password: createRandomString()},\n\t\t\te.acceptanceTimeout,\n\t\t)\n\t\txChainAddress, _, err := secondaryClients[i].CreateDefaultAddresses()\n\t\tif err != nil {\n\t\t\treturn stacktrace.Propagate(err, \"Failed to create default addresses for client: %d\", i)\n\t\t}\n\t\txChainAddrs[i] = xChainAddress\n\t}\n\n\tgenesisUser := api.UserPass{Username: createRandomString(), Password: createRandomString()}\n\thighLevelGenesisClient := helpers.NewRPCWorkFlowRunner(\n\t\tgenesisClient,\n\t\tgenesisUser,\n\t\te.acceptanceTimeout,\n\t)\n\n\tif _, err := highLevelGenesisClient.ImportGenesisFunds(); err != nil {\n\t\treturn stacktrace.Propagate(err, \"Failed to fund genesis client.\")\n\t}\n\taddrs, err := genesisClient.XChainAPI().ListAddresses(genesisUser)\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"Failed to get genesis client's addresses\")\n\t}\n\tif len(addrs) != 1 {\n\t\treturn stacktrace.NewError(\"Found unexecpted number of addresses for genesis client: %d\", len(addrs))\n\t}\n\tgenesisAddress := addrs[0]\n\tlogrus.Infof(\"Imported genesis funds at address: %s\", genesisAddress)\n\n\t// Fund X Chain Addresses enough to issue [numTxs]\n\tseedAmount := (e.numTxs + 1) * e.txFee\n\tif err := highLevelGenesisClient.FundXChainAddresses(xChainAddrs, seedAmount); err != nil {\n\t\treturn stacktrace.Propagate(err, \"Failed to fund X Chain Addresses for Clients\")\n\t}\n\tlogrus.Infof(\"Funded X Chain Addresses with seedAmount %v.\", seedAmount)\n\n\tcodec, err := createXChainCodec()\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"Failed to initialize codec.\")\n\t}\n\tutxoLists := make([][]*avax.UTXO, len(secondaryClients))\n\tfor i, client := range secondaryClients {\n\t\t// Each address should have [e.txFee] remaining after sending [numTxs] and paying the fixed fee each time\n\t\tif err := client.VerifyXChainAVABalance(xChainAddrs[i], seedAmount); err != nil {\n\t\t\treturn stacktrace.Propagate(err, \"Failed to verify X Chain Balane for Client: %d\", i)\n\t\t}\n\t\tutxosBytes, _, err := genesisClient.XChainAPI().GetUTXOs([]string{xChainAddrs[i]}, 10, \"\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tutxos := make([]*avax.UTXO, len(utxosBytes))\n\t\tfor i, utxoBytes := range utxosBytes {\n\t\t\tutxo := &avax.UTXO{}\n\t\t\t_, err := codec.Unmarshal(utxoBytes, utxo)\n\t\t\tif err != nil {\n\t\t\t\treturn stacktrace.Propagate(err, \"Failed to unmarshal utxo bytes.\")\n\t\t\t}\n\t\t\tutxos[i] = utxo\n\t\t}\n\t\tutxoLists[i] = utxos\n\t\tlogrus.Infof(\"Decoded %d UTXOs\", len(utxos))\n\t}\n\tlogrus.Infof(\"Verified X Chain Balances and retrieved UTXOs.\")\n\n\t// Create a string of consecutive transactions for each secondary client to send\n\tprivateKeys := make([]*crypto.PrivateKeySECP256K1R, len(secondaryClients))\n\ttxLists := make([][][]byte, len(secondaryClients))\n\ttxIDLists := make([][]ids.ID, len(secondaryClients))\n\tfor i, client := range e.normalClients[1:] {\n\t\tutxo := utxoLists[i][0]\n\t\tpkStr, err := client.XChainAPI().ExportKey(secondaryClients[i].User(), xChainAddrs[i])\n\t\tif err != nil {\n\t\t\treturn stacktrace.Propagate(err, \"Failed to export key.\")\n\t\t}\n\n\t\tif !strings.HasPrefix(pkStr, constants.SecretKeyPrefix) {\n\t\t\treturn fmt.Errorf(\"private key missing %s prefix\", constants.SecretKeyPrefix)\n\t\t}\n\t\ttrimmedPrivateKey := strings.TrimPrefix(pkStr, constants.SecretKeyPrefix)\n\t\tpkBytes, err := formatting.Decode(formatting.CB58, trimmedPrivateKey)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"problem parsing private key: %w\", err)\n\t\t}\n\n\t\tfactory := crypto.FactorySECP256K1R{}\n\t\tskIntf, err := factory.ToPrivateKey(pkBytes)\n\t\tsk := skIntf.(*crypto.PrivateKeySECP256K1R)\n\t\tprivateKeys[i] = sk\n\n\t\tlogrus.Infof(\"Creating string of %d transactions\", e.numTxs)\n\t\ttxs, txIDs, err := CreateConsecutiveTransactions(utxo, e.numTxs, seedAmount, e.txFee, sk)\n\t\tif err != nil {\n\t\t\treturn stacktrace.Propagate(err, \"Failed to create transaction list.\")\n\t\t}\n\t\ttxLists[i] = txs\n\t\ttxIDLists[i] = txIDs\n\t}\n\n\twg := sync.WaitGroup{}\n\tissueTxsAsync := func(runner *helpers.RPCWorkFlowRunner, txList [][]byte) {\n\t\tif err := runner.IssueTxList(txList); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\twg.Done()\n\t}\n\n\tstartTime := time.Now()\n\tlogrus.Infof(\"Beginning to issue transactions...\")\n\tfor i, client := range secondaryClients {\n\t\twg.Add(1)\n\t\tissueTxsAsync(client, txLists[i])\n\t}\n\twg.Wait()\n\n\tduration := time.Since(startTime)\n\tlogrus.Infof(\"Finished issuing transaction lists in %v seconds.\", duration.Seconds())\n\tfor _, txIDs := range txIDLists {\n\t\tif err := highLevelGenesisClient.AwaitXChainTxs(txIDs...); err != nil {\n\t\t\tstacktrace.Propagate(err, \"Failed to confirm transactions.\")\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Confirmed all issued transactions.\")\n\n\treturn nil\n}", "func CheckMainPuzzleSolution(t *testing.T, expect1, expect2 int) {\n\t// Run the puzzle driver.\n\tcmd := exec.Command(\"go\", \"run\", \"main.go\")\n\n\t// Fetch the output written to the console.\n\traw, err := cmd.CombinedOutput()\n\trequire.NoError(t, err)\n\toutput := string(raw)\n\n\t// Write puzzle output to the console via test object. Will only be shown\n\t// if the test fails. Leading newline for nice formatting.\n\tt.Log(string(linefeed) + output)\n\n\t// The test output should only have two lines, if nothing fails.\n\toutput = strings.TrimRight(output, string(linefeed)) // remove trailing \\n\n\tlines := strings.Split(output, string(linefeed))\n\trequire.Len(t, lines, 2, \"puzzle driver ought to only write two lines\")\n\n\t// Check each puzzle solution to make sure it is correct.\n\tvar ok int\n\tvar actual1, actual2 int\n\n\tok, err = fmt.Sscanf(lines[0], \"Part one answer is: %d\", &actual1)\n\trequire.NoError(t, err, \"failed to scan part one\")\n\trequire.Equal(t, 1, ok, \"no answer value for part one could be scanned\")\n\tassert.Equal(t, expect1, actual1, \"part one answer is incorrect\")\n\n\tok, err = fmt.Sscanf(lines[1], \"Part two answer is: %d\", &actual2)\n\trequire.NoError(t, err, \"failed to scan part two\")\n\trequire.Equal(t, 1, ok, \"no answer value for part two could be scanned\")\n\tassert.Equal(t, expect2, actual2, \"part two answer is incorrect\")\n}", "func executeScript(pkg *ast.Package) (string, string, error) {\n\ttestPkg, err := inPlaceTestGen(pkg)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrap(err, \"error during test generation\")\n\t}\n\n\tquerier := querytest.NewQuerier()\n\tc := lang.FluxCompiler{\n\t\tQuery: ast.Format(testPkg),\n\t}\n\n\tr, err := querier.C.Query(context.Background(), c)\n\tif err != nil {\n\t\tfmt.Println(ast.Format(testPkg))\n\t\treturn \"\", \"\", errors.Wrap(err, \"error during compilation, check your script and retry\")\n\t}\n\tdefer r.Done()\n\tresults, ok := <-r.Ready()\n\tif !ok {\n\t\treturn \"\", \"\", errors.Wrap(r.Err(), \"error retrieving query result\")\n\t}\n\n\tvar diffBuf, resultBuf bytes.Buffer\n\t// encode diff if present\n\tif diff, in := results[\"diff\"]; in {\n\t\tif err := diff.Tables().Do(func(tbl flux.Table) error {\n\t\t\t_, _ = execute.NewFormatter(tbl, nil).WriteTo(&diffBuf)\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\t// do not return diff error, but show it\n\t\t\tfmt.Fprintln(os.Stderr, errors.Wrap(err, \"error while running test script\"))\n\t\t}\n\t}\n\n\tvar aee *testing.AssertEqualsError\n\tenc := csv.NewResultEncoder(csv.DefaultEncoderConfig())\n\t// encode test result if present\n\tif tr, in := results[\"_test_result\"]; in {\n\t\tif _, err := enc.Encode(&resultBuf, tr); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, errors.Wrap(err, \"encoding error while running test script\"))\n\t\t}\n\t} else {\n\t\t// cannot use MultiResultEncoder, because it encodes errors, but I need that\n\t\t// errors to assert their type.\n\t\tfmt.Fprintln(os.Stderr, \"This test doesn't use the test framework, using every result produced as output data.\")\n\t\tfmt.Fprintf(os.Stderr, \"The tool will check for assertEquals errors.\\n\\n\")\n\t\tfor _, r := range results {\n\t\t\tif _, err := enc.Encode(&resultBuf, r); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, errors.Wrap(err, \"encoding error while running test script\"))\n\t\t\t\tcause := errors.Cause(err)\n\t\t\t\tif e, ok := cause.(*testing.AssertEqualsError); ok {\n\t\t\t\t\taee = e\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdiff := diffBuf.String()\n\tif aee != nil && len(diff) == 0 {\n\t\t// populate diff because there was an assertion error\n\t\t// the caller should know there was a difference, indeed.\n\t\tdiff = aee.Error()\n\t}\n\n\treturn resultBuf.String(), diff, nil\n}", "func Execute() {\n\tkingpin.Version(\"0.0.1\")\n\tkingpin.Parse()\n\n\tcolor.Red(title)\n\tcolor.Yellow(subTitle)\n\n\ts := spinner.New(spinner.CharSets[21], 100*time.Millisecond)\n\ts.Start()\n\tdefer s.Stop()\n\tds := scanner.New()\n\tstart, end, err := ports.ConvertPortRange(*portRange)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkingpin.Parse()\n\n\t// Scanner\n\tds.Target(*ip)\n\tds.SetPrinter(&printer.StdPrinter{})\n\tds.Start(start, end)\n}", "func Execute(logger *zap.Logger, svcName, ver string) {\n\tvar (\n\t\tfileName = \"price_rules.json\"\n\t\trootCmd = &cobra.Command{\n\t\t\tUse: \"Checkout\",\n\t\t\tShort: \"CheckoutTweet Test\",\n\t\t\tLong: `This is supermarket checkout page`,\n\t\t\tVersion: ver,\n\t\t\t// Pre Run will set PriceRules so we can all priceRule set before the execution\n\t\t\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\truleFile, err := os.Open(fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Fatal(\"Failed to Open Price Rules file : \", zap.Error(err))\n\t\t\t\t}\n\t\t\t\tpriceRulesData, _ := ioutil.ReadAll(ruleFile)\n\t\t\t\terr = json.Unmarshal(priceRulesData, &checkout.PriceRules)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Fatal(\"Failed to decode Json Data : \", zap.Error(err))\n\t\t\t\t}\n\t\t\t},\n\t\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\t// Scan the product input\n\t\t\t\t// This can be params/ Here using scanf to enter the value from user\n\t\t\t\tfor {\n\t\t\t\t\tvar skuName string\n\t\t\t\t\tfmt.Println(\"Please enter Product SKU / exit if done\")\n\t\t\t\t\tfmt.Scanf(\"%s\", &skuName)\n\t\t\t\t\tif skuName == \"exit\" {\n\t\t\t\t\t\ttotal, err := checkout.CalculateTotal()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogger.Error(\"Error to calculate total\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Println(\"Total Amount : \", total)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\t_, checkSku := checkout.IsSkuExist(skuName)\n\t\t\t\t\tif !checkSku {\n\t\t\t\t\t\tfmt.Println(\"Please enter Valid SKU\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcheckout.Scan(logger, skuName)\n\t\t\t\t}\n\n\t\t\t},\n\t\t}\n\t)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogger.Fatal(\"failed to execute command\", zap.Error(err))\n\t}\n\n}", "func (c *cmdVoteTestSetup) Execute(args []string) error {\n\t// Setup vote parameters\n\tvar (\n\t\tvotes uint32 = 10\n\t\tduration = defaultDuration\n\t\tquorum = defaultQuorum\n\t\tpassing = defaultPassing\n\t)\n\tif c.Votes > 0 {\n\t\tvotes = c.Votes\n\t}\n\tif c.Duration > 0 {\n\t\tduration = c.Duration\n\t}\n\tif c.Quorum != nil {\n\t\tquorum = *c.Quorum\n\t}\n\tif c.Passing != 0 {\n\t\tpassing = c.Passing\n\t}\n\n\t// We don't want the output of individual commands printed.\n\tcfg.Verbose = false\n\tcfg.RawJSON = false\n\tcfg.Silent = true\n\n\t// Verify the the provided login credentials are for an admin.\n\tadmin := user{\n\t\tEmail: c.Args.AdminEmail,\n\t\tPassword: c.Args.AdminPassword,\n\t}\n\terr := userLogin(admin)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to login admin: %v\", err)\n\t}\n\tlr, err := client.Me()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !lr.IsAdmin {\n\t\treturn fmt.Errorf(\"provided user is not an admin\")\n\t}\n\tadmin.Username = lr.Username\n\n\t// Verify that the paywall is disabled\n\tpolicyWWW, err := client.Policy()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif policyWWW.PaywallEnabled {\n\t\tfmt.Printf(\"WARN: politeiawww paywall is not disabled\\n\")\n\t}\n\n\t// Setup votes\n\tfor i := 0; i < int(votes); i++ {\n\t\ts := fmt.Sprintf(\"Starting voting period on proposal %v/%v\", i+1, votes)\n\t\tprintInPlace(s)\n\n\t\t// Create a public proposal\n\t\tr, err := proposalPublic(admin, admin, &proposalOpts{\n\t\t\tRandom: true,\n\t\t\tRandomImages: false,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttoken := r.CensorshipRecord.Token\n\n\t\t// Authorize vote\n\t\terr = voteAuthorize(admin, token)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Start vote\n\t\terr = voteStart(admin, token, duration, quorum, passing, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Printf(\"\\n\")\n\n\treturn nil\n}", "func main() {\n\tflag.Usage = usage\n\tflag.Parse()\n\n\t// if *fHelp {\n\t// \tusage()\n\t// \tos.Exit(0)\n\t// }\n\n\t// r := newRunner(os.Stdin)\n\t// done := make(chan error)\n\n\t// go r.process(os.Stdout, done)\n\n\t// err := <-done\n\n\t// if err != nil {\n\t// \tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t// \tos.Exit(1)\n\t// }\n}", "func Test(t *testing.T, command Runner, testCases []Case) {\n\tt.Helper()\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.Name, func(t *testing.T) {\n\t\t\tt.Helper() // TODO: make Helper working for subtests: issue #24128\n\n\t\t\tstdout := &bytes.Buffer{}\n\t\t\tstderr := &bytes.Buffer{}\n\n\t\t\tcommand.SetStdout(stdout)\n\t\t\tcommand.SetStderr(stderr)\n\n\t\t\tm := newMatch(t, tc.wantFail)\n\n\t\t\tif tc.WantFile != \"\" {\n\t\t\t\tif !m.removeFile(tc.WantFile) {\n\t\t\t\t\ttc.WantFile = \"\" // stop testing File match\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar gotErr string\n\t\t\tgotPanic := m.run(func() {\n\t\t\t\tif err := command.Run(tc.Args); err != nil {\n\t\t\t\t\tgotErr = err.Error()\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tif tc.WantFile != \"\" {\n\t\t\t\tif gotFile, ext, ok := m.getFile(tc.WantFile); ok {\n\t\t\t\t\tm.match(\"File golden\"+ext, gotFile, \"golden\"+ext)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm.match(\"WantStdout\", stdout.String(), tc.WantStdout)\n\t\t\tm.match(\"WantStderr\", stderr.String(), tc.WantStderr)\n\t\t\tm.match(\"WantPanic\", gotPanic, tc.WantPanic)\n\t\t\tm.match(\"WantErr\", gotErr, tc.WantErr)\n\t\t\tm.equal(\"WantExitCode\", command.ExitCode(), tc.WantExitCode)\n\n\t\t\tm.done()\n\t\t})\n\t}\n}", "func (z *Zest) Run() error {\n\treturn z.cli.Run(os.Args)\n}", "func (c *Command) Run(args []string) {\n\tflag.StringVar(&c.Filter, \"f\", \"\", \"regexp to filter tests by name\")\n\tflag.BoolVar(&c.Verbose, \"v\", false, \"print all test names\")\n\tcheck(flag.CommandLine.Parse(args))\n\targs = flag.Args()\n\n\tif len(args) == 0 {\n\t\targs = []string{\".\"}\n\t}\n\n\tokPath, err := util.OKPath()\n\tcheck(err)\n\n\tfor _, arg := range args {\n\t\tpackageName := util.PackageNameFromPath(okPath, arg)\n\t\tif arg == \".\" {\n\t\t\tpackageName = \".\"\n\t\t}\n\t\tanonFunctionName := 0\n\t\tf, _, errs := compiler.Compile(okPath, packageName, true,\n\t\t\t&anonFunctionName, false)\n\t\tutil.CheckErrorsWithExit(errs)\n\n\t\tm := vm.NewVM(\"no-package\")\n\t\tstartTime := time.Now()\n\t\tcheck(m.LoadFile(f))\n\t\terr := m.RunTests(c.Verbose, regexp.MustCompile(c.Filter), packageName)\n\t\telapsed := time.Since(startTime).Milliseconds()\n\t\tcheck(err)\n\n\t\tassertWord := pluralise(\"assert\", m.TotalAssertions)\n\t\tif m.TestsFailed > 0 {\n\t\t\tfmt.Printf(\"%s: %d failed %d passed %d %s (%d ms)\\n\",\n\t\t\t\tpackageName, m.TestsFailed, m.TestsPass,\n\t\t\t\tm.TotalAssertions, assertWord, elapsed)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s: %d passed %d %s (%d ms)\\n\",\n\t\t\t\tpackageName, m.TestsPass,\n\t\t\t\tm.TotalAssertions, assertWord, elapsed)\n\t\t}\n\n\t\tif m.TestsFailed > 0 {\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func TestHiddenCommandExecutes(t *testing.T) {\n\n\t// ensure that outs does not already equal what the command will be setting it\n\t// to, if it did this test would not actually be testing anything...\n\tif outs == \"hidden\" {\n\t\tt.Errorf(\"outs should NOT EQUAL hidden\")\n\t}\n\n\tcmdHidden.Execute()\n\n\t// upon running the command, the value of outs should now be 'hidden'\n\tif outs != \"hidden\" {\n\t\tt.Errorf(\"Hidden command failed to run!\")\n\t}\n}", "func Execute(main *cobra.Command) {\n\t// If we were invoked via a multicall entrypoint run it instead.\n\t// TODO(marineam): should we figure out a way to initialize logging?\n\texec.MaybeExec()\n\n\tmain.AddCommand(versionCmd)\n\n\t// TODO(marineam): pflags defines the Value interface differently,\n\t// update capnslog accordingly...\n\tmain.PersistentFlags().Var(&logLevel, \"log-level\",\n\t\t\"Set global log level.\")\n\tmain.PersistentFlags().BoolVarP(&logVerbose, \"verbose\", \"v\", false,\n\t\t\"Alias for --log-level=INFO\")\n\tmain.PersistentFlags().BoolVarP(&logDebug, \"debug\", \"d\", false,\n\t\t\"Alias for --log-level=DEBUG\")\n\n\tWrapPreRun(main, func(cmd *cobra.Command, args []string) error {\n\t\tstartLogging(cmd)\n\t\treturn nil\n\t})\n\n\tif err := main.Execute(); err != nil {\n\t\t// If this isn't a warn:true test failure then go ahead and die\n\t\tif err != kola.ErrWarnOnTestFail {\n\t\t\tplog.Fatal(err)\n\t\t}\n\t\t// Now check if the user wants exit code 77 on warn:true test fail\n\t\t// If they do then we'll exit 77. If they don't we'll do nothing\n\t\t// and drop out to the os.Exit(0)\n\t\tif kola.Options.UseWarnExitCode77 {\n\t\t\tplog.Warning(err)\n\t\t\tos.Exit(77)\n\t\t}\n\t}\n\tos.Exit(0)\n}", "func TestRunCommands(t *testing.T) {\n\n\t// Read the user structure from the test file\n\tusr, _ := myusr.Current()\n\tusers := configuration.ReadUsersYAML(usr.HomeDir + \"/CONFIG/TOD/users/users.yaml\")\n\n\t// configuration\n\tconf := &configuration.Config{}\n\tconf.Port = 22\n\tconf.Protocol = \"tcp\"\n\tconf.Timeout = 10\n\tconf.LogCommand = \"/tmp\"\n\tconf.CPUMax = 25.0\n\tconf.MemoryMax = 30.0\n\tconf.ExcludeLoaded = true\n\tconf.WorkTimer = true\n\tconf.WorkTime = 120\n\tconf.HostsMax = 5\n\tconf.Stdin = true\n\n\t// read command from the example configuration\n\tcmds := configuration.UsersToDispatcher(*users)\n\n\t// replicate the command in the example\n\tcommands := make([]commands.Command, 121)\n\tfor i := range commands {\n\t\tcommands[i] = cmds[0]\n\t}\n\n\t// Create the list of commands and hosts\n\thsts := new(host.Hosts)\n\thosts := make([]*host.Host, len(hostnames))\n\tfor i, hst := range hostnames {\n\t\t// Create the host object in the slice\n\t\thosts[i] = &host.Host{\n\t\t\tHostname: hst,\n\t\t}\n\t}\n\thsts.Hosts = hosts\n\n\t// display\n\tformatter.ColoredPrintln(\n\t\tformatter.Blue,\n\t\tfalse,\n\t\t\"All data initialized !\",\n\t)\n\n\t// Create dispatcher\n\tdispatcher := New(conf, hsts)\n\n\t// Dispatch commands on hosts\n\thsts.Dispatcher(\n\t\tcommands,\n\t\tconf.HostsMax,\n\t\ttrue,\n\t)\n\n\t// display\n\tformatter.ColoredPrintln(\n\t\tformatter.Blue,\n\t\tfalse,\n\t\t\"Dispatching the commands on hosts done !\",\n\t)\n\n\t// Run commands in concurrent\n\tdispatcher.RunCommands(len(commands))\n\n\t// display\n\tformatter.ColoredPrintln(\n\t\tformatter.Blue,\n\t\tfalse,\n\t\t\"Commands done !\",\n\t)\n}", "func Execute(apiCheckHTTP func(string, bool, bool, string, int, string, string, string, string) (string, int)) int {\n\tvar redirect, insecure bool\n\tvar exitCode, timeout int\n\tvar url, format, path, expectedValue, expression, host string\n\n\tvar rootCmd = &cobra.Command{\n\t\tUse: \"check_http\",\n\t\tShort: \"Check the response code of an http request.\",\n\t\tLong: `Perform an HTTP get request and assert whether it is OK, warning or critical.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.ParseFlags(os.Args)\n\t\t\tmsg, retval := apiCheckHTTP(url, redirect, insecure, host, timeout, format, path, expectedValue, expression)\n\n\t\t\tfmt.Println(msg)\n\t\t\texitCode = retval\n\t\t},\n\t}\n\n\tinitcmd.AddVersionCommand(rootCmd)\n\n\trootCmd.Flags().StringVarP(&url, \"url\", \"u\", \"http://127.0.0.1\", \"the URL to check\")\n\trootCmd.Flags().BoolVarP(&redirect, \"redirect\", \"r\", false, \"follow redirects?\")\n\trootCmd.Flags().BoolVarP(&insecure, \"insecure\", \"k\", false, \"do not validate certificate\")\n\trootCmd.Flags().IntVarP(&timeout, \"timeout\", \"t\", 15, \"timeout in seconds\")\n\trootCmd.Flags().StringVarP(&host, \"host\", \"H\", \"\", \"The host header for the request\")\n\trootCmd.Flags().StringVarP(&format, \"format\", \"f\", \"\", \"The expected response format: json\")\n\trootCmd.Flags().StringVarP(&path, \"path\", \"p\", \"\", \"The path in the return value data to test against the expected value\")\n\trootCmd.Flags().StringVarP(&expectedValue, \"expectedValue\", \"e\", \"\", \"The expected response data value\")\n\trootCmd.Flags().StringVarP(&expression, \"expression\", \"\", \"\", \"Expression to evaluate against response data value\")\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Fprintln(os.Stdout, err)\n\t\texitCode = 1\n\t}\n\n\treturn exitCode\n}", "func Execute(plugin Plugin) {\n\tcmd := plugin.Command()\n\tcmd.RunE = func(cmd Command, args []string) error {\n\t\treturn plugin.Run()\n\t}\n\n\t// Execute the plugin\n\tif exit := cmd.Execute(); exit != nil {\n\t\tif exit, ok := exit.(*Exit); ok {\n\t\t\tfmt.Printf(\"%s %s\", cmd.Name(), exit.Error())\n\t\t\tos.Exit(exit.Status)\n\t\t}\n\n\t\t// Unknown exit code\n\t\tfmt.Printf(\"%s %s\", cmd.Name(), exit.Error())\n\t\tos.Exit(4)\n\t}\n\n\t// No exit code was explicitly returned\n\tfmt.Printf(\"%s %s: %+v\\n\", cmd.Name(), Statuses[3], \"check did not returned an exit code\")\n\tos.Exit(4)\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 testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func Run(test *TestData, result chan *TestResult) {\n\n\t// tests which don't require loading of reaction data output\n\tnonDataParseTests := []string{\"DIFF_FILE_CONTENT\", \"FILE_MATCH_PATTERN\",\n\t\t\"CHECK_TRIGGERS\", \"CHECK_EXPRESSIONS\", \"CHECK_LEGACY_VOL_OUTPUT\",\n\t\t\"CHECK_EMPTY_FILE\", \"CHECK_ASCII_VIZ_OUTPUT\", \"CHECK_CHECKPOINT\"}\n\n\tfor _, c := range test.Checks {\n\n\t\tdataPaths, err := file.GetDataPaths(test.Path, c.DataFile, test.Run.Seed,\n\t\t\ttest.Run.NumSeeds)\n\t\tif err != nil {\n\t\t\tresult <- &TestResult{test.Path, false, c.TestType, fmt.Sprint(err)}\n\t\t\tcontinue\n\t\t}\n\n\t\t// load the data for test types which need it\n\t\tvar data []*file.Columns\n\t\tvar stringData []*file.StringColumns\n\t\t// NOTE: only attempt to parse data for the test cases which need it\n\t\tif c.DataFile != \"\" && !misc.ContainsString(nonDataParseTests, c.TestType) {\n\t\t\tdata, err = file.LoadData(dataPaths, c.HaveHeader, c.AverageData)\n\t\t\tif err != nil {\n\t\t\t\tresult <- &TestResult{test.Path, false, c.TestType, fmt.Sprint(err)}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if c.TestType == \"CHECK_TRIGGERS\" {\n\t\t\tstringData, err = file.LoadStringData(dataPaths, c.HaveHeader)\n\t\t\tif err != nil {\n\t\t\t\tresult <- &TestResult{test.Path, false, c.TestType, fmt.Sprint(err)}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// execute requested tests on data\n\t\tvar testErr error\n\t\tswitch c.TestType {\n\t\tcase \"CHECK_SUCCESS\":\n\t\t\tif test.SimStatus == nil {\n\t\t\t\tresult <- &TestResult{test.Path, false, \"CHECK_SUCCESS\",\n\t\t\t\t\t\"simulations did not run or return an exit status\"}\n\t\t\t\treturn // if simulation fails we won't continue testing\n\t\t\t}\n\n\t\t\t// in order to cut down on the amount of output (particularly in the case of\n\t\t\t// multiple seeds) we return failure if one or more of all runs within a test\n\t\t\t// fails and success otherwise\n\t\t\tfor _, testRun := range test.SimStatus {\n\t\t\t\tif !testRun.Success {\n\t\t\t\t\tmessage := strings.Join([]string{testRun.ExitMessage, testRun.StdErrContent}, \"\\n\")\n\t\t\t\t\tresult <- &TestResult{test.Path, false, \"CHECK_SUCCESS\", message}\n\t\t\t\t\treturn // if simulation fails we won't continue testing\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"CHECK_EXIT_CODE\":\n\t\t\tfor _, testRun := range test.SimStatus {\n\t\t\t\tif c.ExitCode != testRun.ExitCode {\n\t\t\t\t\ttestErr = fmt.Errorf(\"Expected exit code %d but got %d instead\",\n\t\t\t\t\t\tc.ExitCode, testRun.ExitCode)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"CHECK_NONEMPTY_FILES\":\n\t\t\tif testErr = checkFilesEmpty(test, c, false); testErr != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\tcase \"CHECK_EMPTY_FILES\":\n\t\t\tif testErr = checkFilesEmpty(test, c, true); testErr != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\tcase \"CHECK_CHECKPOINT\":\n\t\t\tif testErr = checkCheckPoint(test.Path, c); testErr != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\tcase \"CHECK_LEGACY_VOL_OUTPUT\":\n\t\t\tfor _, p := range dataPaths {\n\t\t\t\tif testErr = checkLegacyVolOutput(p, c); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"CHECK_ASCII_VIZ_OUTPUT\":\n\t\t\tfor _, p := range dataPaths {\n\t\t\t\tif testErr = checkASCIIVizOutput(p); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"DIFF_FILE_CONTENT\":\n\t\t\tfor _, p := range dataPaths {\n\t\t\t\tif testErr = diffFileContent(test.Path, p, c.TemplateFile,\n\t\t\t\t\tc.TemplateParameters); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"COUNT_CONSTRAINTS\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkCountConstraints(d, dataPaths[i], c.MinTime, c.MaxTime,\n\t\t\t\t\tc.CountConstraints); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"COUNT_MINMAX\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkCountMinmax(d, dataPaths[i], c.MinTime, c.MaxTime,\n\t\t\t\t\tc.CountMaximum, c.CountMinimum); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"FILE_MATCH_PATTERN\":\n\t\t\tfor _, dataPath := range dataPaths {\n\t\t\t\tif testErr = fileMatchPattern(dataPath, c.MatchPattern, c.NumMatches); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"CHECK_EXPRESSIONS\":\n\t\t\tfor _, dataPath := range dataPaths {\n\t\t\t\tif testErr = checkExpressions(dataPath); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"COMPARE_COUNTS\":\n\t\t\t// only one of absDeviation or relDeviation can be defined\n\t\t\tif (len(c.AbsDeviation) > 0) && (len(c.RelDeviation) > 0) {\n\t\t\t\ttestErr = fmt.Errorf(\"absDeviation and relDeviation are mutually exclusive\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treferencePath := filepath.Join(test.Path, c.ReferenceFile)\n\t\t\trefData, err := file.ReadCounts(referencePath, c.HaveHeader)\n\t\t\tif err != nil {\n\t\t\t\ttestErr = err\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = compareCounts(d, refData, c.AbsDeviation, c.RelDeviation,\n\t\t\t\t\tdataPaths[i], c.MinTime, c.MaxTime); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"COUNT_EQUILIBRIUM\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkCountEquilibrium(d, dataPaths[i], c.MinTime, c.MaxTime,\n\t\t\t\t\tc.Means, c.Tolerances); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"POSITIVE_COUNTS\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkPositiveOrZeroCounts(d, dataPaths[i], c.MinTime,\n\t\t\t\t\tc.MaxTime, false); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"POSITIVE_OR_ZERO_COUNTS\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkPositiveOrZeroCounts(d, dataPaths[i], c.MinTime,\n\t\t\t\t\tc.MaxTime, true); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"ZERO_COUNTS\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = checkZeroCounts(d, dataPaths[i], c.MinTime,\n\t\t\t\t\tc.MaxTime); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"COUNT_RATES\":\n\t\t\tfor i, d := range data {\n\t\t\t\tif testErr = countRates(d, dataPaths[i], c.MinTime, c.MaxTime,\n\t\t\t\t\tc.BaseTime, c.Means, c.Tolerances); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"CHECK_TRIGGERS\":\n\t\t\tfor i, d := range stringData {\n\t\t\t\tif testErr = checkTriggers(d, dataPaths[i], c.MinTime, c.MaxTime,\n\t\t\t\t\tc.TriggerType, c.HaveExactTime, c.OutputTime, c.Xrange, c.Yrange,\n\t\t\t\t\tc.Zrange); testErr != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\ttestErr = fmt.Errorf(\"Unknown test type: %s\", c.TestType)\n\t\t\tbreak\n\t\t}\n\t\trecordResult(result, c.TestType, test.Path, testErr)\n\t}\n}", "func scan(c *cli.Context) error {\r\n\t// Check for arguments after the subcommand\r\n\tif c.Args().Present() {\r\n\t\t// Get next argument (the target)\r\n\t\tt := c.Args().First()\r\n\t\tfmt.Println(\"scanning\", t)\r\n\t\treturn nil\r\n\t}\r\n\t// Show scan subcommand help\r\n\tcli.ShowSubcommandHelp(c)\r\n\treturn cli.NewExitError(\"no arguments provided for subcommand\", 3)\r\n}", "func executeScan(config *ScanOptions, utils whitesourceUtils) error {\n\tif config.ScanType == \"\" {\n\t\tconfig.ScanType = config.BuildTool\n\t}\n\n\tswitch config.ScanType {\n\tcase \"npm\":\n\t\t// Execute scan with whitesource yarn plugin\n\t\tif err := executeYarnScan(config, utils); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Download the unified agent jar file if one does not exist\n\t\tif err := downloadAgent(config, utils); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Auto generate a config file based on the working directory's contents.\n\t\t// TODO/NOTE: Currently this scans the UA jar file as a dependency since it is downloaded beforehand\n\t\tif err := autoGenerateWhitesourceConfig(config, utils); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Execute whitesource scan with unified agent jar file\n\t\tif err := executeUAScan(config, utils); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (suite *AddCommandTestSuite) TestExecuteWithMultipleURLs() {\n\n}", "func mainAnalyze(ctx *cli.Context) error {\n\tcheckAnalyze(ctx)\n\targs := ctx.Args()\n\tif len(args) == 0 {\n\t\tconsole.Fatal(\"No benchmark data file supplied\")\n\t}\n\tif len(args) > 1 {\n\t\tconsole.Fatal(\"Only one benchmark file can be given\")\n\t}\n\tvar zstdDec, _ = zstd.NewReader(nil)\n\tdefer zstdDec.Close()\n\tmonitor := api.NewBenchmarkMonitor(ctx.String(serverFlagName))\n\tdefer monitor.Done()\n\tlog := console.Printf\n\tif globalQuiet {\n\t\tlog = nil\n\t}\n\tfor _, arg := range args {\n\t\tvar input io.Reader\n\t\tif arg == \"-\" {\n\t\t\tinput = os.Stdin\n\t\t} else {\n\t\t\tf, err := os.Open(arg)\n\t\t\tfatalIf(probe.NewError(err), \"Unable to open input file\")\n\t\t\tdefer f.Close()\n\t\t\tinput = f\n\t\t}\n\t\terr := zstdDec.Reset(input)\n\t\tfatalIf(probe.NewError(err), \"Unable to read input\")\n\t\tops, err := bench.OperationsFromCSV(zstdDec, true, ctx.Int(\"analyze.offset\"), ctx.Int(\"analyze.limit\"), log)\n\t\tfatalIf(probe.NewError(err), \"Unable to parse input\")\n\n\t\tprintAnalysis(ctx, ops)\n\t\tmonitor.OperationsReady(ops, strings.TrimSuffix(filepath.Base(arg), \".csv.zst\"), commandLine(ctx))\n\t}\n\treturn nil\n}", "func (Interface *LineInterface) Run() {\n\tInterface.ValidateArguments()\n\tgetBalanceCommand := flag.NewFlagSet(\"getbalance\", flag.ExitOnError)\n\tcreateBlockChainCommand := flag.NewFlagSet(\"createblockchain\", flag.ExitOnError)\n\tsendCommand := flag.NewFlagSet(\"send\", flag.ExitOnError)\n\tprintChainCommand := flag.NewFlagSet(\"printchain\", flag.ExitOnError)\n\tcreateWalletCommand := flag.NewFlagSet(\"createwallet\", flag.ExitOnError)\n\tlistAddressesCommand := flag.NewFlagSet(\"listaddresses\", flag.ExitOnError)\n\n\tgetBalanceAddress := getBalanceCommand.String(\"address\", \"\", \"The Address to find Balance.\")\n\tcreateBlockChainAddress := createBlockChainCommand.String(\"address\", \"\", \"The Address to send Reward to.\")\n\tsendFrom := sendCommand.String(\"from\", \"\", \"Source Wallet Address\")\n\tsendTo := sendCommand.String(\"to\", \"\", \"Destination Wallet Address\")\n\tsendAmount := sendCommand.Int(\"amount\", 0, \"Amount To Send\")\n\tswitch os.Args[1] {\n\tcase \"getbalance\":\n\t\terr := getBalanceCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tcase \"createblockchain\":\n\t\terr := createBlockChainCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tcase \"listaddresses\":\n\t\terr := listAddressesCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tcase \"createwallet\":\n\t\terr := createWalletCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tcase \"printchain\":\n\t\terr := printChainCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tcase \"send\":\n\t\terr := sendCommand.Parse(os.Args[2:])\n\t\tblockchain.Handle(err)\n\tdefault:\n\t\tInterface.PrintUsage()\n\t\truntime.Goexit()\n\t}\n\tif getBalanceCommand.Parsed() {\n\t\tif *getBalanceAddress == \"\" {\n\t\t\tgetBalanceCommand.Usage()\n\t\t\truntime.Goexit()\n\t\t}\n\t\tInterface.GetBalance(*getBalanceAddress)\n\t}\n\tif createBlockChainCommand.Parsed() {\n\t\tif *createBlockChainAddress == \"\" {\n\t\t\tcreateBlockChainCommand.Usage()\n\t\t\truntime.Goexit()\n\t\t}\n\t\tInterface.CreateBlockChain(*createBlockChainAddress)\n\t}\n\tif printChainCommand.Parsed() {\n\t\tInterface.PrintChain()\n\t}\n\tif createWalletCommand.Parsed() {\n\t\tInterface.CreateWallet()\n\t}\n\tif listAddressesCommand.Parsed() {\n\t\tInterface.ListAddresses()\n\t}\n\tif sendCommand.Parsed() {\n\t\tif *sendFrom == \"\" || *sendTo == \"\" || *sendAmount <= 0 {\n\t\t\tsendCommand.Usage()\n\t\t\truntime.Goexit()\n\t\t}\n\t\tInterface.Send(*sendFrom, *sendTo, *sendAmount)\n\t}\n}", "func TestRunMain(t *testing.T) {\n\tmain()\n}", "func RunUnitTest(cobraCmd *cobra.Command, args []string) {\n\terr := CommandWithStdout(\"go\", \"test\", \"./...\").Run()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (v *VsctlMock) Exec(args ...string) ([]byte, error) {\n\tif debugMocks {\n\t\tfmt.Printf(\"MOCK [Vsctl received: ovs-vsctl %s]\\n\", args)\n\t}\n\tv.ReceivedArgs = append(v.ReceivedArgs, args)\n\n\tif len(v.VsctlResults) == 0 {\n\t\treturn nil, errors.New(\"VsctlMock - results not set\")\n\t}\n\n\tout, err := v.VsctlResults[0].ResultOutcome, v.VsctlResults[0].ResultError\n\tv.VsctlResults = v.VsctlResults[1:]\n\tif debugMocks {\n\t\tfmt.Printf(\"MOCK [Vsctl response: %s]\\n\", out)\n\t}\n\treturn []byte(out), err\n}", "func ValidateInput(args []string, out io.Writer) {\n\tuuid.SwitchFormat(uuid.CleanHyphen)\n\n\tif len(args) < ArgumentLength {\n\t\tutils.DisplayCommandUsage(out)\n\t\treturn\n\t}\n\n\terr, _, command, subcommand, parameters := ParseCliCommand(args)\n\n\tif err != nil {\n\t\tutils.DisplayCommandUsage(out)\n\t\tfmt.Fprint(out, err.Error())\n\t\treturn\n\t}\n\n\tif cmd, exists := utils.SsmCliCommands[command]; exists {\n\t\tif utils.IsHelp(subcommand, parameters) {\n\t\t\tfmt.Fprintln(out, cmd.Help())\n\t\t} else {\n\t\t\tcmdErr, result := cmd.Execute(parameters)\n\t\t\tif cmdErr != nil {\n\t\t\t\tutils.DisplayCommandUsage(out)\n\t\t\t\tfmt.Fprint(out, cmdErr.Error())\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(out, result)\n\t\t\t}\n\t\t}\n\t} else if command == utils.HelpFlag {\n\t\tutils.DisplayHelp(out)\n\t} else {\n\t\tutils.DisplayCommandUsage(out)\n\t\tfmt.Fprintf(out, \"\\nInvalid command %v. The following commands are supported:\\n\\n\", command)\n\t\tutils.DisplaySupportedCommands(out)\n\t}\n}", "func TestRegisterAndExecuteCommand(t *testing.T) {\n\t// Create the controller, register the ControllerTestCommand to handle 'ControllerTest' notes\n\tvar controller = controller.GetInstance(\"ControllerTestKey2\", func() interfaces.IController { return &controller.Controller{Key: \"ControllerTestKey2\"} })\n\tcontroller.RegisterCommand(\"ControllerTest\", func() interfaces.ICommand { return &ControllerTestCommand{} })\n\n\t// Create a 'ControllerTest' note\n\tvar vo = ControllerTestVO{Input: 12}\n\tvar note interfaces.INotification = observer.NewNotification(\"ControllerTest\", &vo, \"\")\n\n\t// Tell the controller to execute the Command associated with the note\n\t// the ControllerTestCommand invoked will multiply the vo.input value\n\t// by 2 and set the result on vo.result\n\tcontroller.ExecuteCommand(note)\n\n\t// test assertions\n\tif vo.Result != 24 {\n\t\tt.Error(\"Expecting vo.Result == 24\")\n\t}\n}", "func (l *Ec2DetectorTestCase) ExecuteTestCase() testCommon.TestOutput {\n\t// Test should not be executed on darwin\n\treturn testCommon.TestOutput{}\n}", "func Run() error {\n\tdefer FuncEndingAlways(FuncStarting())\n\tparams := GetCliParams(os.Args[1:])\n\tDebugf(\"CLI Params:\\n%s\", params)\n\tif params.HelpPrinted {\n\t\treturn nil\n\t}\n\tif params.HasError() {\n\t\treturn &params\n\t}\n\tdat, err := ReadFile(params.InputFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tDebugf(\"Input File Contents:\\n%s\", dat)\n\tinput, err := ParseInput(dat)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = input.ApplyParams(params); err != nil {\n\t\treturn err\n\t}\n\tDebugf(\"Parsed Input:\\n%s\", input)\n\tanswer, err := Solve(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tStdout(\"Answer: %s\", answer)\n\treturn nil\n}", "func TestAsciiArtFS(t *testing.T) {\n\tgetTestCases()\n\n\t// Test the program with incorrect amount of args\n\toutput, err := exec.Command(\"go\", \"run\", \".\", testCases[1][0], testCases[1][1], testCases[1][2]).Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif string(output) != testCases[1][3] {\n\t\tt.Errorf(\"\\nTest fails when given the arguments:\\n\\t\\\"%s\\\" \\\"%s\\\" \\\"%s\\\",\"+\n\t\t\t\"\\nexpected:\\n%s\\ngot:\\n%s\\n\\n\",\n\t\t\ttestCases[1][0], testCases[1][1], testCases[1][2], testCases[1][3], string(output))\n\t}\n\n\t/*\tIterate through each test case and starting a goroutine for each, this\n\t\tis done so instead of waiting for the previous test to complete they can\n\t\tall be checked simulaneously\t*/\n\tvar wg sync.WaitGroup\n\tfor i := 2; i <= len(testCases); i++ {\n\t\twg.Add(1)\n\t\tgo func(current []string, w *sync.WaitGroup, ti *testing.T) {\n\t\t\tdefer w.Done()\n\t\t\tresult := getResult(current)\n\t\t\t/*\tFails the project if the test cases expected output doesn't match\n\t\t\t\tthe actual output\t*/\n\t\t\tif string(result) != current[2] {\n\t\t\t\tti.Errorf(\"\\nTest fails when given the test case:\\n\\t\\\"%s\\\" \\\"%s\\\",\"+\n\t\t\t\t\t\"\\nexpected:\\n%s\\ngot:\\n%s\\n\\n\",\n\t\t\t\t\tcurrent[0], current[1], current[2], string(result))\n\t\t\t}\n\t\t}(testCases[i], &wg, t)\n\t}\n\twg.Wait()\n}", "func run(input string) (interface{}, interface{}) {\n\n\t// fmt.Println(\"PASS\")\n\treturn parse(input)\n}", "func Test() error {\n\treturn sh.RunWith(map[string]string{\"GORACE\": \"halt_on_error=1\"},\n\t\t\"go\", \"test\", \"-race\", \"-v\", \"./...\")\n}", "func (p *httpMockProvider) ExecuteTest(t *testing.T, integrationTest func(MockServerConfig) error) error {\n\tlog.Println(\"[DEBUG] pact verify\")\n\n\tvar err error\n\tif p.config.AllowedMockServerPorts != \"\" && p.config.Port <= 0 {\n\t\tp.config.Port, err = utils.FindPortInRange(p.config.AllowedMockServerPorts)\n\t} else if p.config.Port <= 0 {\n\t\tp.config.Port, err = 0, nil\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error: unable to find free port, mock server will fail to start\")\n\t}\n\n\tp.config.Port, err = p.mockserver.Start(fmt.Sprintf(\"%s:%d\", p.config.Host, p.config.Port), p.config.TLS)\n\tdefer p.reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Run the integration test\n\terr = integrationTest(MockServerConfig{\n\t\tPort: p.config.Port,\n\t\tHost: p.config.Host,\n\t\tTLSConfig: GetTLSConfigForTLSMockServer(),\n\t})\n\n\tres, mismatches := p.mockserver.Verify(p.config.Port, p.config.PactDir)\n\tp.displayMismatches(t, mismatches)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !res {\n\t\treturn fmt.Errorf(\"pact validation failed: %+v %+v\", res, mismatches)\n\t}\n\n\tif len(mismatches) > 0 {\n\t\treturn fmt.Errorf(\"pact validation failed: %+v\", mismatches)\n\t}\n\n\tp.mockserver.CleanupPlugins()\n\n\treturn p.writePact()\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 TestMain(m *testing.M) {\n\tflag.Parse()\n\n\tresult := m.Run()\n\n\tos.Exit(result)\n}", "func (command SimpleCommandTestCommand) execute(notification interfaces.INotification) {\n\tvar vo = notification.Body().(*SimpleCommandTestVO)\n\n\t//Fabricate a result\n\tvo.Result = 2 * vo.Input\n}", "func TestDashF_STDIN(t *testing.T) {\n\t// TODO:\n\t//doIt(\"https://raw.githubusercontent.com/cdornsife/dashf/master/tests/test.yaml\", t)\n}", "func (dt *ApisValidatableTest) Run(t *testing.T) {\n\tgot := dt.Input.Validate(dt.Context)\n\n\tAssertEqual(t, \"validation errors\", dt.Want.Error(), got.Error())\n}", "func (sc *ScanClient) Scan(scheme string, host string, port int, username string, password string, path string, projectName string, versionName string, scanName string) error {\n\tif err := sc.ensureScanClientIsDownloaded(scheme, host, port, username, password); err != nil {\n\t\treturn errors.Annotate(err, \"cannot run scan cli\")\n\t}\n\tstartTotal := time.Now()\n\n\tscanCliImplJarPath := sc.scanClientInfo.ScanCliImplJarPath()\n\tscanCliJarPath := sc.scanClientInfo.ScanCliJarPath()\n\tscanCliJavaPath := sc.scanClientInfo.ScanCliJavaPath()\n\tcmd := exec.Command(scanCliJavaPath,\n\t\t\"-Xms512m\",\n\t\t\"-Xmx4096m\",\n\t\t\"-Dblackduck.scan.cli.benice=true\",\n\t\t\"-Dblackduck.scan.skipUpdate=true\",\n\t\t\"-Done-jar.silent=true\",\n\t\t\"-Done-jar.jar.path=\"+scanCliImplJarPath,\n\t\t\"-jar\", scanCliJarPath,\n\t\t\"--host\", host,\n\t\t\"--port\", fmt.Sprintf(\"%d\", port),\n\t\t\"--scheme\", scheme,\n\t\t\"--project\", projectName,\n\t\t\"--release\", versionName,\n\t\t\"--username\", username,\n\t\t\"--name\", scanName,\n\t\tsc.getTLSVerification(),\n\t\t\"-v\",\n\t\tpath)\n\tlog.Infof(\"running command %+v for path %s\\n\", cmd, path)\n\tcmd.Env = append(cmd.Env, fmt.Sprintf(\"BD_HUB_PASSWORD=%s\", password))\n\n\tstartScanClient := time.Now()\n\tstdoutStderr, err := cmd.CombinedOutput()\n\n\trecordScanClientDuration(time.Now().Sub(startScanClient), err == nil)\n\trecordTotalScannerDuration(time.Now().Sub(startTotal), err == nil)\n\n\tif err != nil {\n\t\trecordScannerError(\"scan client failed\")\n\t\tlog.Errorf(\"java scanner failed for path %s with error %s and output:\\n%s\\n\", path, err.Error(), string(stdoutStderr))\n\t\treturn errors.Trace(err)\n\t}\n\tlog.Infof(\"successfully completed java scanner for path %s\", path)\n\tlog.Debugf(\"output from path %s: %s\", path, stdoutStderr)\n\treturn nil\n}", "func main() {\n\texecute.Execute()\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 main() {\n\tif err := cmd.Cmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func Run(opts ...Option) error {\n\tvar o options\n\tfor _, opt := range opts {\n\t\tif err := opt(&o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Now build the command to run with the realized options\n\t// struct.\n\targs := []string{\"test\", \"-v\", \"-json\"}\n\tif o.race {\n\t\targs = append(args, \"-race\")\n\t}\n\tif o.coverprofile != \"\" {\n\t\targs = append(args, \"-coverprofile=\"+o.coverprofile)\n\t}\n\tif o.coverpkg != \"\" {\n\t\targs = append(args, \"-coverpkg=\"+o.coverpkg)\n\t}\n\tif o.covermode != \"\" {\n\t\targs = append(args, \"-covermode=\"+o.covermode)\n\t}\n\tif o.p != 0 {\n\t\targs = append(args, \"-p=\"+strconv.Itoa(o.p))\n\t}\n\targs = append(args, \"./...\")\n\tcmd := exec.Command(\"go\", args...)\n\tcmd.Stderr = os.Stderr\n\n\tcmdStdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\tif err := parseGoTestJSONOutput(cmdStdout, newMultiResultAccepter(o.accepters...)); err != nil {\n\t\t_ = cmd.Process.Kill()\n\t\t_ = cmd.Wait()\n\t\treturn err\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"go test failed: %w\", err)\n\t}\n\n\treturn nil\n}", "func (c *Command) Run(t *testing.T) {\n\targs := strings.Split(c.Args, \" \")\n\tif output, err := exec.Command(c.Exec, args...).CombinedOutput(); err != nil {\n\t\tt.Fatalf(\"Error executing: '%s' '%s' -err: '%v'\", c.Exec, c.Args, strings.TrimSpace(string(output)))\n\t}\n}", "func main() {\n\tvar nTests uint64\n\tfmt.Scanf(\"%d\", &nTests)\n\n\tfor ; nTests > 0; nTests-- {\n\t\tvar lower, upper uint64\n\t\tif nScanned, _ := fmt.Scanf(\"%d %d\", &lower, &upper); 2 != nScanned {\n\t\t\tpanic(\"Could not read proper test case\")\n\t\t}\n\n\t\tfor _, prime := range primesBetween(lower, upper) {\n\t\t\tfmt.Println(prime)\n\t\t}\n\t}\n}", "func (tq TestQuery) Test(name string, client *QueryClient) error {\n\t_, err := exec(client, string(tq), nil)\n\tif err != nil {\n\t\tif name == \"\" {\n\t\t\treturn err\n\t\t}\n\t\treturn vterrors.Wrapf(err, \"%s: Execute failed\", name)\n\t}\n\treturn nil\n}", "func (bt *speedbeat) DoTest() (Speedresult, error) {\n\tlogp.Info(\"Speedtest starting\")\n\tvar tempspeedresult Speedresult\n\n //set up the command line\n\tcmd := exec.Command(\"speedtest\", \"--format=json\")\nlogp.Info(cmd.String())\n\t//run command\n\t output, err := cmd.Output()\n\t if err != nil {\n logp.Warn(\"Speedtest Error\")\n\t\tfmt.Println( \"Error:\", err)\n\t\tfmt.Println( \"Output:\", output)\n\t\treturn tempspeedresult, errors.New(\"Speedtest CLI Error\")\n\t}\n\n\tlogp.Info(\"Speedtest Success\")\n\tfmt.Printf( \"Output: %s\\n\", output)\n\n\t//parse the results\n\n\ttempResultJSON := output\nerr = json.Unmarshal([]byte(tempResultJSON), &tempspeedresult)\n\n if err != nil {\n\t\tlogp.Warn(\"Test Result Parsing Error\")\n\t\tfmt.Println( \"Error:\", err)\n\t\treturn tempspeedresult, errors.New(\"Speedtest Result Parsing Error\")\n\t}\n\n return tempspeedresult, nil\n}", "func (tc ScannerTestcase) Run(ctx context.Context) func(*testing.T) {\n\tsort.Slice(tc.Want, pkgSort(tc.Want))\n\treturn func(t *testing.T) {\n\t\tctx := zlog.Test(ctx, t)\n\t\td := tc.Digest()\n\t\tn, err := fetch.Layer(ctx, t, http.DefaultClient, tc.Domain, tc.Name, d)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer n.Close()\n\t\tl := &claircore.Layer{\n\t\t\tHash: d,\n\t\t}\n\t\tl.SetLocal(n.Name())\n\n\t\tgot, err := tc.Scanner.Scan(ctx, l)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsort.Slice(got, pkgSort(got))\n\t\tt.Logf(\"found %d packages\", len(got))\n\t\tif !cmp.Equal(tc.Want, got) {\n\t\t\tt.Error(cmp.Diff(tc.Want, got))\n\t\t}\n\t}\n}", "func Execute() {\n\tif err := searchCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\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 (h *validateCommand) Do(args []string) int {\n\tif len(args) == 0 {\n\t\treturn h.MissingOption(`--input`)\n\t}\n\n\tinput := ``\n\tspec := ``\n\tfor len(args) > 0 {\n\t\topt := args[0]\n\t\targs = args[1:]\n\t\tswitch opt {\n\t\tcase `help`, `-?`, `--help`, `-help`:\n\t\t\treturn h.Help()\n\t\tcase `-i`, `--input`:\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn h.MissingOptionArgument(opt)\n\t\t\t}\n\t\t\tinput = args[0]\n\t\t\targs = args[1:]\n\t\tcase `-s`, `--spec`:\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn h.MissingOptionArgument(opt)\n\t\t\t}\n\t\t\tspec = args[0]\n\t\t\targs = args[1:]\n\t\tcase `-v`, `--verbose`:\n\t\t\th.verbose = true\n\t\tdefault:\n\t\t\treturn h.UnknownOption(opt)\n\t\t}\n\t}\n\tif input == `` {\n\t\treturn h.MissingOption(`--input`)\n\t}\n\tif spec == `` {\n\t\treturn h.MissingOption(`--spec`)\n\t}\n\treturn h.RunWithCatch(func() int {\n\t\treturn h.run(input, spec)\n\t})\n}", "func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\n\t// Add port 22 to the target if we didn't get a port from the user.\n\tif !strings.Contains(target, \":\") {\n\t\ttarget = target + \":22\"\n\t}\n\n\tvar config ssh.ClientConfig\n\tvar err error\n\n\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\n\tresult := scanners.Result{\n\t\tHost: target,\n\t\tAuth: cred,\n\t\tMessage: \"Successfully connected\",\n\t\tStatus: true,\n\t\tOutput: \"\",\n\t}\n\n\t// Depending on the authentication type, run the correct connection function\n\tswitch cred.Type {\n\tcase \"basic\":\n\t\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\n\tcase \"sshkey\":\n\t\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\n\t}\n\n\t// Return if we got an error.\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t_, session, err := this.connect(cred.Account, target, config)\n\n\t// If we got an error, let's set the data properly\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t// If we didn't get an error and we have a command to run, let's do it.\n\tif err == nil && cmd != \"\" {\n\t\t// Execute the command\n\t\tresult.Output, err = this.executeCommand(cmd, session)\n\t\tif err != nil {\n\t\t\t// If we got an error, let's give the user some output.\n\t\t\tresult.Output = \"Script Error: \" + err.Error()\n\t\t}\n\t}\n\n\t// Finally, let's pass our result to the proper channel to write out to the user\n\toutChan <- result\n}", "func (c *cmdVoteTest) Execute(args []string) error {\n\t// We don't want the output of individual commands printed.\n\tcfg.Verbose = false\n\tcfg.RawJSON = false\n\tcfg.Silent = true\n\n\t// Get all ongoing votes\n\tvotes := make([]string, 0, 256)\n\tvar page uint32 = 1\n\tfor {\n\t\ttokens, err := voteInvForStatus(tkv1.VoteStatusStarted, page)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(tokens) == 0 {\n\t\t\t// We've reached the end of the inventory\n\t\t\tbreak\n\t\t}\n\t\tvotes = append(votes, tokens...)\n\t\tpage++\n\t}\n\tif len(votes) == 0 {\n\t\treturn fmt.Errorf(\"no ongoing votes\")\n\t}\n\n\t// Setup vote options\n\tvoteOptions := []string{\n\t\ttkv1.VoteOptionIDApprove,\n\t\ttkv1.VoteOptionIDReject,\n\t}\n\n\t// Cast ballots concurrently\n\tvar wg sync.WaitGroup\n\tfor _, v := range votes {\n\t\t// Select vote option randomly\n\t\tr := rand.Intn(len(voteOptions))\n\t\tvoteOption := voteOptions[r]\n\n\t\twg.Add(1)\n\t\tgo func(wg *sync.WaitGroup, token, voteOption, password string) {\n\t\t\tdefer wg.Done()\n\n\t\t\t// Turn printing back on for this part\n\t\t\tcfg.Silent = false\n\n\t\t\t// Cast ballot\n\t\t\tfmt.Printf(\"Casting ballot for %v %v\\n\", token, voteOption)\n\t\t\tstart := time.Now()\n\t\t\terr := castBallot(token, voteOption, password)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"castBallot %v: %v\\n\", token, err)\n\t\t\t}\n\t\t\tend := time.Now()\n\t\t\telapsed := end.Sub(start)\n\n\t\t\tfmt.Printf(\"%v elapsed time %v\\n\", token, elapsed)\n\n\t\t}(&wg, v, voteOption, c.Args.Password)\n\t}\n\n\twg.Wait()\n\n\treturn nil\n}", "func TestMain(m *testing.M) {\n\tDropTestData(0)\n\tanswer := m.Run()\n\tDropTestData(0)\n\tos.Exit(answer)\n}", "func Main() int {\n\treturn ParseAndRun(os.Stdout, os.Stderr, os.Stdin, os.Args[1:])\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}" ]
[ "0.66738474", "0.61816204", "0.61401296", "0.6130477", "0.61267704", "0.6054782", "0.60366654", "0.5880252", "0.58619845", "0.5850724", "0.581697", "0.5810173", "0.5746905", "0.57246107", "0.57229185", "0.57181555", "0.5695352", "0.56370866", "0.56357914", "0.5620503", "0.560419", "0.55973387", "0.5561238", "0.55328107", "0.5528965", "0.5521076", "0.55125993", "0.5494939", "0.54827", "0.5473217", "0.5473217", "0.5473217", "0.5473217", "0.5473217", "0.5473217", "0.5473217", "0.5443875", "0.5430957", "0.5420125", "0.5418603", "0.5409378", "0.5400126", "0.5386756", "0.53687245", "0.53201264", "0.53184193", "0.5317635", "0.53096294", "0.53092647", "0.528868", "0.5276924", "0.52394795", "0.52362114", "0.52339786", "0.5228292", "0.52178305", "0.521554", "0.52129745", "0.520969", "0.52004457", "0.5193689", "0.5189695", "0.5187493", "0.5186333", "0.5175848", "0.51733404", "0.51731753", "0.51716614", "0.51672566", "0.5164289", "0.5163825", "0.5153346", "0.51532185", "0.5144884", "0.5131922", "0.5129241", "0.5121197", "0.5113865", "0.51110476", "0.5105695", "0.5103139", "0.5100473", "0.5092859", "0.5092859", "0.5092009", "0.5087257", "0.50848836", "0.5081183", "0.5073488", "0.50732476", "0.50647485", "0.5064412", "0.5061866", "0.50577754", "0.5053602", "0.50491554", "0.5046985", "0.50438637", "0.5041965", "0.50341195" ]
0.7561027
0
CreateTilesetSource creates a new tileset source. This function simply calls PutTilesetSource. The provided JSON path should point to a file containing one GeoJSON feature object per line.
func (c *Client) CreateTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) { return c.PutTilesetSource(ctx, tilesetID, jsonReader) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) PutTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {\n\turl := baseURL +\n\t\t\"/tilesets/v1/sources/\" + c.username + \"/\" + tilesetID +\n\t\t\"?access_token=\" + c.accessToken\n\n\tvar jsonResp NewTilesetSourceResponse\n\tresp, err := putMultipart(ctx, c.httpClient, url, \"filenamedoesntmatter\", jsonReader)\n\tif err != nil {\n\t\treturn jsonResp, fmt.Errorf(\"upload %w failed, %v\", ErrOperation, err)\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn jsonResp, fmt.Errorf(\"upload %w failed, non-200 response: %v\", ErrOperation, resp.StatusCode)\n\t}\n\n\tif err = json.NewDecoder(resp.Body).Decode(&jsonResp); err != nil {\n\t\treturn jsonResp, fmt.Errorf(\"%w failed, err: %v\", ErrParse, err)\n\t}\n\n\treturn jsonResp, nil\n}", "func (t *Tileset) UploadGeoJSON(pathToFile string) (*UploadResponse, error) {\n\tpostURL := fmt.Sprintf(\"%s/%s/sources/%s/%s\", apiName, apiVersion, t.username, t.tilesetID)\n\tuploadResponse := &UploadResponse{}\n\tres, err := t.base.PostUploadFileRequest(postURL, pathToFile, \"file\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(res, uploadResponse)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn uploadResponse, nil\n\n}", "func NewJSONSource(b []byte) (*MapSource, error) {\n\tv := make(map[string]interface{})\n\terr := json.Unmarshal(b, &v)\n\treturn NewMapSource(v), err\n}", "func (t *Tileset) CreateTileset(pathToFile string) (*base.MapboxAPIMessage, error) {\n\tmaboxAPIMessage := &base.MapboxAPIMessage{}\n\trecipeJSON, err := os.Open(pathToFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer recipeJSON.Close()\n\n\tdata, _ := ioutil.ReadAll(recipeJSON)\n\tres, err := t.base.PostRequest(t.postURL(), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjson.Unmarshal(res, &maboxAPIMessage)\n\n\treturn maboxAPIMessage, nil\n\n}", "func NewTileSet(ctx context.Context, path string) (t *pb.TileSet, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tt = &pb.TileSet{}\n\td := tsx.NewDecoder(f)\n\terr = d.Decode(t)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"marshal\")\n\t\treturn\n\t}\n\treturn\n}", "func (s *Service) CreateSource(ctx context.Context, src *influxdb.Source) error {\n\terr := s.kv.Update(ctx, func(tx Tx) error {\n\t\tsrc.ID = s.IDGenerator.ID()\n\n\t\t// Generating an organization id if it missing or invalid\n\t\tif !src.OrganizationID.Valid() {\n\t\t\tsrc.OrganizationID = s.IDGenerator.ID()\n\t\t}\n\n\t\treturn s.putSource(ctx, tx, src)\n\t})\n\tif err != nil {\n\t\treturn &influxdb.Error{\n\t\t\tErr: err,\n\t\t}\n\t}\n\treturn nil\n}", "func CreateOSMSource(uri string, cachePath string) Source {\n\n\t/*\n\t * Create OSM tile source.\n\t */\n\tsrc := osmSourceStruct{\n\t\tcachePath: cachePath,\n\t\turi: uri,\n\t}\n\n\treturn &src\n}", "func (client FeatureStateClient) CreateStatesetPreparer(ctx context.Context, datasetID string, statesetCreateRequestBody StylesObject, description string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n \"datasetId\": autorest.Encode(\"query\",datasetID),\n }\n if len(description) > 0 {\n queryParameters[\"description\"] = autorest.Encode(\"query\",description)\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPost(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPath(\"/featureStateSets\"),\nautorest.WithJSON(statesetCreateRequestBody),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func NewTileSets(header Header, ts Tilesets, path string) *TileSets {\n\treturn &TileSets{header, ts, path}\n}", "func NewFileSource(path string) (*MapSource, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// changed how we handled a deferred file closure due to go lint security check https://github.com/securego/gosec/issues/512#issuecomment-675286833\n\tdefer func() {\n\t\tif cerr := f.Close(); cerr != nil {\n\t\t\tfmt.Printf(\"Error closing file: %s\\n\", cerr)\n\t\t}\n\t}()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm, err := NewJSONSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\tm, err = NewYAMLSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\treturn nil, fmt.Errorf(\"could not determine file format for %s\", path)\n}", "func (a *SourcesApiService) CreateSource(ctx context.Context, workspace string, collection string) ApiCreateSourceRequest {\n\treturn ApiCreateSourceRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tworkspace: workspace,\n\t\tcollection: collection,\n\t}\n}", "func NewCreateanewCFSourceSetRequestWithBody(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(\"/cfsourcesets\")\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 (this *osmSourceStruct) tilePath(template string, zoom uint8, x uint32, y uint32) string {\n\tzoom64 := uint64(zoom)\n\tzoomString := strconv.FormatUint(zoom64, BASE_DECIMAL)\n\tx64 := uint64(x)\n\txString := strconv.FormatUint(x64, BASE_DECIMAL)\n\ty64 := uint64(y)\n\tyString := strconv.FormatUint(y64, BASE_DECIMAL)\n\ttemplate = strings.Replace(template, TEMPLATE_ZOOM, zoomString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_X, xString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_Y, yString, ALL)\n\treturn template\n}", "func NewJSONSource(opts ...JSONSourceOption) (*JSONSource, error) {\n\tj := &JSONSource{\n\t\trecords: make(chan record, 3),\n\t}\n\tfor _, opt := range opts {\n\t\topt(j)\n\t}\n\n\tif j.listener == nil {\n\t\tvar err error\n\t\tj.listener, err = net.Listen(\"tcp\", j.addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tj.listener = tcpKeepAliveListener{j.listener.(*net.TCPListener)}\n\n\tj.server = &http.Server{\n\t\tAddr: j.addr,\n\t\tHandler: j,\n\t}\n\tgo func() {\n\t\terr := j.server.Serve(j.listener)\n\t\tif err != nil {\n\t\t\tj.records <- record{err: errors.Wrap(err, \"starting server\")}\n\t\t\tclose(j.records)\n\t\t}\n\t}()\n\treturn j, nil\n}", "func NewSource(\n\tfset *token.FileSet, path string,\n\tfilter func(fs.FileInfo) bool, mode parser.Mode) (doc NodeSet, err error) {\n\n\tpkgs, err := parser.ParseDir(fset, path, filter, mode)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn NodeSet{Data: &oneNode{astPackages(pkgs)}}, nil\n}", "func NewSource(path string) *Source {\n\treturn &Source{Path: path}\n}", "func Make_Tile(tileid m.TileID, feats []*geojson.Feature, prefix string) {\n\tfilename := prefix + \"/\" + strconv.Itoa(int(tileid.Z)) + \"/\" + strconv.Itoa(int(tileid.X)) + \"/\" + strconv.Itoa(int(tileid.Y))\n\tdir := prefix + \"/\" + strconv.Itoa(int(tileid.Z)) + \"/\" + strconv.Itoa(int(tileid.X))\n\tos.MkdirAll(dir, os.ModePerm)\n\tbound := m.Bounds(tileid)\n\tvar keys []string\n\tvar values []*vector_tile.Tile_Value\n\tkeysmap := map[string]uint32{}\n\tvaluesmap := map[*vector_tile.Tile_Value]uint32{}\n\n\t// iterating through each feature\n\tfeatures := []*vector_tile.Tile_Feature{}\n\t//position := []int32{0, 0}\n\tfor _, i := range feats {\n\t\tvar tags, geometry []uint32\n\t\tvar feat vector_tile.Tile_Feature\n\t\ttags, keys, values, keysmap, valuesmap = Update_Properties(i.Properties, keys, values, keysmap, valuesmap)\n\n\t\t// logic for point feature\n\t\tif i.Geometry.Type == \"Point\" {\n\t\t\tgeometry, _ = Make_Point(i.Geometry.Point, []int32{0, 0}, bound)\n\t\t\tfeat_type := vector_tile.Tile_POINT\n\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\tfeatures = append(features, &feat)\n\n\t\t} else if i.Geometry.Type == \"LineString\" {\n\t\t\teh := Make_Coords_Float(i.Geometry.LineString, bound, tileid)\n\t\t\tif len(eh) > 0 {\n\t\t\t\tgeometry, _ = Make_Line_Geom(eh, []int32{0, 0})\n\t\t\t\tfeat_type := vector_tile.Tile_LINESTRING\n\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\tfeatures = append(features, &feat)\n\t\t\t}\n\n\t\t} else if i.Geometry.Type == \"Polygon\" {\n\t\t\tgeometry, _ = Make_Polygon(Make_Coords_Polygon_Float(i.Geometry.Polygon, bound), []int32{0, 0})\n\t\t\tfeat_type := vector_tile.Tile_POLYGON\n\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\tfeatures = append(features, &feat)\n\n\t\t}\n\n\t}\n\n\tlayerVersion := uint32(15)\n\textent := vector_tile.Default_Tile_Layer_Extent\n\t//var bound []Bounds\n\tlayername := prefix\n\tlayer := vector_tile.Tile_Layer{\n\t\tVersion: &layerVersion,\n\t\tName: &layername,\n\t\tExtent: &extent,\n\t\tValues: values,\n\t\tKeys: keys,\n\t\tFeatures: features,\n\t}\n\n\ttile := vector_tile.Tile{}\n\ttile.Layers = append(tile.Layers, &layer)\n\n\tbytevals, _ := proto.Marshal(&tile)\n\tioutil.WriteFile(filename, bytevals, 0666)\n\n\t//fmt.Printf(\"\\r%s\", filename)\n}", "func createSetFromJSON(jsonPath string) map[string]bool {\n\tfile, err := ioutil.ReadFile(jsonPath)\n\tif err != nil {\n\t\tfmt.Printf(\"File error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// TODO: handle this error\n\tvar arr []string\n\t_ = json.Unmarshal([]byte(file), &arr)\n\n\tstopwordSet := make(map[string]bool)\n\tfor _, sword := range arr {\n\t\tstopwordSet[sword] = true\n\t}\n\n\treturn stopwordSet\n}", "func (client BaseClient) CreateFeaturePreparer(ctx context.Context, body *Feature) (*http.Request, error) {\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPath(\"/api/features\"))\n\tif body != nil {\n\t\tpreparer = autorest.DecoratePreparer(preparer,\n\t\t\tautorest.WithJSON(body))\n\t}\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c APIClient) CreateDataSource(ds *DataSource) error {\n\treturn c.doHTTPBoth(\"PUT\", \"https://api.nsone.net/v1/data/sources\", ds)\n}", "func (a *DefaultApiService) CreateSource(ctx _context.Context) ApiCreateSourceRequest {\n\treturn ApiCreateSourceRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (f *Factory) NewFromJSON(filePath string) (string, uint8, FilteredServer) {\n\tlog := f.log.WithField(\"file\", filepath.Base(filePath))\n\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot read file: %v\", err)\n\t}\n\n\tvar c Config\n\n\terr = json.Unmarshal(content, &c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot decode JSON: %v\", err)\n\t}\n\n\treturn f.newFromConfig(log, c)\n}", "func Init(filepath string) (TData, error) {\n\tvar this TData\n\t_, err := os.Stat(filepath)\n\tif os.IsNotExist(err) {\n\t\t// File doesn't exist, create it.\n\t\tthis = TData{filepath, cmap.New()}\n\t\treturn this, nil\n\t}\n\tif err != nil && !os.IsExist(err) {\n\t\treturn TData{}, err\n\t}\n\t// File exists already, read into Data.\n\tvar readData map[string]interface{}\n\tf, err := os.Open(filepath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn TData{}, err\n\t}\n\tif err := json.NewDecoder(f).Decode(&readData); err != nil {\n\t\treturn TData{}, err\n\t}\n\td := cmap.New()\n\n\td.MSet(readData)\n\tthis = TData{filepath, d}\n\treturn this, nil\n}", "func (c *googleCloudStorageSources) Create(ctx context.Context, googleCloudStorageSource *v1alpha1.GoogleCloudStorageSource, opts v1.CreateOptions) (result *v1alpha1.GoogleCloudStorageSource, err error) {\n\tresult = &v1alpha1.GoogleCloudStorageSource{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"googlecloudstoragesources\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tBody(googleCloudStorageSource).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func NewSourceFrom(\n\tfset *token.FileSet, fs parser.FileSystem, path string,\n\tfilter func(fs.FileInfo) bool, mode parser.Mode) (doc NodeSet, err error) {\n\n\tpkgs, err := parser.ParseFSDir(fset, fs, path, parser.Config{Filter: filter, Mode: mode})\n\tif err != nil {\n\t\treturn\n\t}\n\treturn NodeSet{Data: &oneNode{astPackages(pkgs)}}, nil\n}", "func NewSource(path string) config.Source {\n\treturn &file{path: path}\n}", "func NewSource(path string) (*Source, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Source{\n\t\tf: f,\n\t\tstream: stream.NewSource(f),\n\t}, nil\n}", "func (c *ClientWithResponses) CreateanewCFSourceSetWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader) (*CreateanewCFSourceSetResponse, error) {\n\trsp, err := c.CreateanewCFSourceSetWithBody(ctx, contentType, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseCreateanewCFSourceSetResponse(rsp)\n}", "func (client FeatureStateClient) PutStatesetPreparer(ctx context.Context, statesetID string, statesetStyleUpdateRequestBody StylesObject) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"statesetId\": autorest.Encode(\"path\",statesetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPut(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/featureStateSets/{statesetId}\",pathParameters),\nautorest.WithJSON(statesetStyleUpdateRequestBody),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (c *Client) CreateSource(ctx context.Context, organizationID, displayName, description string) (*securitycenterpb.Source, error) {\n\texistingSource, err := c.GetSourceNameForDisplayName(ctx, organizationID, displayName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif existingSource != \"\" {\n\t\treturn nil, fmt.Errorf(\"source already exists for organizationID=<%v> with displayName=<%v>\", organizationID, displayName)\n\t}\n\tsource := &securitycenterpb.Source{\n\t\tDisplayName: displayName,\n\t\tDescription: description,\n\t}\n\tif c.dryRun {\n\t\tc.log.Info(\"(dry-run) creating source\", \"displayName\", source.DisplayName)\n\t\treturn source, nil\n\t}\n\treq := &securitycenterpb.CreateSourceRequest{\n\t\tParent: fmt.Sprintf(\"organizations/%s\", organizationID),\n\t\tSource: source,\n\t}\n\tctx, cancel := context.WithTimeout(ctx, c.timeout)\n\tdefer cancel()\n\treturn c.client.CreateSource(ctx, req)\n}", "func (s *Session) CreateDataSource(ds DataSource) (err error) {\n\treqURL := s.url + \"/api/datasources\"\n\n\tjsonStr, _ := json.Marshal(ds)\n\t_, err = s.httpRequest(\"POST\", reqURL, bytes.NewBuffer(jsonStr))\n\n\treturn\n}", "func NewCreateanewCFSourceSetRequest(server string, body CreateanewCFSourceSetJSONRequestBody) (*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 NewCreateanewCFSourceSetRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (t *TrainingSet) Create(ctx context.Context) error {\n\t_, err := tspb.NewTrainingSetClient(t.c.ClientConn).Create(t.newContext(ctx), &tspb.CreateRequest{\n\t\tName: t.name,\n\t})\n\treturn err\n}", "func NewDataSource(path string) (job.Repository, error) {\n\tdb, err := leveldb.OpenFile(path, nil)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &dataSource{db}, nil\n}", "func CreateFromFile(path string) (*Converter, error) {\n\tvar data, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar dict map[string]string\n\terr = json.Unmarshal(data, &dict)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn createFromDict(dict)\n}", "func NewSourceFile(path string, optfs ...vfs.FileSystem) Source {\n\tvar fs vfs.FileSystem\n\tif len(optfs) > 0 {\n\t\tfs = optfs[0]\n\t}\n\tif fs == nil {\n\t\tfs = osfs.New()\n\t}\n\treturn &sourceFile{sourceBase{path}, fs}\n}", "func (a *SourcesApiService) CreateSourceExecute(r ApiCreateSourceRequest) (*GetSourceResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *GetSourceResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"SourcesApiService.CreateSource\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/orgs/self/ws/{workspace}/collections/{collection}/sources\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"workspace\"+\"}\", url.PathEscape(parameterValueToString(r.workspace, \"workspace\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"collection\"+\"}\", url.PathEscape(parameterValueToString(r.collection, \"collection\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body 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.body\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 := io.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = io.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 ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\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 ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\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 ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\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 ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 405 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 406 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 408 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 415 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\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 ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 501 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 502 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 503 {\n\t\t\tvar v ErrorModel\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\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\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 (this *osmSourceStruct) getTile(id osmTileIdStruct) *osmTileStruct {\n\tzoom := id.zoom\n\tx := id.x\n\ty := id.y\n\tmaxId := uint32((1 << zoom) - 1)\n\ttemplateFile := this.cachePath\n\n\t/*\n\t * Check if tile ID and file path template are valid.\n\t */\n\tif templateFile == \"\" || x > maxId || y > maxId {\n\t\trect := image.Rect(0, 0, TILE_SIZE, TILE_SIZE)\n\t\timg := image.NewNRGBA(rect)\n\n\t\t/*\n\t\t * Create OSM tile.\n\t\t */\n\t\tt := osmTileStruct{\n\t\t\timageData: img,\n\t\t\ttileId: id,\n\t\t}\n\n\t\treturn &t\n\t} else {\n\t\treadFromFile := false\n\t\tpathFile := this.tilePath(templateFile, zoom, x, y)\n\t\tthis.mutex.RLock()\n\t\tfd, err := os.Open(pathFile)\n\t\trect := image.ZR\n\t\timg := image.NewNRGBA(rect)\n\n\t\t/*\n\t\t * Check if file exists.\n\t\t */\n\t\tif err == nil {\n\t\t\timgPng, err := png.Decode(fd)\n\n\t\t\t/*\n\t\t\t * Check if image was decoded from file.\n\t\t\t */\n\t\t\tif err == nil {\n\t\t\t\trect = imgPng.Bounds()\n\t\t\t\timg = image.NewNRGBA(rect)\n\t\t\t\trectMin := rect.Min\n\t\t\t\tminX := rectMin.X\n\t\t\t\tminY := rectMin.Y\n\t\t\t\trectMax := rect.Max\n\t\t\t\tmaxX := rectMax.X\n\t\t\t\tmaxY := rectMax.Y\n\n\t\t\t\t/*\n\t\t\t\t * Read image line by line.\n\t\t\t\t */\n\t\t\t\tfor y := minY; y < maxY; y++ {\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Read line pixel by pixel.\n\t\t\t\t\t */\n\t\t\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\t\t\tc := imgPng.At(x, y)\n\t\t\t\t\t\timg.Set(x, y, c)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treadFromFile = true\n\t\t\t}\n\n\t\t\tfd.Close()\n\t\t}\n\n\t\tthis.mutex.RUnlock()\n\n\t\t/*\n\t\t * If tile was not found in cache, download it from tile server and\n\t\t * store it in cache.\n\t\t */\n\t\tif !readFromFile {\n\t\t\ttemplateUri := this.uri\n\n\t\t\t/*\n\t\t\t * Only download from OSM server if URI is not empty.\n\t\t\t */\n\t\t\tif templateUri != \"\" {\n\t\t\t\tpathUri := this.tilePath(templateUri, zoom, x, y)\n\t\t\t\tfmt.Printf(\"Fetching from URI: %s\\n\", pathUri)\n\t\t\t\tclient := &http.Client{}\n\t\t\t\treq, err := http.NewRequest(\"GET\", pathUri, nil)\n\n\t\t\t\t/*\n\t\t\t\t * Check if we have a valid request.\n\t\t\t\t */\n\t\t\t\tif err == nil {\n\t\t\t\t\tthis.mutex.Lock()\n\t\t\t\t\treq.Header.Set(\"User-Agent\", \"location-visualizer\")\n\t\t\t\t\tresp, err := client.Do(req)\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Check if we got a response and store it in cache.\n\t\t\t\t\t */\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbody := resp.Body\n\t\t\t\t\t\tfd, err := os.Create(pathFile)\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Check if file was created.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tr := io.TeeReader(body, fd)\n\t\t\t\t\t\t\timgPng, err := png.Decode(r)\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * Check if image was decoded from response.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\trect = imgPng.Bounds()\n\t\t\t\t\t\t\t\timg = image.NewNRGBA(rect)\n\t\t\t\t\t\t\t\trectMin := rect.Min\n\t\t\t\t\t\t\t\tminX := rectMin.X\n\t\t\t\t\t\t\t\tminY := rectMin.Y\n\t\t\t\t\t\t\t\trectMax := rect.Max\n\t\t\t\t\t\t\t\tmaxX := rectMax.X\n\t\t\t\t\t\t\t\tmaxY := rectMax.Y\n\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * Read image line by line.\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\tfor y := minY; y < maxY; y++ {\n\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * Read line pixel by pixel.\n\t\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\t\t\t\t\t\t\tc := imgPng.At(x, y)\n\t\t\t\t\t\t\t\t\t\timg.Set(x, y, c)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfd.Close()\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbody.Close()\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.mutex.Unlock()\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t/*\n\t\t * Create OSM tile.\n\t\t */\n\t\tt := osmTileStruct{\n\t\t\timageData: img,\n\t\t\ttileId: id,\n\t\t}\n\n\t\treturn &t\n\t}\n\n}", "func (mbutil *Mbtiles) Make_Tile_Geojson(tileid m.TileID,features_str []*geojson.Feature) {\n\t// getitng featuerstr\n\n\tif len(features_str) > 100000000 {\n\t\t//fmt.Println(\"concurrent\")\n\t\tmbutil.Make_Tile_Geojson_Concurrent(tileid,features_str)\n\t} else {\n\n\t\t// intializing shit for cursor\n\t\tbound := m.Bounds(tileid)\n\t\tdeltax := bound.E-bound.W\n\t\tdeltay := bound.N - bound.S\n\n\t\t// random intializatioin for property collection\n\t\tvar keys []string\n\t\tvar values []*vector_tile.Tile_Value\n\t\tkeysmap := map[string]uint32{}\n\t\tvaluesmap := map[*vector_tile.Tile_Value]uint32{}\n\n\t\t// iterating through each feature\n\t\tfeatures := []*vector_tile.Tile_Feature{}\n\t\t\n\t\t// setting and converting coordinate\t\n\t\tcur := Cursor{LastPoint:[]int32{0,0},Bounds:bound,DeltaX:deltax,DeltaY:deltay,Count:0}\n\t\tcur = Convert_Cursor(cur)\n\t\tvar bytevals []byte\n\n\t\t// creating new mapper\n\t\t\n\t\t//position := []int32{0, 0}\n\t\tfor _,i := range features_str {\n\t\t\t// appplying the soft boudning box filter\n\t\t\t\t\n\t\t\t\t// getitng the featuer\t\t\n\t\t\n\n\t\t\t\t// adding properties and getting correct tags\n\t\t\t\tvar tags, geometry []uint32\n\t\t\t\tvar feat vector_tile.Tile_Feature\n\t\t\t\ttags, keys, values, keysmap, valuesmap = Update_Properties(i.Properties, keys, values, keysmap, valuesmap)\n\t\t\t\t//fmt.Println(i.Geometry)\n\t\t\t\t// logic for point feature'\n\t\t\t\tif i.Geometry == nil {\n\n\t\t\t\t} else if i.Geometry.Type == \"Point\" {\n\t\t\t\t\tgeometry = cur.Make_Point_Float(i.Geometry.Point)\n\t\t\t\t\tfeat_type := vector_tile.Tile_POINT\n\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\tfeatures = append(features, &feat)\n\n\t\t\t\t} else if i.Geometry.Type == \"LineString\" {\n\t\t\t\t\tif len(i.Geometry.LineString) >= 2 {\n\t\t\t\t\t\tgeometry = cur.Make_Line_Float(i.Geometry.LineString)\n\t\t\t\t\t\tif geometry[3] > 2 {\n\t\t\t\t\t\t\tfeat_type := vector_tile.Tile_LINESTRING\n\t\t\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\t\t\tfeatures = append(features, &feat)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t} else if i.Geometry.Type == \"Polygon\" {\n\t\t\t\t\tgeometry = cur.Make_Polygon_Float(i.Geometry.Polygon)\n\t\t\t\t\tfeat_type := vector_tile.Tile_POLYGON\n\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\tfeatures = append(features, &feat)\n\t\t\t\t}\n\t\t}\n\n\t\t//fmt.Println(len(features))\n\t\tif len(features) > 0 {\n\t\t\tlayerVersion := uint32(15)\n\t\t\textent := vector_tile.Default_Tile_Layer_Extent\n\t\t\t//var bound []Bounds\n\t\t\tlayername := mbutil.LayerName\n\t\t\tlayer := vector_tile.Tile_Layer{\n\t\t\t\tVersion: &layerVersion,\n\t\t\t\tName: &layername,\n\t\t\t\tExtent: &extent,\n\t\t\t\tValues: values,\n\t\t\t\tKeys: keys,\n\t\t\t\tFeatures: features,\n\t\t\t}\n\n\t\t\ttile := vector_tile.Tile{}\n\t\t\ttile.Layers = append(tile.Layers, &layer)\n\t\t\tbytevals,_ = proto.Marshal(&tile)\n\t\t\t//if len(bytevals) > 0 {\n\t\t\t//\tmbtile.Add_Tile(tileid,bytevals)\n\t\t\t//}\n\t\t} else {\n\t\t\tbytevals = []byte{}\n\t\t}\n\t\tif len(bytevals) > 0 { \n\t\t\tmbutil.Add_Tile(tileid,bytevals)\n\t\t}\n\t}\n}", "func FromJSONFile(jsonFilename string) (*Story, error) {\n\tjsonFile, err := os.Open(jsonFilename)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read json file: %s\", err)\n\t}\n\n\tst := newStory()\n\td := json.NewDecoder(jsonFile)\n\n\terr = d.Decode(&st.chapterMap)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode json file: %s\", err)\n\t}\n\n\treturn st, nil\n}", "func setUpSourceSites(t *testing.T, fileName, upstreamURL string, objects []string) {\n\tfile, err := os.Create(fileName)\n\tassert.Nil(t, err)\n\tfor _, object := range objects {\n\t\tfile.WriteString(\n\t\t\tfmt.Sprintf(\"%s/%s\\n\", upstreamURL, object),\n\t\t)\n\t}\n\tfile.Close()\n}", "func NewTileset(base *base.Base) *Tileset {\n\treturn &Tileset{base, \"\", \"\"}\n}", "func (m Mean) Setup(inputDir string, tile *Tile) ([]*GeoImage, error) {\n\tfileName := fmt.Sprintf(\"%s_%s_%s.tif\", tile.GeoHash, tile.Date, m.ColumnName)\n\tpath := path.Join(inputDir, fileName)\n\timage, err := loadGeoImage(path)\n\tif err != nil {\n\t\tlog.Error(err, \"mean file not loaded\")\n\t\tos.Exit(1)\n\t}\n\treturn []*GeoImage{image}, nil\n}", "func NewLocalStoreFromJSONMmappableFile(\n\tlogger log.Logger,\n\tcomponent component.StoreAPI,\n\textLabels labels.Labels,\n\tpath string,\n\tsplit bufio.SplitFunc,\n) (*LocalStore, error) {\n\tf, err := fileutil.OpenMmapFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\trunutil.CloseWithErrCapture(&err, f, \"json file %s close\", path)\n\t\t}\n\t}()\n\n\ts := &LocalStore{\n\t\tlogger: logger,\n\t\textLabels: extLabels,\n\t\tc: f,\n\t\tinfo: &storepb.InfoResponse{\n\t\t\tLabelSets: []labelpb.ZLabelSet{\n\t\t\t\t{Labels: labelpb.ZLabelsFromPromLabels(extLabels)},\n\t\t\t},\n\t\t\tStoreType: component.ToProto(),\n\t\t\tMinTime: math.MaxInt64,\n\t\t\tMaxTime: math.MinInt64,\n\t\t},\n\t}\n\n\t// Do quick pass for in-mem index.\n\tcontent := f.Bytes()\n\tcontentStart := bytes.Index(content, []byte(\"{\"))\n\tif contentStart != -1 {\n\t\tcontent = content[contentStart:]\n\t}\n\n\tif idx := bytes.LastIndex(content, []byte(\"}\")); idx != -1 {\n\t\tcontent = content[:idx+1]\n\t}\n\n\tskanner := NewNoCopyScanner(content, split)\n\tresp := &storepb.SeriesResponse{}\n\tfor skanner.Scan() {\n\t\tif err := jsonpb.Unmarshal(bytes.NewReader(skanner.Bytes()), resp); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unmarshal storepb.SeriesResponse frame for file %s\", path)\n\t\t}\n\t\tseries := resp.GetSeries()\n\t\tif series == nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"not a valid series\", \"frame\", resp.String())\n\t\t\tcontinue\n\t\t}\n\t\tchks := make([]int, 0, len(series.Chunks))\n\t\t// Sort chunks in separate slice by MinTime for easier lookup. Find global max and min.\n\t\tfor ci, c := range series.Chunks {\n\t\t\tif s.info.MinTime > c.MinTime {\n\t\t\t\ts.info.MinTime = c.MinTime\n\t\t\t}\n\t\t\tif s.info.MaxTime < c.MaxTime {\n\t\t\t\ts.info.MaxTime = c.MaxTime\n\t\t\t}\n\t\t\tchks = append(chks, ci)\n\t\t}\n\n\t\tsort.Slice(chks, func(i, j int) bool {\n\t\t\treturn series.Chunks[chks[i]].MinTime < series.Chunks[chks[j]].MinTime\n\t\t})\n\t\ts.series = append(s.series, series)\n\t\ts.sortedChunks = append(s.sortedChunks, chks)\n\t}\n\n\tif err := skanner.Err(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"scanning file %s\", path)\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"loading JSON file succeeded\", \"file\", path, \"info\", s.info.String(), \"series\", len(s.series))\n\treturn s, nil\n}", "func newMapTileFromFile(fpath string, n, s, e, w float64) (*mapTile, error) {\n\twid, high, err := imageWxH(fpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newMapTile(fpath, wid, high, n, s, e, w), nil\n}", "func createSourceRun(ctx context.Context) error {\n\tlog := logging.CreateStdLog(\"create\")\n\tsource, err := createSource(ctx, log, organizationID.Value(), displayName.Value(), description.Value(), googleServiceAccount.Value())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn print.AsJSON(source)\n}", "func (client DatasetClient) CreatePreparer(ctx context.Context, conversionID string, datasetID string, descriptionDataset string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n \"conversionId\": autorest.Encode(\"query\",conversionID),\n }\n if len(datasetID) > 0 {\n queryParameters[\"datasetId\"] = autorest.Encode(\"query\",datasetID)\n }\n if len(descriptionDataset) > 0 {\n queryParameters[\"description\"] = autorest.Encode(\"query\",descriptionDataset)\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsPost(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPath(\"/datasets\"),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (client FeatureStateClient) CreateStatesetSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func SetTemplate(t *template.Template, name, filename string) error {\n\n\t// Read template\n\tbuf, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update if exists\n\tif tt := t.Lookup(name); tt != nil {\n\t\t_, err = tt.Parse(string(buf))\n\t\treturn err\n\t}\n\n\t// Allocate new name if not\n\t_, err = t.New(name).Parse(string(buf))\n\treturn err\n}", "func NewTokenSource(name string, path string) oauth2.TokenSource {\n\treturn &tokenSource{\n\t\tname: name,\n\t\tpath: path,\n\t}\n}", "func (c *CSV) SetSource(s string) {\n\tc.source = NewResource(s, FmtCSV, File)\n}", "func NewBoltSource(path string) (Source, error) {\n\n\tdb, err := bolt.Open(path, 0600, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucketName))\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &boltSource{\n\t\tdb: db,\n\t\tbucket: []byte(bucketName),\n\t}, nil\n\n}", "func (s *DatatypeGeoShape) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"geo_shape\",\n\t// \t\t\"copy_to\": [\"field_1\", \"field_2\"],\n\t// \t\t\"tree\": \"quadtree\",\n\t// \t\t\"precision\": \"50m\",\n\t// \t\t\"tree_levels\": \"various\",\n\t// \t\t\"strategy\": \"recursive\",\n\t// \t\t\"distance_error_pct\": 0.0,\n\t// \t\t\"orientation\": \"ccw\",\n\t// \t\t\"points_only\": true,\n\t// \t\t\"ignore_malformed\": true,\n\t// \t\t\"ignore_z_value\": true,\n\t// \t\t\"coerce\": true\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"geo_shape\"\n\n\tif len(s.copyTo) > 0 {\n\t\tvar copyTo interface{}\n\t\tswitch {\n\t\tcase len(s.copyTo) > 1:\n\t\t\tcopyTo = s.copyTo\n\t\t\tbreak\n\t\tcase len(s.copyTo) == 1:\n\t\t\tcopyTo = s.copyTo[0]\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcopyTo = \"\"\n\t\t}\n\t\toptions[\"copy_to\"] = copyTo\n\t}\n\tif s.tree != \"\" {\n\t\toptions[\"tree\"] = s.tree\n\t}\n\tif s.precision != \"\" {\n\t\toptions[\"precision\"] = s.precision\n\t}\n\tif s.treeLevels != \"\" {\n\t\toptions[\"tree_levels\"] = s.treeLevels\n\t}\n\tif s.strategy != \"\" {\n\t\toptions[\"strategy\"] = s.strategy\n\t}\n\tif s.distanceErrorPct != nil {\n\t\toptions[\"distance_error_pct\"] = s.distanceErrorPct\n\t}\n\tif s.orientation != \"\" {\n\t\toptions[\"orientation\"] = s.orientation\n\t}\n\tif s.pointsOnly != nil {\n\t\toptions[\"points_only\"] = s.pointsOnly\n\t}\n\tif s.ignoreMalformed != nil {\n\t\toptions[\"ignore_malformed\"] = s.ignoreMalformed\n\t}\n\tif s.ignoreZValue != nil {\n\t\toptions[\"ignore_z_value\"] = s.ignoreZValue\n\t}\n\tif s.coerce != nil {\n\t\toptions[\"coerce\"] = s.coerce\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[s.name] = options\n\treturn source, nil\n}", "func CreateSourceFromDecoder(decoder SourceDecoder, dsid DatasetID, a Administration) (Source, error) {\n\treturn &sourceDecoder{decoder: decoder, id: dsid}, nil\n}", "func (m *DeviceManagementConfigurationPolicy) SetCreationSource(value *string)() {\n err := m.GetBackingStore().Set(\"creationSource\", value)\n if err != nil {\n panic(err)\n }\n}", "func (f *File) SetSource(source []string) {\n\tf.mutex.Lock()\n\tf.source = source\n\tf.mutex.Unlock()\n}", "func (h *TokenizerPathHierarchy) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"path_hierarchy\",\n\t// \t\t\"delimiter\": \"-\",\n\t// \t\t\"replacement\": \"/\",\n\t// \t\t\"butter_size\": 1024,\n\t// \t\t\"reverse\": true,\n\t// \t\t\"skip\": 2\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"path_hierarchy\"\n\n\tif h.delimiter != \"\" {\n\t\toptions[\"delimiter\"] = h.delimiter\n\t}\n\tif h.replacement != \"\" {\n\t\toptions[\"replacement\"] = h.replacement\n\t}\n\tif h.bufferSize != nil {\n\t\toptions[\"buffer_size\"] = h.bufferSize\n\t}\n\tif h.reverse != nil {\n\t\toptions[\"reverse\"] = h.reverse\n\t}\n\tif h.skip != nil {\n\t\toptions[\"skip\"] = h.skip\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[h.name] = options\n\treturn source, nil\n}", "func CreateSourceFromIterator(iterator SourceIterator, dsid DatasetID) (Source, error) {\n\treturn &sourceIterator{iterator: iterator, id: dsid}, nil\n}", "func newSource(opts ...SourceOption) *sourcesv1alpha1.HTTPSource {\n\tsrc := &sourcesv1alpha1.HTTPSource{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: tNs,\n\t\t\tName: tName,\n\t\t\tUID: tUID,\n\t\t},\n\t\tSpec: sourcesv1alpha1.HTTPSourceSpec{\n\t\t\tSource: tSource,\n\t\t},\n\t}\n\n\tsrc.Status.InitializeConditions()\n\n\tfor _, opt := range opts {\n\t\topt(src)\n\t}\n\n\treturn src\n}", "func (a *DefaultApiService) CreateSourceExecute(r ApiCreateSourceRequest) (Source, *_nethttp.Response, GenericOpenAPIError) {\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\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue Source\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"DefaultApiService.CreateSource\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/sources\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.source == nil {\n\t\texecutionError.error = \"source is required and must be specified\"\n\t\treturn localVarReturnValue, nil, executionError\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.source\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\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\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\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, executionError\n}", "func NewEnvSource(env []string) (*MapSource, error) {\n\tm := make(map[string]interface{})\n\tfor _, envStr := range env {\n\t\tparts := strings.SplitN(envStr, \"=\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse variable %s\", envStr)\n\t\t}\n\t\tname := parts[0]\n\t\tvalue := parts[1]\n\t\tpath := strings.Split(name, \"_\")\n\t\tlocation := m\n\t\tfor x := 0; x < len(path)-1; x = x + 1 {\n\t\t\tpart := path[x]\n\t\t\tif _, ok := location[part]; !ok {\n\t\t\t\tlocation[part] = make(map[string]interface{})\n\t\t\t}\n\t\t\tvar nextLocation map[string]interface{}\n\t\t\tvar ok bool\n\t\t\tif nextLocation, ok = location[part].(map[string]interface{}); !ok {\n\t\t\t\t// This condition indicates that there is a conflict while\n\t\t\t\t// interpreting the environment variables. Specifically, the\n\t\t\t\t// system is attempting to add an element to a subtree but one\n\t\t\t\t// of the parents in that tree is a value instead of a tree.\n\t\t\t\t// For example, A_B_C_D=\"value\" will result in the string \"value\"\n\t\t\t\t// being stored in {\"a\": {\"b\": {\"c\": {\"d\": \"value\"}}}}. However, if\n\t\t\t\t// there was previously an entry like A_B=\"value2\" then we would\n\t\t\t\t// have already created {\"a\": {\"b\": \"value2\"}}. The string \"value2\"\n\t\t\t\t// and the subtree {\"c\": {\"d\": \"value\"}} cannot exist under the\n\t\t\t\t// same parent of \"b\".\n\t\t\t\t//\n\t\t\t\t// This is not an issue for some of the other sources, like JSON\n\t\t\t\t// or YAML, because their structure prevents it. However, naive\n\t\t\t\t// key-value stores like ENV vars or Redis, potentially, do not\n\t\t\t\t// have an inherent hierarchy concept so this conflict can appear.\n\t\t\t\t// It's challenging to determine the best course of action here\n\t\t\t\t// because, while there are benefits to strict validation of the\n\t\t\t\t// data and returning an error for this condition, nearly every\n\t\t\t\t// environment will trigger this path. For now, we will choose to\n\t\t\t\t// ignore these conflicts. If the need arrises for a \"strict mode\"\n\t\t\t\t// then we can offer a separate component that returns an error.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlocation = nextLocation\n\t\t}\n\t\tlocation[path[len(path)-1]] = value\n\t}\n\treturn NewMapSource(m), nil\n}", "func SourceFromPath(path string) (*Source, error) {\n in, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n text, err := ioutil.ReadAll(in)\n if err != nil {\n return nil, err\n }\n return &Source{ Path : path, Text : text }, nil\n}", "func CreateMazeFromFile(fileName string) t.Maze {\n\tvar m t.Maze\n\tvar startX int\n\tvar endX int\n\n\tfile, err := os.Open(fileName)\n\tvar line string = \"\"\n\tif err != nil {\n\t\tlog.Fatal(fileName, \" File does not exist:\", err)\n\t}\n\tdefer file.Close()\n\tscanner := bufio.NewScanner(file)\n\n\tfor scanner.Scan() {\n\t\tline = scanner.Text()\n\t\tstartX = strings.Index(line, \"D\")\n\t\tendX = strings.Index(line, \"A\")\n\n\t\tif startX != -1 {\n\t\t\tm.Start = t.Point{X: startX, Y: len(m.Maze)}\n\t\t}\n\n\t\tif endX != -1 {\n\t\t\tm.End = t.Point{X: endX, Y: len(m.Maze)}\n\t\t}\n\n\t\tm.Maze = append(m.Maze, line)\n\t}\n\treturn m\n}", "func sourceTablesFromJSON(s string) (st SourceTables, err error) {\n\terr = json.Unmarshal([]byte(s), &st)\n\treturn\n}", "func newGitSource(dataType, fsPath string, partitionCount int) *GitSource {\n\tbase := filepath.Base(fsPath)\n\n\treturn &GitSource{\n\t\tpartitionCount: partitionCount,\n\t\tdataType: dataType,\n\t\tprefix: dataType,\n\t\thasHeader: true,\n\t\tfolder: filepath.Dir(fsPath),\n\t\tfileBaseName: base,\n\t\tpath: fsPath,\n\t\thasWildcard: strings.Contains(base, \"**\"),\n\t\tnestedSource: nestedSource{},\n\t}\n}", "func LoadJSON(source interface{}, state data.Map) (interface{}, error) {\n\tlocation := toolbox.AsString(source)\n\tif location == \"\" {\n\t\treturn nil, errors.New(\"location was empty at LoadJSON\")\n\t}\n\tdata, err := ioutil.ReadFile(location)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to load: %v\", location)\n\t}\n\tJSON := string(data)\n\tif toolbox.IsNewLineDelimitedJSON(JSON) {\n\t\tslice, err := toolbox.NewLineDelimitedJSON(JSON)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar result = make([]interface{}, 0)\n\t\ttoolbox.ProcessSlice(slice, func(item interface{}) bool {\n\t\t\tif item == nil {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif toolbox.IsMap(item) && len(toolbox.AsMap(item)) == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tresult = append(result, item)\n\t\t\treturn true\n\t\t})\n\t\treturn result, nil\n\t}\n\tvar result interface{}\n\terr = json.Unmarshal(data, &result)\n\treturn result, err\n}", "func ZipSource(zipFullPath string, zipFiles map[string]string) (err error) {\n\tzipSourceFile, err := os.Create(zipFullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipSourceFile.Close()\n\tzipWriter := zip.NewWriter(zipSourceFile)\n\n\tfor name, strContent := range zipFiles {\n\t\tfile, err := zipWriter.Create(name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = file.Write([]byte(strContent))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = zipWriter.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func newTarget(path string, xt, yt int) *target {\n\treturn &target{path: path, xTiles: xt, yTiles: yt}\n}", "func (m3 *DatatypeMapperMurmur3) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"murmur3\",\n\t// \t\t\"copy_to\": [\"field_1\", \"field_2\"]\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"murmur3\"\n\n\tif len(m3.copyTo) > 0 {\n\t\tvar copyTo interface{}\n\t\tswitch {\n\t\tcase len(m3.copyTo) > 1:\n\t\t\tcopyTo = m3.copyTo\n\t\t\tbreak\n\t\tcase len(m3.copyTo) == 1:\n\t\t\tcopyTo = m3.copyTo[0]\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcopyTo = \"\"\n\t\t}\n\t\toptions[\"copy_to\"] = copyTo\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[m3.name] = options\n\treturn source, nil\n}", "func (graph *Graph) SetStringTiles(strtile string) {\n\tbufreader := bytes.NewReader([]byte(strtile))\n\treader := bufio.NewReader(bufreader)\n\n\tfor y := 0; ; {\n\t\tline, _, err := reader.ReadLine()\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor x, i := 0, 0; x < graph.dimX && i < len(line); i++ {\n\t\t\tattr := line[i]\n\t\t\tswitch attr {\n\t\t\tcase START:\n\t\t\t\tgraph.start = &Point{Y: y, X: x}\n\t\t\t\tx++\n\t\t\t\tcontinue\n\t\t\tcase END:\n\t\t\t\tgraph.end = &Point{Y: y, X: x}\n\t\t\t\tx++\n\t\t\t\tcontinue\n\t\t\tcase '\\t':\n\t\t\t\tcontinue\n\t\t\tcase ' ':\n\t\t\t\tcontinue\n\t\t\tcase '\\n':\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif attr != SKIP {\n\t\t\t\tgraph.Tiles[y][x].Attr = attr\n\t\t\t}\n\t\t\tx++\n\t\t}\n\t\ty++\n\t}\n}", "func loadTiles(z uint8, x0, y0, x1, y1 int, ext string) Tiles {\n\ttiles := Tiles{\n\t\tX0: x0, X1: x1, Y0: y0, Y1: y1,\n\t\tTiles: make([]Tile, (x1-x0+1)*(y1-y0+1)),\n\t}\n\n\ti := 0\n\tfor y := y0; y <= y1; y++ {\n\t\tfor x := x0; x <= x1; x++ {\n\t\t\ttiles.Tiles[i] = Tile{\n\t\t\t\tZ: z, X: x, Y: y, Data: readFile(fmt.Sprintf(\"test_data/%v_%v_%v.%s\", z, x, y, ext)),\n\t\t\t}\n\n\t\t\ti++\n\t\t}\n\t}\n\treturn tiles\n}", "func (client DatabasesClient) CreateImportOperationPreparer(resourceGroupName string, serverName string, databaseName string, parameters ImportExtensionRequest, cancel <-chan struct{}) (*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.AsJSON(),\n\t\tautorest.AsPut(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/extensions/import\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{Cancel: cancel})\n}", "func (s *SimilarityLMJelinekMercer) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"LMJelinekMercer\",\n\t// \t\t\"lambda\": 0.1\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"LMJelinekMercer\"\n\n\tif s.lambda != nil {\n\t\toptions[\"lambda\"] = s.lambda\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[s.name] = options\n\treturn source, nil\n}", "func (t *TileData) Create(uri string, coord *binning.TileCoord, query veldt.Query) ([]byte, error) {\n\tresponseChan := make(chan batch.TileResponse, 1)\n\trequest := &batch.TileRequest{\n\t\tParams: *t.parameters,\n\t\tURI: uri,\n\t\tCoord: coord,\n\t\tQuery: query,\n\t\tResultChannel: responseChan,\n\t}\n\tt.CreateTiles([]*batch.TileRequest{request})\n\tresponse := <-responseChan\n\tif response.Tile != nil {\n\t\tDebugf(\"Create: Got response tile of length %d\", len(response.Tile))\n\t} else {\n\t\tDebugf(\"Create: Got nil response tile\")\n\t}\n\tif response.Err != nil {\n\t\tDebugf(\"Create: Got non-nil error\")\n\t} else {\n\t\tDebugf(\"Create: no error\")\n\t}\n\treturn response.Tile, response.Err\n}", "func (client ThreatIntelligenceIndicatorClient) CreatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, name string, threatIntelligenceProperties ThreatIntelligenceIndicatorModel) (*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.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\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.WithJSON(threatIntelligenceProperties),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (r Virtual_Guest_Block_Device_Template_Group) CreateFromExternalSource(configuration *datatypes.Container_Virtual_Guest_Block_Device_Template_Configuration) (resp datatypes.Virtual_Guest_Block_Device_Template_Group, err error) {\n\tparams := []interface{}{\n\t\tconfiguration,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"createFromExternalSource\", params, &r.Options, &resp)\n\treturn\n}", "func Make_Tiles_Geojson3(gjson *geojson.FeatureCollection, prefix string, zooms []int) {\n\tfmt.Print(\"Writing Layers \", zooms, \"\\n\")\n\t// reading geojson\n\ts := time.Now()\n\n\t// iterating through each zoom\n\t// creating tilemap\n\ttilemap := Make_Tilemap(gjson, zooms[0])\n\n\t// iterating through each tileid in the tilemap\n\tc := make(chan string)\n\tfor k, v := range tilemap {\n\t\tgo func(k m.TileID, v []*geojson.Feature, prefix string, c chan string) {\n\t\t\tMake_Tile(k, v, prefix)\n\t\t\tc <- \"\"\n\t\t}(k, v, prefix, c)\n\t}\n\tcount := 0\n\tsizetilemap := len(tilemap)\n\tfor range tilemap {\n\t\tmsg1 := <-c\n\t\tfmt.Printf(\"\\r[%d / %d] Tiles Complete of Size %d%s\", count, sizetilemap, zooms[0], msg1)\n\t\tcount += 1\n\t}\n\ttilemap = Make_Tilemap_Children(tilemap, prefix)\n\ttilemap = Make_Tilemap_Children(tilemap, prefix)\n\n\tMake_Tilemap_Children2(tilemap, prefix, zooms[len(zooms)-1])\n\n\tfmt.Printf(\"\\nCompleted in %s.\\n\", time.Now().Sub(s))\n}", "func New(path string, mask int, d debug.Debugger) (*Source, error) {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn nil, ErrFileNotFound\n\t}\n\n\tts := &Source{\n\t\tpath: path,\n\t\ttoken: new(oauth2.Token),\n\t\tmask: mask,\n\t\tDebugger: d,\n\t}\n\tts.readToken()\n\n\treturn ts, nil\n}", "func JWKSFileSource(filepath string) (*jwks.DummySource, error) {\n\tb, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn JWKSByteSource(b)\n}", "func (res *Resource) Source(properties map[string]interface{}) {\n\t// KeyName\n\tres.KeyName = StringValue(properties, KeyName, res.PhysicalID)\n\n\t// ParameterName\n\tif path := StringValue(properties, ParameterPath, DefaultParameterPath); path == \"\" {\n\t\tres.ParameterName = res.KeyName\n\t} else {\n\t\tres.ParameterName = fmt.Sprintf(\"%s/%s\", path, res.KeyName)\n\t}\n\n\t// ParameterKeyID\n\tres.ParameterKeyID = StringValue(properties, ParameterKeyID, DefaultParameterKeyID)\n}", "func CreateTarFromSrc(source string, dest string) error {\n\tfile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create tarball file '%s': %w\", dest, err)\n\t}\n\tdefer file.Close()\n\treturn TarChrootToFilesystem(source, file)\n}", "func (client FeatureStateClient) GetStatesetPreparer(ctx context.Context, statesetID string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"statesetId\": autorest.Encode(\"path\",statesetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsGet(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/featureStateSets/{statesetId}\",pathParameters),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func NewConfigFromPath(jsonPath string) (*Config, error) {\n\n\tfile, err := ioutil.ReadFile(jsonPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading JSON file : %v\", err)\n\t}\n\tc := &Config{}\n\terr = json.Unmarshal(file, c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error parsing JSON : %v\", err)\n\t}\n\terr = c.makeScenarioMap()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error making scenario map : %v\", err)\n\t}\n\treturn c, nil\n}", "func NewSourceData(name string, data []byte) Source {\n\treturn &sourceData{sourceBase{name}, data}\n}", "func NewDataSource(ctx *pulumi.Context,\n\tname string, args *DataSourceArgs, opts ...pulumi.ResourceOption) (*DataSource, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.IndexId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'IndexId'\")\n\t}\n\tif args.Type == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Type'\")\n\t}\n\tvar resource DataSource\n\terr := ctx.RegisterResource(\"aws:kendra/dataSource:DataSource\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func Read(reader io.Reader) (s SourceMap, err error) {\n\tvar jsonMap jsonSourceMap\n\tvar lines []Line\n\n\tdec := json.NewDecoder(reader)\n\tif err = dec.Decode(&jsonMap); err != nil {\n\t\treturn\n\t}\n\n\tif jsonMap.Version != 3 {\n\t\terr = fmt.Errorf(\"unsupported version: %v\", s.Version)\n\t}\n\n\tif lines, err = parseMappings(jsonMap.Mappings); err != nil {\n\t\treturn\n\t}\n\n\t// Populate the source map structure.\n\ts.Version = jsonMap.Version\n\ts.File = jsonMap.File\n\ts.SourceRoot = jsonMap.SourceRoot\n\ts.Sources = jsonMap.Sources\n\ts.SourcesContent = jsonMap.SourcesContent\n\ts.Names = jsonMap.Names\n\ts.Mappings = lines\n\n\treturn\n}", "func SetFromSourceToFile(src source.Source, dst, name string) error {\n\tif dst == \"\" {\n\t\treturn errors.New(\"dst file path is empty\")\n\t}\n\n\td, err := destination.NewFile(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SetFromSourceToDestination(src, d, name)\n}", "func Make_Tile_Geojson2(tileid m.TileID,layername string,features_str []*geojson.Feature) []byte {\n\t// getitng featuerstr\n\tvar bytevals []byte\n\tif len(features_str) > 100000000 {\n\t\t//fmt.Println(\"concurrent\")\n\t} else {\n\n\t\t// intializing shit for cursor\n\t\tbound := m.Bounds(tileid)\n\t\tdeltax := bound.E-bound.W\n\t\tdeltay := bound.N - bound.S\n\n\t\t// random intializatioin for property collection\n\t\tvar keys []string\n\t\tvar values []*vector_tile.Tile_Value\n\t\tkeysmap := map[string]uint32{}\n\t\tvaluesmap := map[*vector_tile.Tile_Value]uint32{}\n\n\t\t// iterating through each feature\n\t\tfeatures := []*vector_tile.Tile_Feature{}\n\t\t\n\t\t// setting and converting coordinate\t\n\t\tcur := Cursor{LastPoint:[]int32{0,0},Bounds:bound,DeltaX:deltax,DeltaY:deltay,Count:0}\n\t\tcur = Convert_Cursor(cur)\n\t\tvar bytevals []byte\n\n\t\t// creating new mapper\n\t\t\n\t\t//position := []int32{0, 0}\n\t\tfor _,i := range features_str {\n\t\t\t// appplying the soft boudning box filter\n\t\t\t\t\n\t\t\t\t// getitng the featuer\t\t\n\t\t\n\n\t\t\t\t// adding properties and getting correct tags\n\t\t\t\tvar tags, geometry []uint32\n\t\t\t\tvar feat vector_tile.Tile_Feature\n\t\t\t\ttags, keys, values, keysmap, valuesmap = Update_Properties(i.Properties, keys, values, keysmap, valuesmap)\n\t\t\t\t//fmt.Println(i.Geometry)\n\t\t\t\t// logic for point feature'\n\t\t\t\tif i.Geometry == nil {\n\n\t\t\t\t} else if i.Geometry.Type == \"Point\" {\n\t\t\t\t\tgeometry = cur.Make_Point_Float(i.Geometry.Point)\n\t\t\t\t\tfeat_type := vector_tile.Tile_POINT\n\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\tfeatures = append(features, &feat)\n\n\t\t\t\t} else if i.Geometry.Type == \"LineString\" {\n\t\t\t\t\tif len(i.Geometry.LineString) >= 2 {\n\t\t\t\t\t\tgeometry = cur.Make_Line_Float(i.Geometry.LineString)\n\t\t\t\t\t\tif geometry[3] > 2 {\n\t\t\t\t\t\t\tfeat_type := vector_tile.Tile_LINESTRING\n\t\t\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\t\t\tfeatures = append(features, &feat)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t} else if i.Geometry.Type == \"Polygon\" {\n\t\t\t\t\tgeometry = cur.Make_Polygon_Float(i.Geometry.Polygon)\n\t\t\t\t\tfeat_type := vector_tile.Tile_POLYGON\n\t\t\t\t\tfeat = vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\tfeatures = append(features, &feat)\n\t\t\t\t}\n\t\t}\n\n\t\t//fmt.Println(len(features))\n\t\tif len(features) > 0 {\n\t\t\tlayerVersion := uint32(15)\n\t\t\textent := vector_tile.Default_Tile_Layer_Extent\n\t\t\t//var bound []Bounds\n\t\t\tlayer := vector_tile.Tile_Layer{\n\t\t\t\tVersion: &layerVersion,\n\t\t\t\tName: &layername,\n\t\t\t\tExtent: &extent,\n\t\t\t\tValues: values,\n\t\t\t\tKeys: keys,\n\t\t\t\tFeatures: features,\n\t\t\t}\n\n\t\t\ttile := vector_tile.Tile{}\n\t\t\ttile.Layers = append(tile.Layers, &layer)\n\t\t\tbytevals,_ = proto.Marshal(&tile)\n\t\t\t//if len(bytevals) > 0 {\n\t\t\t//\tmbtile.Add_Tile(tileid,bytevals)\n\t\t\t//}\n\t\t} else {\n\t\t\tbytevals = []byte{}\n\t\t}\n\t\tif len(bytevals) > 0 { \n\t\t}\n\t}\n\treturn bytevals\n}", "func PatchTestSource(fpath string, r io.Reader) (io.Reader, error) {\n\tc, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Patch the path to a shard by adding quotes around the shard number,\n\t// which is a map key, not an array index.\n\tfor _, p := range []string{\n\t\t\"indices.flush/10_basic.yml\",\n\t\t\"indices.put_template/10_basic.yml\",\n\t\t\"indices.recovery/10_basic.yml\",\n\t\t\"indices.segments/10_basic.yml\",\n\t\t\"indices.shard_stores/10_basic.yml\",\n\t\t\"indices.stats/12_level.yml\",\n\t} {\n\t\tif strings.Contains(fpath, p) {\n\t\t\tc = rePatchShardKeys.ReplaceAll(c, []byte(`shards.\"$1\".$2`))\n\t\t\tc = rePatchShardStoresKeys.ReplaceAll(c, []byte(`shards.\"$1\".stores.$2`))\n\t\t}\n\t}\n\n\tfor _, p := range []string{\n\t\t\"search.aggregation/230_composite.yml\",\n\t} {\n\t\tif strings.Contains(fpath, p) {\n\t\t\tc = rePatchBucketKeys.ReplaceAll(c, []byte(`aggregations.\"$1\".\"$2\".buckets`))\n\t\t}\n\t}\n\n\treturn bytes.NewReader(c), nil\n}", "func CreateFromJson(_json string) Geometry {\n\tcString := C.CString(_json)\n\tdefer C.free(unsafe.Pointer(cString))\n\tvar newGeom Geometry\n\tnewGeom.cval = C.OGR_G_CreateGeometryFromJson(cString)\n\treturn newGeom\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Make_Tiles_Geojson(gjson *geojson.FeatureCollection, prefix string, zooms []int) {\n\t// reading geojson\n\ts := time.Now()\n\t// iterating through each zoom\n\tfor _, i := range zooms {\n\t\t// creating tilemap\n\t\ttilemap := Make_Tilemap(gjson, i)\n\n\t\t// iterating through each tileid in the tilemap\n\t\tc := make(chan string)\n\t\tfor k, v := range tilemap {\n\t\t\tgo func(k m.TileID, v []*geojson.Feature, prefix string, c chan string) {\n\t\t\t\tMake_Tile(k, v, prefix)\n\t\t\t\tc <- \"\"\n\t\t\t}(k, v, prefix, c)\n\t\t}\n\t\tcount := 0\n\t\tsizetilemap := len(tilemap)\n\t\tfor range tilemap {\n\t\t\tmsg1 := <-c\n\t\t\tfmt.Printf(\"\\r[%d / %d] Tiles Complete of Size %d%s\", count, sizetilemap, i, msg1)\n\t\t\tcount += 1\n\t\t}\n\n\t}\n\tfmt.Printf(\"\\nCompleted in %s.\\n\", time.Now().Sub(s))\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 (d *TileDB) Tile(revision int, path []byte) (*batchmap.Tile, error) {\n\tvar bs []byte\n\tif err := d.db.QueryRow(\"SELECT tile FROM tiles WHERE revision=? AND path=?\", revision, path).Scan(&bs); err != nil {\n\t\treturn nil, err\n\t}\n\ttile := &batchmap.Tile{}\n\tif err := json.Unmarshal(bs, tile); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse tile at revision=%d, path=%x: %v\", revision, path, err)\n\t}\n\treturn tile, nil\n}", "func (d *btrfs) Create() error {\n\t// Store the provided source as we are likely to be mangling it.\n\td.config[\"volatile.initial_source\"] = d.config[\"source\"]\n\n\trevert := revert.New()\n\tdefer revert.Fail()\n\n\terr := d.FillConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloopPath := loopFilePath(d.name)\n\tif d.config[\"source\"] == \"\" || d.config[\"source\"] == loopPath {\n\t\t// Create a loop based pool.\n\t\td.config[\"source\"] = loopPath\n\n\t\t// Create the loop file itself.\n\t\tsize, err := units.ParseByteSizeString(d.config[\"size\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = ensureSparseFile(d.config[\"source\"], size)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create the sparse file: %w\", err)\n\t\t}\n\n\t\trevert.Add(func() { _ = os.Remove(d.config[\"source\"]) })\n\n\t\t// Format the file.\n\t\t_, err = makeFSType(d.config[\"source\"], \"btrfs\", &mkfsOptions{Label: d.name})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to format sparse file: %w\", err)\n\t\t}\n\t} else if shared.IsBlockdevPath(d.config[\"source\"]) {\n\t\t// Wipe if requested.\n\t\tif shared.IsTrue(d.config[\"source.wipe\"]) {\n\t\t\terr := wipeBlockHeaders(d.config[\"source\"])\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to wipe headers from disk %q: %w\", d.config[\"source\"], err)\n\t\t\t}\n\n\t\t\td.config[\"source.wipe\"] = \"\"\n\t\t}\n\n\t\t// Format the block device.\n\t\t_, err := makeFSType(d.config[\"source\"], \"btrfs\", &mkfsOptions{Label: d.name})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to format block device: %w\", err)\n\t\t}\n\n\t\t// Record the UUID as the source.\n\t\tdevUUID, err := fsUUID(d.config[\"source\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Confirm that the symlink is appearing (give it 10s).\n\t\tif tryExists(fmt.Sprintf(\"/dev/disk/by-uuid/%s\", devUUID)) {\n\t\t\t// Override the config to use the UUID.\n\t\t\td.config[\"source\"] = devUUID\n\t\t}\n\t} else if d.config[\"source\"] != \"\" {\n\t\thostPath := d.config[\"source\"]\n\t\tif d.isSubvolume(hostPath) {\n\t\t\t// Existing btrfs subvolume.\n\t\t\tsubvols, err := d.getSubvolumes(hostPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Could not determine if existing btrfs subvolume is empty: %w\", err)\n\t\t\t}\n\n\t\t\t// Check that the provided subvolume is empty.\n\t\t\tif len(subvols) > 0 {\n\t\t\t\treturn fmt.Errorf(\"Requested btrfs subvolume exists but is not empty\")\n\t\t\t}\n\t\t} else {\n\t\t\t// New btrfs subvolume on existing btrfs filesystem.\n\t\t\tcleanSource := filepath.Clean(hostPath)\n\t\t\tdaemonDir := shared.VarPath()\n\n\t\t\tif shared.PathExists(hostPath) {\n\t\t\t\thostPathFS, _ := filesystem.Detect(hostPath)\n\t\t\t\tif hostPathFS != \"btrfs\" {\n\t\t\t\t\treturn fmt.Errorf(\"Provided path does not reside on a btrfs filesystem\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(cleanSource, daemonDir) {\n\t\t\t\tif cleanSource != GetPoolMountPath(d.name) {\n\t\t\t\t\treturn fmt.Errorf(\"Only allowed source path under %q is %q\", shared.VarPath(), GetPoolMountPath(d.name))\n\t\t\t\t}\n\n\t\t\t\tstoragePoolDirFS, _ := filesystem.Detect(shared.VarPath(\"storage-pools\"))\n\t\t\t\tif storagePoolDirFS != \"btrfs\" {\n\t\t\t\t\treturn fmt.Errorf(\"Provided path does not reside on a btrfs filesystem\")\n\t\t\t\t}\n\n\t\t\t\t// Delete the current directory to replace by subvolume.\n\t\t\t\terr := os.Remove(cleanSource)\n\t\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\t\treturn fmt.Errorf(\"Failed to remove %q: %w\", cleanSource, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Create the subvolume.\n\t\t\t_, err := shared.RunCommand(\"btrfs\", \"subvolume\", \"create\", hostPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(`Invalid \"source\" property`)\n\t}\n\n\trevert.Success()\n\treturn nil\n}", "func (mbutil Mbtiles) Make_Tile_Geojson_Concurrent(tileid m.TileID,features_str []*geojson.Feature) {\n\t// intializing shit for cursor\n\tbound := m.Bounds(tileid)\n\tdeltax := bound.E-bound.W\n\tdeltay := bound.N - bound.S\n\n\n\tfeatures := []*vector_tile.Tile_Feature{}\n\tc := make(chan *vector_tile.Tile_Feature)\n\t// setting and converting coordinate\t\n\tcur := Cursor{LastPoint:[]int32{0,0},Bounds:bound,DeltaX:deltax,DeltaY:deltay,Count:0}\n\tcur = Convert_Cursor(cur)\t\n\tvar bytevals []byte\n\tvar mapme sync.Map \n\tconfig := &Properties_Config{KeysMap:&mapme,ValuesMap:&mapme}\n\tguard := make(chan struct{}, 100) // 10000 concurrent processes for reading\n\n\tfor _,feat := range features_str {\n\t\tguard <- struct{}{}\n\t\t// creating cursor used in geometry creation\n\t\t//i := geobuf.\n\t\tgo func(i *geojson.Feature,c chan *vector_tile.Tile_Feature) {\n\t\t\t<-guard\n\n\t\t\ttags := config.Update_Properties(i.Properties)\n\t\t\tvar geometry []uint32\n\t\t\t// logic for point feature\n\t\t\tif i.Geometry == nil {\n\t\t\t\tc <- &vector_tile.Tile_Feature{}\n\t\t\t} else if i.Geometry.Type == \"Point\" {\n\t\t\t\tgeometry = cur.Make_Point_Float(i.Geometry.Point)\n\t\t\t\tfeat_type := vector_tile.Tile_POINT\n\t\t\t\tc <- &vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t//features = append(features, &feat)\n\t\t\t} else if i.Geometry.Type == \"LineString\" {\n\t\t\t\tif len(i.Geometry.LineString) >= 2 {\n\t\t\t\t\tgeometry = cur.Make_Line_Float(i.Geometry.LineString)\n\t\t\t\t\tif geometry[3] > 2 {\n\t\t\t\t\t\tfeat_type := vector_tile.Tile_LINESTRING\n\t\t\t\t\t\tc <- &vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t\t\t//features = append(features, &feat)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tc <- &vector_tile.Tile_Feature{}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc <- &vector_tile.Tile_Feature{}\n\t\t\t\t}\n\t\t\t} else if i.Geometry.Type == \"Polygon\" {\n\t\t\t\tgeometry = cur.Make_Polygon_Float(i.Geometry.Polygon)\n\t\t\t\tfeat_type := vector_tile.Tile_POLYGON\n\t\t\t\tc <- &vector_tile.Tile_Feature{Tags: tags, Type: &feat_type, Geometry: geometry}\n\t\t\t\t//features = append(features, &feat)\n\t\t\t} else {\n\t\t\t\tc <- &vector_tile.Tile_Feature{}\n\t\t\t}\n\t\t}(feat,c)\n\t}\t\n\n\tfor range features_str {\n\t\tout := <-c\n\t\tif len(out.Geometry) > 0 {\n\t\t\tfeatures = append(features,out)\n\t\t}\n\t}\n\n\tlayerVersion := uint32(15)\n\textent := vector_tile.Default_Tile_Layer_Extent\n\t//var bound []Bounds\n\tlayername := mbutil.LayerName\n\tlayer := vector_tile.Tile_Layer{\n\t\tVersion: &layerVersion,\n\t\tName: &layername,\n\t\tExtent: &extent,\n\t\tValues: config.Values,\n\t\tKeys: config.Keys,\n\t\tFeatures: features,\n\t}\n\ttile := vector_tile.Tile{}\n\ttile.Layers = append(tile.Layers, &layer)\n\tbytevals,_ = proto.Marshal(&tile)\n\tif len(bytevals) > 0 { \n\t\tmbutil.Add_Tile(tileid,bytevals)\n\t}\n}", "func newSourceDatastore(lookup environment.Environmenter) (*sourceDatastore, error) {\n\turl := fmt.Sprintf(\n\t\t\"%s://%s:%s\",\n\t\tenvDatastoreProtocol.Value(lookup),\n\t\tenvDatastoreHost.Value(lookup),\n\t\tenvDatastorePort.Value(lookup),\n\t)\n\n\ttimeout, err := environment.ParseDuration(envDatastoreTimeout.Value(lookup))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing timeout: %w\", err)\n\t}\n\n\tmaxParallel, err := strconv.Atoi(envDatastoreMaxParallelKeys.Value(lookup))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"environment variable MAX_PARALLEL_KEYS has to be a number, not %s\",\n\t\t\tenvDatastoreMaxParallelKeys.Value(lookup),\n\t\t)\n\t}\n\n\tsource := sourceDatastore{\n\t\turl: url,\n\t\tclient: &http.Client{\n\t\t\tTimeout: timeout,\n\t\t},\n\t\tmaxKeysPerRequest: maxParallel,\n\t}\n\n\treturn &source, nil\n}", "func ImportGeoJSONFile(filename string, debug bool, fields []string) error {\n\tvar loopID int\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar geo geojson.FeatureCollection\n\n\terr = json.Unmarshal(b, &geo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar geoData GeoData\n\n\tcl := make(map[s2.CellID][]int)\n\n\tfor _, f := range geo.Features {\n\t\tgeom, err := f.GetGeometry()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trc := &s2.RegionCoverer{MinLevel: 1, MaxLevel: 30, MaxCells: 8}\n\n\t\tswitch geom.GetType() {\n\t\tcase \"Polygon\":\n\t\t\tmp := geom.(*geojson.Polygon)\n\t\t\t// multipolygon\n\t\t\tfor _, p := range mp.Coordinates {\n\t\t\t\t// polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []CPoint\n\t\t\t\t// For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t// \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t// For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\n\t\t\t\t// reverse the slice\n\t\t\t\tfor i := len(p)/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t// do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, CPoint{Coordinate: []float64{float64(c[1]), float64(c[0])}})\n\t\t\t\t}\n\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\tr := RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellUnion: covering,\n\t\t\t\t}\n\n\t\t\t\tgeoData.RS = append(geoData.RS, r)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\n\t\tcase \"MultiPolygon\":\n\t\t\tmp := geom.(*geojson.MultiPolygon)\n\t\t\t// multipolygon\n\t\t\tfor _, m := range mp.Coordinates {\n\t\t\t\t// polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []CPoint\n\t\t\t\t// For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t// \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t// For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\t\t\t\tif len(m) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tp := m[0]\n\t\t\t\t// coordinates\n\n\t\t\t\t// reverse the slice\n\t\t\t\tfor i := len(p)/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t// do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, CPoint{Coordinate: []float64{float64(c[1]), float64(c[0])}})\n\t\t\t\t}\n\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\tr := RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellUnion: covering,\n\t\t\t\t}\n\n\t\t\t\tgeoData.RS = append(geoData.RS, r)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.New(\"unknown type\")\n\t\t}\n\n\t}\n\n\tfor k, v := range cl {\n\t\tgeoData.CL = append(geoData.CL, CellIDLoopStorage{C: k, Loops: v})\n\t}\n\n\tlog.Println(\"imported\", filename, len(geoData.RS), \"regions\")\n\n\tb, err = msgpack.Marshal(geoData)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"geodata\", b, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *DatatypeGeoPoint) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"geo_point\",\n\t// \t\t\"copy_to\": [\"field_1\", \"field_2\"],\n\t// \t\t\"ignore_malformed\": true,\n\t// \t\t\"ignore_z_value\": true,\n\t// \t\t\"null_value\": [ 0, 0 ]\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"geo_point\"\n\n\tif len(p.copyTo) > 0 {\n\t\tvar copyTo interface{}\n\t\tswitch {\n\t\tcase len(p.copyTo) > 1:\n\t\t\tcopyTo = p.copyTo\n\t\t\tbreak\n\t\tcase len(p.copyTo) == 1:\n\t\t\tcopyTo = p.copyTo[0]\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcopyTo = \"\"\n\t\t}\n\t\toptions[\"copy_to\"] = copyTo\n\t}\n\tif p.ignoreMalformed != nil {\n\t\toptions[\"ignore_malformed\"] = p.ignoreMalformed\n\t}\n\tif p.ignoreZValue != nil {\n\t\toptions[\"ignore_z_value\"] = p.ignoreZValue\n\t}\n\tif p.nullValue != nil {\n\t\toptions[\"null_value\"] = p.nullValue\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[p.name] = options\n\treturn source, nil\n}", "func NewSatelliteDataset(dataset string, imageType string, rawFilePath string) (*Satellite, error) {\n\texpandedInfo, err := ExpandZipDataset(rawFilePath, dataset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Satellite{\n\t\tDataset: dataset,\n\t\tImageType: imageType,\n\t\tRawFilePath: expandedInfo.RawFilePath,\n\t\tExtractedFilePath: expandedInfo.ExtractedFilePath,\n\t}, nil\n}" ]
[ "0.6848556", "0.55987674", "0.5551357", "0.5504878", "0.52943933", "0.48837715", "0.48816705", "0.48532996", "0.4792988", "0.47518417", "0.4721573", "0.4709976", "0.45843259", "0.45751652", "0.45683601", "0.45579433", "0.4538929", "0.447754", "0.44282672", "0.44276345", "0.44043976", "0.44027287", "0.4387681", "0.438311", "0.43404797", "0.43206114", "0.42721444", "0.42711014", "0.426922", "0.4261049", "0.4231076", "0.42172787", "0.4212192", "0.4190102", "0.41818678", "0.4171941", "0.41678786", "0.4167868", "0.41672897", "0.41663507", "0.4153257", "0.4151795", "0.41513672", "0.4149866", "0.41297817", "0.41151965", "0.41145778", "0.41120064", "0.40815604", "0.40665537", "0.4066317", "0.40647793", "0.40608212", "0.40355244", "0.40304083", "0.40252686", "0.40249333", "0.40180805", "0.40169847", "0.40078133", "0.39849874", "0.3980132", "0.39745563", "0.39697367", "0.39536333", "0.3946602", "0.39447474", "0.39426807", "0.39401963", "0.393926", "0.39193556", "0.3917412", "0.39168704", "0.3912657", "0.3911474", "0.3909158", "0.39035806", "0.39026383", "0.3889658", "0.38778457", "0.38745755", "0.3870175", "0.38679197", "0.38673103", "0.3866995", "0.3865076", "0.3863697", "0.3859247", "0.38581598", "0.38579455", "0.38525832", "0.3844821", "0.383997", "0.38381183", "0.38224715", "0.38221946", "0.38195348", "0.38155726", "0.38013023", "0.3799437" ]
0.7586447
0
PutTilesetSource replaces a tileset source with new data, or creates a new tileset source if it does not already exist. The provided path should point to a file containing one GeoJSON feature object per line.
func (c *Client) PutTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) { url := baseURL + "/tilesets/v1/sources/" + c.username + "/" + tilesetID + "?access_token=" + c.accessToken var jsonResp NewTilesetSourceResponse resp, err := putMultipart(ctx, c.httpClient, url, "filenamedoesntmatter", jsonReader) if err != nil { return jsonResp, fmt.Errorf("upload %w failed, %v", ErrOperation, err) } if resp.StatusCode != http.StatusOK { return jsonResp, fmt.Errorf("upload %w failed, non-200 response: %v", ErrOperation, resp.StatusCode) } if err = json.NewDecoder(resp.Body).Decode(&jsonResp); err != nil { return jsonResp, fmt.Errorf("%w failed, err: %v", ErrParse, err) } return jsonResp, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) CreateTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {\n\treturn c.PutTilesetSource(ctx, tilesetID, jsonReader)\n}", "func (f *File) SetSource(source []string) {\n\tf.mutex.Lock()\n\tf.source = source\n\tf.mutex.Unlock()\n}", "func (this *osmSourceStruct) tilePath(template string, zoom uint8, x uint32, y uint32) string {\n\tzoom64 := uint64(zoom)\n\tzoomString := strconv.FormatUint(zoom64, BASE_DECIMAL)\n\tx64 := uint64(x)\n\txString := strconv.FormatUint(x64, BASE_DECIMAL)\n\ty64 := uint64(y)\n\tyString := strconv.FormatUint(y64, BASE_DECIMAL)\n\ttemplate = strings.Replace(template, TEMPLATE_ZOOM, zoomString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_X, xString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_Y, yString, ALL)\n\treturn template\n}", "func (m *ItemFacet) SetSource(value PersonDataSourcesable)() {\n err := m.GetBackingStore().Set(\"source\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetSource(theMap core.Element, newSource core.Element, attributeName core.AttributeName, trans *core.Transaction) error {\n\tref := theMap.GetFirstOwnedReferenceRefinedFromURI(CrlMapSourceURI, trans)\n\tif ref == nil {\n\t\treturn errors.New(\"CrlMaps.SetSource called with map that does not have a source reference\")\n\t}\n\treturn ref.SetReferencedConcept(newSource, attributeName, trans)\n}", "func NewTileSet(ctx context.Context, path string) (t *pb.TileSet, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tt = &pb.TileSet{}\n\td := tsx.NewDecoder(f)\n\terr = d.Decode(t)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"marshal\")\n\t\treturn\n\t}\n\treturn\n}", "func (s *Service) PutSource(ctx context.Context, src *influxdb.Source) error {\n\treturn s.kv.Update(ctx, func(tx Tx) error {\n\t\treturn s.putSource(ctx, tx, src)\n\t})\n}", "func (t *Tileset) UploadGeoJSON(pathToFile string) (*UploadResponse, error) {\n\tpostURL := fmt.Sprintf(\"%s/%s/sources/%s/%s\", apiName, apiVersion, t.username, t.tilesetID)\n\tuploadResponse := &UploadResponse{}\n\tres, err := t.base.PostUploadFileRequest(postURL, pathToFile, \"file\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(res, uploadResponse)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn uploadResponse, nil\n\n}", "func (c *CSV) SetSource(s string) {\n\tc.source = NewResource(s, FmtCSV, File)\n}", "func (h *Hop) SetSource(src string) {\n\tif h == nil || len(h.Errors) == 0 {\n\t\treturn\n\t}\n\n\th.Errors[0].Source = src\n}", "func (d *Database) SetTile(height, level, offset int, hashes []byte) error {\n\t_, err := d.db.Exec(\"INSERT INTO tiles (height, level, offset, hashes) VALUES (?, ?, ?, ?)\", height, level, offset, hashes)\n\treturn err\n}", "func SetFromSourceToFile(src source.Source, dst, name string) error {\n\tif dst == \"\" {\n\t\treturn errors.New(\"dst file path is empty\")\n\t}\n\n\td, err := destination.NewFile(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SetFromSourceToDestination(src, d, name)\n}", "func (m *CopyToDefaultContentLocationPostRequestBody) SetSourceFile(value iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ItemReferenceable)() {\n m.sourceFile = value\n}", "func (d *Dir) Set(path string, file reflow.File) {\n\tif d.contents == nil {\n\t\td.contents = make(map[string]reflow.File)\n\t}\n\td.contents[path] = file\n}", "func (s *Store) replacePluginCacheFileWithSource(pluginItem *PluginInfo, entityKey string) error {\n\tsourceFilePath := s.SourceFilePath(pluginItem, entityKey)\n\tcachedFilePath := s.cachedFilePath(pluginItem, entityKey)\n\treturn helpers.CopyFile(sourceFilePath, cachedFilePath)\n}", "func (t *TransientDescriptor) SetSource(source *StableDescriptor) (*TransientDescriptor, error) {\n\tif t == nil {\n\t\treturn nil, errors.New(\"reference to transient descriptor is nil\")\n\t}\n\n\tif source == nil {\n\t\treturn nil, errors.New(\"nil pointer value for `source` parameter\")\n\t}\n\n\tt.Lock()\n\tdefer t.Unlock()\n\n\terr := source.IsStable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.source = source\n\treturn t, nil\n}", "func SetTemplate(t *template.Template, name, filename string) error {\n\n\t// Read template\n\tbuf, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update if exists\n\tif tt := t.Lookup(name); tt != nil {\n\t\t_, err = tt.Parse(string(buf))\n\t\treturn err\n\t}\n\n\t// Allocate new name if not\n\t_, err = t.New(name).Parse(string(buf))\n\treturn err\n}", "func (pr *Parser) SetSrc(src [][]rune, fname string) {\n}", "func (_m *requestHeaderMapUpdatable) SetPath(path string) {\n\t_m.Called(path)\n}", "func (o *PluginMount) SetSource(v string) {\n\to.Source = v\n}", "func (t *targetCache) Put(path string, target *dep.ResolvedTarget) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tif t.data == nil {\n\t\tt.data = make(map[string]*dep.ResolvedTarget)\n\t}\n\tt.data[path] = target\n}", "func (obj Player) SetTile(x, y, z int) error {\n\ts := fmt.Sprintf(\"player.setTile(%s,%d,%d,%d)\",obj.name, x, y, z)\n\treturn object(obj.obj).send(s)\n}", "func (o *ContentUnitDerivation) SetSource(exec boil.Executor, insert bool, related *ContentUnit) 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 \\\"content_unit_derivations\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"source_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, contentUnitDerivationPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.SourceID, o.DerivedID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\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.SourceID = related.ID\n\tif o.R == nil {\n\t\to.R = &contentUnitDerivationR{\n\t\t\tSource: related,\n\t\t}\n\t} else {\n\t\to.R.Source = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &contentUnitR{\n\t\t\tSourceContentUnitDerivations: ContentUnitDerivationSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.SourceContentUnitDerivations = append(related.R.SourceContentUnitDerivations, o)\n\t}\n\n\treturn nil\n}", "func (client FeatureStateClient) PutStatesetPreparer(ctx context.Context, statesetID string, statesetStyleUpdateRequestBody StylesObject) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n pathParameters := map[string]interface{} {\n \"statesetId\": autorest.Encode(\"path\",statesetID),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPut(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPathParameters(\"/featureStateSets/{statesetId}\",pathParameters),\nautorest.WithJSON(statesetStyleUpdateRequestBody),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (graph *Graph) SetStringTiles(strtile string) {\n\tbufreader := bytes.NewReader([]byte(strtile))\n\treader := bufio.NewReader(bufreader)\n\n\tfor y := 0; ; {\n\t\tline, _, err := reader.ReadLine()\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor x, i := 0, 0; x < graph.dimX && i < len(line); i++ {\n\t\t\tattr := line[i]\n\t\t\tswitch attr {\n\t\t\tcase START:\n\t\t\t\tgraph.start = &Point{Y: y, X: x}\n\t\t\t\tx++\n\t\t\t\tcontinue\n\t\t\tcase END:\n\t\t\t\tgraph.end = &Point{Y: y, X: x}\n\t\t\t\tx++\n\t\t\t\tcontinue\n\t\t\tcase '\\t':\n\t\t\t\tcontinue\n\t\t\tcase ' ':\n\t\t\t\tcontinue\n\t\t\tcase '\\n':\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif attr != SKIP {\n\t\t\t\tgraph.Tiles[y][x].Attr = attr\n\t\t\t}\n\t\t\tx++\n\t\t}\n\t\ty++\n\t}\n}", "func PatchTestSource(fpath string, r io.Reader) (io.Reader, error) {\n\tc, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Patch the path to a shard by adding quotes around the shard number,\n\t// which is a map key, not an array index.\n\tfor _, p := range []string{\n\t\t\"indices.flush/10_basic.yml\",\n\t\t\"indices.put_template/10_basic.yml\",\n\t\t\"indices.recovery/10_basic.yml\",\n\t\t\"indices.segments/10_basic.yml\",\n\t\t\"indices.shard_stores/10_basic.yml\",\n\t\t\"indices.stats/12_level.yml\",\n\t} {\n\t\tif strings.Contains(fpath, p) {\n\t\t\tc = rePatchShardKeys.ReplaceAll(c, []byte(`shards.\"$1\".$2`))\n\t\t\tc = rePatchShardStoresKeys.ReplaceAll(c, []byte(`shards.\"$1\".stores.$2`))\n\t\t}\n\t}\n\n\tfor _, p := range []string{\n\t\t\"search.aggregation/230_composite.yml\",\n\t} {\n\t\tif strings.Contains(fpath, p) {\n\t\t\tc = rePatchBucketKeys.ReplaceAll(c, []byte(`aggregations.\"$1\".\"$2\".buckets`))\n\t\t}\n\t}\n\n\treturn bytes.NewReader(c), nil\n}", "func (m *ServicePrincipalRiskDetection) SetSource(value *string)() {\n err := m.GetBackingStore().Set(\"source\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *DefaultSelector) SetSource(name string) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.onDataCb == nil {\n\t\treturn fmt.Errorf(\"selector callback not set\")\n\t}\n\n\tif _, ok := s.sources[name]; !ok {\n\t\treturn fmt.Errorf(\"unknown source %s\", name)\n\t}\n\n\tfor _, src := range s.sources {\n\t\tsrc.active = false\n\t\tsrc.Stop()\n\t\tsrc.SetCb(nil)\n\t}\n\n\ts.sources[name].active = true\n\ts.sources[name].SetCb(s.onDataCb)\n\ts.sources[name].Start()\n\n\treturn nil\n}", "func NewSource(path string) *Source {\n\treturn &Source{Path: path}\n}", "func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error {\n\tclient := &http.Client{}\n\n\turlPath := strings.TrimSuffix(filepath.Join(\"/v1/data\"+path), \"/\")\n\n\treq, err := http.NewRequest(\"PUT\", t.URL()+urlPath, data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unexpected error creating request: %s\", err)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to PUT data: %s\", err)\n\t}\n\tif resp.StatusCode != http.StatusNoContent {\n\t\treturn fmt.Errorf(\"Unexpected response: %d %s\", resp.StatusCode, resp.Status)\n\t}\n\treturn nil\n}", "func (n *Notifier) SetSource(source Source) {\n\tn.lock.Lock()\n\tn.source = source\n\tn.lock.Unlock()\n\tif err := n.Reload(); err != nil {\n\t\tlog.Warningf(\"Reload failed after setting source: %v\", err)\n\t}\n}", "func (m *ThreatAssessmentRequest) SetRequestSource(value *ThreatAssessmentRequestSource)() {\n err := m.GetBackingStore().Set(\"requestSource\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *FileSet) Source(p token.Pos) (line string, pos token.Position) {\n\tif f := s.File(p); f != nil {\n\t\tline, pos = f.Source(p)\n\t}\n\treturn\n}", "func (store *FileTileStore) Put(scale, index int, tile *tiling.Tile) error {\n\tsklog.Info(\"Put()\")\n\t// Make sure the scale and tile index are correct.\n\tif tile.Scale != scale || tile.TileIndex != index {\n\t\treturn fmt.Errorf(\"Tile scale %d and index %d do not match real tile scale %d and index %d\", scale, index, tile.Scale, tile.TileIndex)\n\t}\n\n\tif index < 0 {\n\t\treturn fmt.Errorf(\"Can't write Tiles with an index < 0: %d\", index)\n\t}\n\n\t// Begin by writing the Tile out into a temporary location.\n\tf, err := store.fileTileTemp(scale, index)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenc := gob.NewEncoder(f)\n\tif err := enc.Encode(tile); err != nil {\n\t\treturn fmt.Errorf(\"Failed to encode tile %s: %s\", f.Name(), err)\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to close temporary file: %v\", err)\n\t}\n\n\t// Now rename the completed file to the real tile name. This is atomic and\n\t// doesn't affect current readers of the old tile contents.\n\ttargetName, err := store.tileFilename(scale, index)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(filepath.Dir(targetName), 0755); err != nil {\n\t\treturn fmt.Errorf(\"Error creating directory for tile %s: %s\", targetName, err)\n\t}\n\tsklog.Infof(\"Renaming: %q %q\", f.Name(), targetName)\n\tif err := os.Rename(f.Name(), targetName); err != nil {\n\t\treturn fmt.Errorf(\"Failed to rename tile: %s\", err)\n\t}\n\tfiledata, err := os.Stat(targetName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to stat new tile: %s\", err)\n\n\t}\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\n\tentry := &CacheEntry{\n\t\ttile: tile,\n\t\tlastModified: filedata.ModTime(),\n\t}\n\tkey := CacheKey{\n\t\tstartIndex: index,\n\t\tscale: scale,\n\t}\n\tstore.cache.Add(key, entry)\n\n\treturn nil\n}", "func (repo *Repository) RegisterSource(name Name, source RegisterableSource) {\n\trepo.repoL.Lock()\n\trepo.repo[name] = source\n\trepo.repoL.Unlock()\n}", "func (o *CurrentChartDataMinutely) SetSourceCurrency(exec boil.Executor, insert bool, related *Currency) 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 \\\"current_chart_data_minutely\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"source_currency_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, currentChartDataMinutelyPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, 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.SourceCurrencyID = related.ID\n\tif o.R == nil {\n\t\to.R = &currentChartDataMinutelyR{\n\t\t\tSourceCurrency: related,\n\t\t}\n\t} else {\n\t\to.R.SourceCurrency = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &currencyR{\n\t\t\tSourceCurrencyCurrentChartDataMinutelies: CurrentChartDataMinutelySlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.SourceCurrencyCurrentChartDataMinutelies = append(related.R.SourceCurrencyCurrentChartDataMinutelies, o)\n\t}\n\n\treturn nil\n}", "func NewSource(\n\tfset *token.FileSet, path string,\n\tfilter func(fs.FileInfo) bool, mode parser.Mode) (doc NodeSet, err error) {\n\n\tpkgs, err := parser.ParseDir(fset, path, filter, mode)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn NodeSet{Data: &oneNode{astPackages(pkgs)}}, nil\n}", "func (w *World) SetTile(t *Tile, x, y int) {\n\n\tif w.Map[x] == nil {\n\t\tw.Map[x] = map[int]*Tile{}\n\t}\n\tt.X = x\n\tt.Y = y\n\tt.W = w\n\tw.Map[x][y] = t\n}", "func (m *DeviceConfigurationAssignment) SetSource(value *DeviceAndAppManagementAssignmentSource)() {\n err := m.GetBackingStore().Set(\"source\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *tiles) SetTiles(val []TileInfo) {\n\tm.tilesField = val\n}", "func NewSource(path string) (*Source, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Source{\n\t\tf: f,\n\t\tstream: stream.NewSource(f),\n\t}, nil\n}", "func (m *Machine) SetFactSource(facts func() json.RawMessage) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.facts = facts\n}", "func NewSource(path string) config.Source {\n\treturn &file{path: path}\n}", "func (g *Graph) InsertSource(source, tag string) (db.Node, error) {\n\tnode, err := g.InsertNodeIfNotExist(source, \"source\")\n\tif err != nil {\n\t\treturn node, err\n\t}\n\n\tvar insert bool\n\tif p, err := g.db.ReadProperties(node, \"tag\"); err == nil && len(p) > 0 {\n\t\tif p[0].Value != tag {\n\t\t\t// Remove an existing 'tag' property\n\t\t\tg.db.DeleteProperty(node, p[0].Predicate, p[0].Value)\n\t\t\t// Update the 'tag' property\n\t\t\tinsert = true\n\t\t}\n\t} else {\n\t\t// The tag was not found\n\t\tinsert = true\n\t}\n\n\tif insert {\n\t\tif err := g.db.InsertProperty(node, \"tag\", tag); err != nil {\n\t\t\treturn node, err\n\t\t}\n\t}\n\n\treturn node, nil\n}", "func NewFileSource(path string) (*MapSource, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// changed how we handled a deferred file closure due to go lint security check https://github.com/securego/gosec/issues/512#issuecomment-675286833\n\tdefer func() {\n\t\tif cerr := f.Close(); cerr != nil {\n\t\t\tfmt.Printf(\"Error closing file: %s\\n\", cerr)\n\t\t}\n\t}()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm, err := NewJSONSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\tm, err = NewYAMLSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\treturn nil, fmt.Errorf(\"could not determine file format for %s\", path)\n}", "func (s *HostVolumeProperties) SetSourcePath(v string) *HostVolumeProperties {\n\ts.SourcePath = &v\n\treturn s\n}", "func (t *Tileset) SetTileset(username string, tilesetID string) {\n\tt.username = username\n\tt.tilesetID = tilesetID\n}", "func (a *chunkBasedAtlas) setTile(chunk int, local maths.Vector, tile byte) {\n\ta.populate(chunk)\n\tc := a.Chunks[chunk]\n\tc.Tiles[a.chunkTileIndex(local)] = tile\n\ta.Chunks[chunk] = c\n}", "func SetFromPath(node interface{}, path string, out interface{}) (bool, error) {\n\tval, found, err := GetFromStructPath(node, path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !found {\n\t\treturn false, nil\n\t}\n\n\treturn true, Set(val, out)\n}", "func (i *zipWriter) RegisterSource(dumpFileName string, p Source) error {\n\tif _, ok := i.sources[dumpFileName]; ok {\n\t\treturn fmt.Errorf(\"dumpfile already registered %s\", dumpFileName)\n\t}\n\ti.sources[dumpFileName] = p\n\treturn nil\n}", "func (c *Wire) SetSource(u Updater) {\n\tc.src = u\n}", "func SetPath(path string) {\n\tc.setPath(path)\n}", "func (a *chunkBasedAtlas) SetTile(v maths.Vector, tile roveapi.Tile) {\n\tc := a.worldSpaceToChunkWithGrow(v)\n\tlocal := a.worldSpaceToChunkLocal(v)\n\ta.setTile(c, local, byte(tile))\n}", "func (storage *PublishedStorage) putFile(path string, source io.ReadSeeker, sourceMD5 string) error {\n\n\tparams := &s3.PutObjectInput{\n\t\tBucket: aws.String(storage.bucket),\n\t\tKey: aws.String(filepath.Join(storage.prefix, path)),\n\t\tBody: source,\n\t\tACL: aws.String(storage.acl),\n\t}\n\tif storage.storageClass != \"\" {\n\t\tparams.StorageClass = aws.String(storage.storageClass)\n\t}\n\tif storage.encryptionMethod != \"\" {\n\t\tparams.ServerSideEncryption = aws.String(storage.encryptionMethod)\n\t}\n\tif sourceMD5 != \"\" {\n\t\tparams.Metadata = map[string]*string{\n\t\t\t\"Md5\": aws.String(sourceMD5),\n\t\t}\n\t}\n\n\t_, err := storage.s3.PutObject(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif storage.plusWorkaround && strings.Contains(path, \"+\") {\n\t\t_, err = source.Seek(0, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn storage.putFile(strings.Replace(path, \"+\", \" \", -1), source, sourceMD5)\n\t}\n\treturn nil\n}", "func (pm *PathMap) set(path string, value interface{}) {\n\tparts := strings.Split(path, svnSep)\n\tdir, name := parts[:len(parts)-1], parts[len(parts)-1]\n\tpm._createTree(dir).blobs[name] = value\n}", "func (options *CreateActionOptions) SetSource(source *ExternalSource) *CreateActionOptions {\n\toptions.Source = source\n\treturn options\n}", "func (s *StartReferenceImportJobSourceItem) SetSourceFile(v string) *StartReferenceImportJobSourceItem {\n\ts.SourceFile = &v\n\treturn s\n}", "func (j Json) Set(path string, value interface{}) (string, error) {\n\treturn sjson.Set(string(j), path, value)\n}", "func (s *atomixStore) registerSrcTgt(obj *topoapi.Object, strict bool) {\n\tif relation := obj.GetRelation(); relation != nil {\n\t\tif strict {\n\t\t\t// check that the connection is valid (src and tgt are in the store). otherwise remove the dangling relation\n\t\t\tif _, err := s.objects.Get(context.Background(), relation.SrcEntityID); err != nil {\n\t\t\t\terr = errors.FromAtomix(err)\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\t_, _ = s.objects.Remove(context.Background(), obj.ID)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := s.objects.Get(context.Background(), relation.TgtEntityID); err != nil {\n\t\t\t\terr = errors.FromAtomix(err)\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\t_, _ = s.objects.Remove(context.Background(), obj.ID)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\ts.relations.lock.Lock()\n\t\tdefer s.relations.lock.Unlock()\n\t\ts.relations.sources[relation.SrcEntityID] = add(s.relations.sources[relation.SrcEntityID], obj.ID)\n\t\ts.relations.targets[relation.TgtEntityID] = add(s.relations.targets[relation.TgtEntityID], obj.ID)\n\t}\n}", "func (m *AssignedEntitiesWithMetricTile) SetTileType(val string) {\n\n}", "func SetPath(newpath string) {\n\tpath = newpath\n}", "func (m *DeviceManagementConfigurationPolicy) SetCreationSource(value *string)() {\n err := m.GetBackingStore().Set(\"creationSource\", value)\n if err != nil {\n panic(err)\n }\n}", "func (l *Log) SetSource(src string) {\n\tif l == nil {\n\t\treturn\n\t}\n\n\tl.Source = src\n}", "func NewSourceFrom(\n\tfset *token.FileSet, fs parser.FileSystem, path string,\n\tfilter func(fs.FileInfo) bool, mode parser.Mode) (doc NodeSet, err error) {\n\n\tpkgs, err := parser.ParseFSDir(fset, fs, path, parser.Config{Filter: filter, Mode: mode})\n\tif err != nil {\n\t\treturn\n\t}\n\treturn NodeSet{Data: &oneNode{astPackages(pkgs)}}, nil\n}", "func (m *Resource) SetPath(name string) error {\n\tif len(m.name) > 0 {\n\t\treturn errors.New(\"name already set\")\n\t}\n\tname = strings.TrimSpace(strings.ToLower(s))\n\tmatched, err := regexp.MatchString(\"^[a-z]{4,15}$\", name)\n\tif err == nil && matched {\n\t\tm.name = name\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(\"name does not match requirements and has not been set: must be ^[a-z]{4-15}$\")\n\t}\n}", "func NewTileSets(header Header, ts Tilesets, path string) *TileSets {\n\treturn &TileSets{header, ts, path}\n}", "func (s *ReadSetFiles) SetSource1(v *FileInformation) *ReadSetFiles {\n\ts.Source1 = v\n\treturn s\n}", "func (this *osmSourceStruct) getTile(id osmTileIdStruct) *osmTileStruct {\n\tzoom := id.zoom\n\tx := id.x\n\ty := id.y\n\tmaxId := uint32((1 << zoom) - 1)\n\ttemplateFile := this.cachePath\n\n\t/*\n\t * Check if tile ID and file path template are valid.\n\t */\n\tif templateFile == \"\" || x > maxId || y > maxId {\n\t\trect := image.Rect(0, 0, TILE_SIZE, TILE_SIZE)\n\t\timg := image.NewNRGBA(rect)\n\n\t\t/*\n\t\t * Create OSM tile.\n\t\t */\n\t\tt := osmTileStruct{\n\t\t\timageData: img,\n\t\t\ttileId: id,\n\t\t}\n\n\t\treturn &t\n\t} else {\n\t\treadFromFile := false\n\t\tpathFile := this.tilePath(templateFile, zoom, x, y)\n\t\tthis.mutex.RLock()\n\t\tfd, err := os.Open(pathFile)\n\t\trect := image.ZR\n\t\timg := image.NewNRGBA(rect)\n\n\t\t/*\n\t\t * Check if file exists.\n\t\t */\n\t\tif err == nil {\n\t\t\timgPng, err := png.Decode(fd)\n\n\t\t\t/*\n\t\t\t * Check if image was decoded from file.\n\t\t\t */\n\t\t\tif err == nil {\n\t\t\t\trect = imgPng.Bounds()\n\t\t\t\timg = image.NewNRGBA(rect)\n\t\t\t\trectMin := rect.Min\n\t\t\t\tminX := rectMin.X\n\t\t\t\tminY := rectMin.Y\n\t\t\t\trectMax := rect.Max\n\t\t\t\tmaxX := rectMax.X\n\t\t\t\tmaxY := rectMax.Y\n\n\t\t\t\t/*\n\t\t\t\t * Read image line by line.\n\t\t\t\t */\n\t\t\t\tfor y := minY; y < maxY; y++ {\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Read line pixel by pixel.\n\t\t\t\t\t */\n\t\t\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\t\t\tc := imgPng.At(x, y)\n\t\t\t\t\t\timg.Set(x, y, c)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treadFromFile = true\n\t\t\t}\n\n\t\t\tfd.Close()\n\t\t}\n\n\t\tthis.mutex.RUnlock()\n\n\t\t/*\n\t\t * If tile was not found in cache, download it from tile server and\n\t\t * store it in cache.\n\t\t */\n\t\tif !readFromFile {\n\t\t\ttemplateUri := this.uri\n\n\t\t\t/*\n\t\t\t * Only download from OSM server if URI is not empty.\n\t\t\t */\n\t\t\tif templateUri != \"\" {\n\t\t\t\tpathUri := this.tilePath(templateUri, zoom, x, y)\n\t\t\t\tfmt.Printf(\"Fetching from URI: %s\\n\", pathUri)\n\t\t\t\tclient := &http.Client{}\n\t\t\t\treq, err := http.NewRequest(\"GET\", pathUri, nil)\n\n\t\t\t\t/*\n\t\t\t\t * Check if we have a valid request.\n\t\t\t\t */\n\t\t\t\tif err == nil {\n\t\t\t\t\tthis.mutex.Lock()\n\t\t\t\t\treq.Header.Set(\"User-Agent\", \"location-visualizer\")\n\t\t\t\t\tresp, err := client.Do(req)\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Check if we got a response and store it in cache.\n\t\t\t\t\t */\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbody := resp.Body\n\t\t\t\t\t\tfd, err := os.Create(pathFile)\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Check if file was created.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tr := io.TeeReader(body, fd)\n\t\t\t\t\t\t\timgPng, err := png.Decode(r)\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * Check if image was decoded from response.\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\trect = imgPng.Bounds()\n\t\t\t\t\t\t\t\timg = image.NewNRGBA(rect)\n\t\t\t\t\t\t\t\trectMin := rect.Min\n\t\t\t\t\t\t\t\tminX := rectMin.X\n\t\t\t\t\t\t\t\tminY := rectMin.Y\n\t\t\t\t\t\t\t\trectMax := rect.Max\n\t\t\t\t\t\t\t\tmaxX := rectMax.X\n\t\t\t\t\t\t\t\tmaxY := rectMax.Y\n\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * Read image line by line.\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\tfor y := minY; y < maxY; y++ {\n\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * Read line pixel by pixel.\n\t\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\t\t\t\t\t\t\tc := imgPng.At(x, y)\n\t\t\t\t\t\t\t\t\t\timg.Set(x, y, c)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfd.Close()\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbody.Close()\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.mutex.Unlock()\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t/*\n\t\t * Create OSM tile.\n\t\t */\n\t\tt := osmTileStruct{\n\t\t\timageData: img,\n\t\t\ttileId: id,\n\t\t}\n\n\t\treturn &t\n\t}\n\n}", "func (o *WorkflowBuildTaskMeta) SetSrc(v string) {\n\to.Src = &v\n}", "func (m *DeviceManagementResourceAccessProfileAssignment) SetSourceId(value *string)() {\n err := m.GetBackingStore().Set(\"sourceId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (d *DataPacket) SetSourceName(s string) {\n\tb := [64]byte{}\n\tcopy(b[:], []byte(s))\n\td.replace(44, b[:64])\n}", "func (f *File) SetSourceForContent(content []byte) {\n\tstr := string(content)\n\tstart, n := 0, len(str)\n\tvar source []string\n\tfor i := 0; i < n; i++ {\n\t\tif str[i] == '\\n' {\n\t\t\tsource = append(source, str[start:i])\n\t\t\t// skip '\\n'\n\t\t\tstart = i + 1\n\t\t}\n\t}\n\tif start < n {\n\t\tsource = append(source, str[start:])\n\t}\n\tf.SetSource(source)\n}", "func NewSourceFile(path string, optfs ...vfs.FileSystem) Source {\n\tvar fs vfs.FileSystem\n\tif len(optfs) > 0 {\n\t\tfs = optfs[0]\n\t}\n\tif fs == nil {\n\t\tfs = osfs.New()\n\t}\n\treturn &sourceFile{sourceBase{path}, fs}\n}", "func (r *Input) SetPath(path string) error {\n\tquery, err := fetch.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Lock()\n\tr.Path = query\n\tr.Unlock()\n\treturn nil\n}", "func (f *IndexFile) SetPath(path string) { f.path = path }", "func (client FeatureStateClient) PutStateset(ctx context.Context, statesetID string, statesetStyleUpdateRequestBody StylesObject) (result autorest.Response, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/FeatureStateClient.PutStateset\")\n defer func() {\n sc := -1\n if result.Response != nil {\n sc = result.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.PutStatesetPreparer(ctx, statesetID, statesetStyleUpdateRequestBody)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"PutStateset\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.PutStatesetSender(req)\n if err != nil {\n result.Response = resp\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"PutStateset\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.PutStatesetResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"PutStateset\", resp, \"Failure responding to request\")\n return\n }\n\n return\n}", "func (t *Tileset) CreateTileset(pathToFile string) (*base.MapboxAPIMessage, error) {\n\tmaboxAPIMessage := &base.MapboxAPIMessage{}\n\trecipeJSON, err := os.Open(pathToFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer recipeJSON.Close()\n\n\tdata, _ := ioutil.ReadAll(recipeJSON)\n\tres, err := t.base.PostRequest(t.postURL(), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjson.Unmarshal(res, &maboxAPIMessage)\n\n\treturn maboxAPIMessage, nil\n\n}", "func (options *UpdateActionOptions) SetSource(source *ExternalSource) *UpdateActionOptions {\n\toptions.Source = source\n\treturn options\n}", "func (s *SinceDB) SetRessource(ressource string, v []byte) error {\n\ts.offsets.Store(ressource, v)\n\treturn nil\n}", "func (obj *Device) SetStreamSource(\n\tstreamNumber uint,\n\tstreamData *VertexBuffer,\n\toffsetInBytes uint,\n\tstride uint,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.SetStreamSource,\n\t\t5,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(streamNumber),\n\t\tuintptr(unsafe.Pointer(streamData)),\n\t\tuintptr(offsetInBytes),\n\t\tuintptr(stride),\n\t\t0,\n\t)\n\treturn toErr(ret)\n}", "func (s *DescribeTrialComponentOutput) SetSource(v *TrialComponentSource) *DescribeTrialComponentOutput {\n\ts.Source = v\n\treturn s\n}", "func SourceSetClosure(source *glib.Source, closure *Closure) {\n\tc_source := (*C.GSource)(C.NULL)\n\tif source != nil {\n\t\tc_source = (*C.GSource)(source.ToC())\n\t}\n\n\tc_closure := (*C.GClosure)(C.NULL)\n\tif closure != nil {\n\t\tc_closure = (*C.GClosure)(closure.ToC())\n\t}\n\n\tC.g_source_set_closure(c_source, c_closure)\n\n\treturn\n}", "func NewBoltSource(path string) (Source, error) {\n\n\tdb, err := bolt.Open(path, 0600, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(bucketName))\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &boltSource{\n\t\tdb: db,\n\t\tbucket: []byte(bucketName),\n\t}, nil\n\n}", "func filesetForSource(gc GenerationContext, source vts.Target) (fileset, error) {\n\tswitch src := source.(type) {\n\tcase *vts.Puesdo:\n\t\tswitch src.Kind {\n\t\tcase vts.FileRef:\n\t\t\treturn filesetForFileSource(src)\n\t\tcase vts.DebRef:\n\t\t\treturn filesetForDebSource(gc, src)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"cannot generate using puesdo source %v\", src.Kind)\n\n\tcase *vts.Generator:\n\t\treturn nil, errors.New(\"not implemented\")\n\n\tcase *vts.Build:\n\t\th, err := src.RollupHash(gc.RunnerEnv, proc.EvalComputedAttribute)\n\t\tif err != nil {\n\t\t\treturn nil, vts.WrapWithTarget(err, src)\n\t\t}\n\t\treturn gc.Cache.FilesetReader(h)\n\n\tcase *vts.Sieve:\n\t\treturn filesetForSieve(gc, src)\n\t}\n\treturn nil, fmt.Errorf(\"cannot obtain fileset for source %T\", source)\n}", "func (me *TxsdFeTurbulenceTypeStitchTiles) Set(s string) { (*xsdt.String)(me).Set(s) }", "func (s *Shader) SetVertexSource(src string) (err error) {\n\t// Do some cleanup if we're replacing an existing shader\n\ts.destroyVertexShader()\n\n\t// Set new shader\n\ts.vertID, err = setShader(src, gl.VERTEX_SHADER)\n\n\t// If successful and applicable, attach and compile\n\tif err == nil && s.programID != 0 {\n\t\tgl.AttachShader(s.programID, s.vertID)\n\t\terr = s.compileProgram()\n\t}\n\n\treturn\n}", "func SourceFromPath(path string) (*Source, error) {\n in, err := os.Open(path)\n if err != nil {\n return nil, err\n }\n text, err := ioutil.ReadAll(in)\n if err != nil {\n return nil, err\n }\n return &Source{ Path : path, Text : text }, nil\n}", "func (m *AssignedEntitiesWithMetricTile) SetTileFilter(val *TileFilter) {\n\tm.tileFilterField = val\n}", "func (j *JSONData) SetPath(v interface{}, path ...string) error {\n\tjson, err := sj.NewJson(j.data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjson.SetPath(path, v)\n\tbt, err := json.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\tj.data = bt\n\treturn nil\n}", "func (m *ThreatAssessmentRequest) SetRequestSource(value *ThreatAssessmentRequestSource)() {\n m.requestSource = value\n}", "func (*SpxTemplate) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/template/%s\", ref)\n}", "func (s *CreateEnvironmentTemplateVersionInput) SetSource(v *TemplateVersionSourceInput) *CreateEnvironmentTemplateVersionInput {\n\ts.Source = v\n\treturn s\n}", "func (mySource *Source) SetSource(val string) {\n\tmySource.Sourcevar = val\n}", "func (s *MultiMeasureAttributeMapping) SetSourceColumn(v string) *MultiMeasureAttributeMapping {\n\ts.SourceColumn = &v\n\treturn s\n}", "func (z *ZkPlus) Set(path string, data []byte, version int32) (*zk.Stat, error) {\n\tz.forPath(path).Log(logkey.ZkMethod, \"Set\")\n\treturn z.blockOnConn().Set(z.realPath(path), data, version)\n}", "func (o *SoftwarerepositoryCategoryMapper) SetSource(v string) {\n\to.Source = &v\n}", "func (s *ImportReferenceSourceItem) SetSourceFile(v string) *ImportReferenceSourceItem {\n\ts.SourceFile = &v\n\treturn s\n}", "func (*HttpLocalSite) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/local_site/%s\", ref)\n}", "func (s *Store) SavePluginSource(entityKey, category, term string, source map[string]interface{}) (err error) {\n\t// construct the plugin data directory and ensure it exists\n\toutputDir := s.PluginDirPath(category, entityKey)\n\tif err = disk.MkdirAll(outputDir, DATA_DIR_MODE); err != nil {\n\t\treturn err\n\t}\n\n\t// construct the output file path\n\toutputFile := fmt.Sprintf(\"%s/%s.json\", outputDir, term)\n\n\tsourceB, err := json.Marshal(source)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif bytes.Contains(sourceB, NULL) {\n\t\tsourceB, err = removeNilsFromMarshaledJSON(sourceB)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif len(sourceB) > s.maxInventorySize {\n\t\terr = fmt.Errorf(\n\t\t\t\"Plugin data for entity %v plugin %v/%v is larger than max size of %v\",\n\t\t\tentityKey,\n\t\t\tcategory,\n\t\t\tterm,\n\t\t\ts.maxInventorySize,\n\t\t)\n\t\treturn\n\t}\n\terr = disk.WriteFile(outputFile, sourceB, DATA_FILE_MODE)\n\treturn\n}", "func (o *CustomHostMetadataKey) SetSource(v string) {\n\to.Source = v\n}" ]
[ "0.6059684", "0.5351458", "0.5199152", "0.5056169", "0.5014092", "0.5001283", "0.5000093", "0.49824324", "0.49708128", "0.4796271", "0.47573808", "0.47215167", "0.46444505", "0.46420372", "0.46308562", "0.46213987", "0.4595381", "0.45926014", "0.45886418", "0.45883557", "0.4582964", "0.45398968", "0.4530842", "0.45082334", "0.4497778", "0.44900316", "0.4470458", "0.4443644", "0.44355735", "0.44256634", "0.4406308", "0.43826815", "0.43782118", "0.43511173", "0.43482247", "0.43481678", "0.43453854", "0.43139848", "0.43112913", "0.42903966", "0.4287413", "0.42778274", "0.42725796", "0.42722583", "0.42704016", "0.4266696", "0.42585468", "0.42479888", "0.4247153", "0.42424002", "0.4231601", "0.42314246", "0.42133912", "0.41980344", "0.41555363", "0.41526693", "0.4151139", "0.41432327", "0.41208383", "0.41176638", "0.41147855", "0.41125107", "0.4106395", "0.41028008", "0.40962845", "0.40930793", "0.40857992", "0.40801427", "0.40784925", "0.40725878", "0.4071908", "0.40685618", "0.40614685", "0.4061005", "0.4058971", "0.40536082", "0.40521276", "0.40502024", "0.40494385", "0.4048584", "0.40420142", "0.40412498", "0.40359208", "0.40299228", "0.40286383", "0.40275684", "0.40260813", "0.40241274", "0.40191746", "0.4015585", "0.40008268", "0.39983475", "0.39958444", "0.39949673", "0.39919817", "0.39878428", "0.3983931", "0.39828935", "0.39753988", "0.39677614" ]
0.7761068
0
ParseHclInterface is used to convert an interface value representing a hcl2 body and return the interpolated value. Vars may be nil if there are no variables to interpolate.
func ParseHclInterface(val interface{}, spec hcldec.Spec, vars map[string]cty.Value) (cty.Value, hcl.Diagnostics, []error) { evalCtx := &hcl.EvalContext{ Variables: vars, Functions: GetStdlibFuncs(), } // Encode to json var buf bytes.Buffer enc := codec.NewEncoder(&buf, structs.JsonHandle) err := enc.Encode(val) if err != nil { // Convert to a hcl diagnostics message errorMessage := fmt.Sprintf("Label encoding failed: %v", err) return cty.NilVal, hcl.Diagnostics([]*hcl.Diagnostic{{ Severity: hcl.DiagError, Summary: "Failed to encode label value", Detail: errorMessage, }}), []error{errors.New(errorMessage)} } // Parse the json as hcl2 hclFile, diag := hjson.Parse(buf.Bytes(), "") if diag.HasErrors() { return cty.NilVal, diag, formattedDiagnosticErrors(diag) } value, decDiag := hcldec.Decode(hclFile.Body, spec, evalCtx) diag = diag.Extend(decDiag) if diag.HasErrors() { return cty.NilVal, diag, formattedDiagnosticErrors(diag) } return value, diag, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cv *ConVar) Interface() (interface{}, error) {\n\treturn cv.value.Load(), nil\n}", "func (c *opticsCollector) ParseInterfaces(output string) ([]string, error) {\n\titems := []string{}\n\tifNameRegexp := regexp.MustCompile(`name=(.*) default-name`)\n\n\tmatches := ifNameRegexp.FindAllStringSubmatch(output, -1)\n\tfor _, match := range matches {\n\t\titems = append(items, match[1])\n\t}\n\treturn items, nil\n}", "func (r *Response) Interface() interface{} {\n\t// Attempt int64\n\ti, err := strconv.ParseInt(r.String(), 10, 64)\n\tif err == nil {\n\t\treturn i\n\t}\n\n\t// Attempt float64\n\tf, err := strconv.ParseFloat(r.String(), 64)\n\tif err == nil {\n\t\treturn f\n\t}\n\n\t// Attempt bool\n\tb, err := strconv.ParseBool(r.String())\n\tif err == nil {\n\t\treturn b\n\t}\n\n\treturn r.String()\n}", "func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterfaceInterfaceRef(ctx context.Context, interfaceId string, frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam FrinxOpenconfigInterfacesInterfacerefInterfaceRefRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/frinx-logging:interface-ref/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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\", \"application/xml\"}\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 = &frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\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\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (p *Parser) Interface() interface{} {\n\treturn p.data\n}", "func (m *Message) unmarshalInterface(v interface{}) error {\n\tstrdata, err := stringMap(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range strdata {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"id\":\n\t\t\tm.ID = v\n\t\tcase \"description\":\n\t\t\tm.Description = v\n\t\tcase \"hash\":\n\t\t\tm.Hash = v\n\t\tcase \"leftdelim\":\n\t\t\tm.LeftDelim = v\n\t\tcase \"rightdelim\":\n\t\t\tm.RightDelim = v\n\t\tcase \"zero\":\n\t\t\tm.Zero = v\n\t\tcase \"one\":\n\t\t\tm.One = v\n\t\tcase \"two\":\n\t\t\tm.Two = v\n\t\tcase \"few\":\n\t\t\tm.Few = v\n\t\tcase \"many\":\n\t\t\tm.Many = v\n\t\tcase \"other\":\n\t\t\tm.Other = v\n\t\t}\n\t}\n\treturn nil\n}", "func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterface(ctx context.Context, interfaceId string, frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam FrinxLoggingLogginginterfacesstructuralInterfacesInterfaceRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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\", \"application/xml\"}\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 = &frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\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\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (d *MockDataResyncDSL) Interface(val *interfaces.Interfaces_Interface) vppclient.DataResyncDSL {\n\top := dsl.TxnOp{Key: interfaces.InterfaceKey(val.Name), Value: val}\n\td.Ops = append(d.Ops, op)\n\treturn d\n}", "func (cl *AgentClient) InterfaceUpdate(putData netproto.Interface) error {\n\tvar resp Response\n\n\terr := netutils.HTTPPut(\"http://\"+cl.agentURL+\"/api/interfaces/default/default/preCreatedInterface\", &putData, &resp)\n\n\treturn err\n}", "func (_Contract *ContractFilterer) ParseInterfaceChanged(log types.Log) (*ContractInterfaceChanged, error) {\n\tevent := new(ContractInterfaceChanged)\n\tif err := _Contract.contract.UnpackLog(event, \"InterfaceChanged\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (s *InterfaceStep) Interface() interface{} {\n\treturn s.value\n}", "func ImportsInterface(pkg string, m *ir.Module) ([]byte, error) {\n\tasset, err := lookupTemplate(\"imports\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpl, err := template.New(\"imports\").Parse(string(asset))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := struct {\n\t\tPkg string\n\t\tImportedFuncs []importedFunc\n\t}{\n\t\tPkg: pkg,\n\t}\n\tfor _, f := range m.ImportedFunctions {\n\t\tdata.ImportedFuncs = append(data.ImportedFuncs, impFunc(f, true))\n\t}\n\tvar b bytes.Buffer\n\tif err := tmpl.Execute(&b, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func LoadValueIfFromInterface(val interface{}) (valIf ValueIf, err error) {\n\tswitch reflect.TypeOf(val).Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8,\n\t\treflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tvalIf, err = NewValueInt64(val)\n\tcase reflect.Bool:\n\t\tvalIf, err = NewValueBool(val)\n\tcase reflect.String:\n\t\tvalIf, err = NewValueString(val)\n\tcase reflect.Float32, reflect.Float64:\n\t\tvalIf, err = NewValueFloat64(val)\n\tdefault:\n\t\terr = powerr.New(powerr.ErrNotSupportValueType).StoreKV(\"Type\", reflect.TypeOf(val).Kind()).StoreStack()\n\t}\n\n\treturn valIf, err\n}", "func (data *Data) Interface(s ...string) interface{} {\n\tx := *data\n\tvar y interface{}\n\n\tfor _, i := range s {\n\n\t\tif _, ok := x[i]; ok == false {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch x[i].(type) {\n\t\tdefault:\n\t\t\ty = x[i].(interface{})\n\n\t\tcase map[string]interface{}:\n\t\t\tx = x[i].(map[string]interface{})\n\t\t}\n\t}\n\treturn y\n}", "func (d *Decoder) DecodeInterfaceLoose() (interface{}, error) {\n\tc, err := d.readCode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msgpcode.IsFixedNum(c) {\n\t\treturn int64(int8(c)), nil\n\t}\n\tif msgpcode.IsFixedMap(c) {\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\t}\n\tif msgpcode.IsFixedArray(c) {\n\t\treturn d.decodeSlice(c)\n\t}\n\tif msgpcode.IsFixedString(c) {\n\t\treturn d.string(c)\n\t}\n\n\tswitch c {\n\tcase msgpcode.Nil:\n\t\treturn nil, nil\n\tcase msgpcode.False, msgpcode.True:\n\t\treturn d.bool(c)\n\tcase msgpcode.Float, msgpcode.Double:\n\t\treturn d.float64(c)\n\tcase msgpcode.Uint8, msgpcode.Uint16, msgpcode.Uint32, msgpcode.Uint64:\n\t\treturn d.uint(c)\n\tcase msgpcode.Int8, msgpcode.Int16, msgpcode.Int32, msgpcode.Int64:\n\t\treturn d.int(c)\n\tcase msgpcode.Bin8, msgpcode.Bin16, msgpcode.Bin32:\n\t\treturn d.bytes(c, nil)\n\tcase msgpcode.Str8, msgpcode.Str16, msgpcode.Str32:\n\t\treturn d.string(c)\n\tcase msgpcode.Array16, msgpcode.Array32:\n\t\treturn d.decodeSlice(c)\n\tcase msgpcode.Map16, msgpcode.Map32:\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\tcase msgpcode.FixExt1, msgpcode.FixExt2, msgpcode.FixExt4, msgpcode.FixExt8, msgpcode.FixExt16,\n\t\tmsgpcode.Ext8, msgpcode.Ext16, msgpcode.Ext32:\n\t\treturn d.decodeInterfaceExt(c)\n\t}\n\n\treturn 0, fmt.Errorf(\"msgpack: unknown code %x decoding interface{}\", c)\n}", "func (o FioSpecVolumeVolumeSourceIscsiOutput) IscsiInterface() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceIscsi) *string { return v.IscsiInterface }).(pulumi.StringPtrOutput)\n}", "func (s StaticInfoExtn_InternalHopsInfo) NewInterfaceHops(n int32) (StaticInfoExtn_InternalHopsInfo_InterfaceHops_List, error) {\n\tl, err := NewStaticInfoExtn_InternalHopsInfo_InterfaceHops_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn StaticInfoExtn_InternalHopsInfo_InterfaceHops_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func (d *Decoder) DecodeInterface() (interface{}, error) {\n\tc, err := d.readCode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msgpcode.IsFixedNum(c) {\n\t\treturn int8(c), nil\n\t}\n\tif msgpcode.IsFixedMap(c) {\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\t}\n\tif msgpcode.IsFixedArray(c) {\n\t\treturn d.decodeSlice(c)\n\t}\n\tif msgpcode.IsFixedString(c) {\n\t\treturn d.string(c)\n\t}\n\n\tswitch c {\n\tcase msgpcode.Nil:\n\t\treturn nil, nil\n\tcase msgpcode.False, msgpcode.True:\n\t\treturn d.bool(c)\n\tcase msgpcode.Float:\n\t\treturn d.float32(c)\n\tcase msgpcode.Double:\n\t\treturn d.float64(c)\n\tcase msgpcode.Uint8:\n\t\treturn d.uint8()\n\tcase msgpcode.Uint16:\n\t\treturn d.uint16()\n\tcase msgpcode.Uint32:\n\t\treturn d.uint32()\n\tcase msgpcode.Uint64:\n\t\treturn d.uint64()\n\tcase msgpcode.Int8:\n\t\treturn d.int8()\n\tcase msgpcode.Int16:\n\t\treturn d.int16()\n\tcase msgpcode.Int32:\n\t\treturn d.int32()\n\tcase msgpcode.Int64:\n\t\treturn d.int64()\n\tcase msgpcode.Bin8, msgpcode.Bin16, msgpcode.Bin32:\n\t\treturn d.bytes(c, nil)\n\tcase msgpcode.Str8, msgpcode.Str16, msgpcode.Str32:\n\t\treturn d.string(c)\n\tcase msgpcode.Array16, msgpcode.Array32:\n\t\treturn d.decodeSlice(c)\n\tcase msgpcode.Map16, msgpcode.Map32:\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\tcase msgpcode.FixExt1, msgpcode.FixExt2, msgpcode.FixExt4, msgpcode.FixExt8, msgpcode.FixExt16,\n\t\tmsgpcode.Ext8, msgpcode.Ext16, msgpcode.Ext32:\n\t\treturn d.decodeInterfaceExt(c)\n\t}\n\n\treturn 0, fmt.Errorf(\"msgpack: unknown code %x decoding interface{}\", c)\n}", "func (s *StringStep) Interface() interface{} {\n\treturn string(*s)\n}", "func UseInterface() {\n\ti1 := map[string]interface{}{\n\t\t\"id\": 1111,\n\t\t\"name\": \"Toran\",\n\t\t\"interests\": []interface{}{\n\t\t\t\"technology\",\n\t\t\t\"trekking\",\n\t\t\t\"biking\",\n\t\t},\n\t\t\"extra\": map[string]interface{}{\n\t\t\t\"edu\": \"graduation\",\n\t\t},\n\t}\n\tfmt.Println(i1)\n\n\ti2 := []interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"id\": 1111,\n\t\t\t\"name\": \"Toran\",\n\t\t},\n\t\tmap[string]interface{}{\n\t\t\t\"id\": 1112,\n\t\t\t\"name\": \"Abhishek\",\n\t\t},\n\t}\n\tfmt.Println(i2)\n}", "func (v *Value) Interface() interface{} {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tswitch v2 := v.Value().(type) {\n\tcase bool:\n\t\treturn v2\n\tcase float64:\n\t\treturn v2\n\tcase string:\n\t\treturn v2\n\tcase id.ID:\n\t\treturn v2.String()\n\tcase *url.URL:\n\t\treturn v2.String()\n\tcase LatLng:\n\t\treturn encodeValue(&v2)\n\tcase LatLngHeight:\n\t\treturn encodeValue(&v2)\n\t}\n\treturn nil\n}", "func (n *mockAgent) updateInterface(inf *pbTypes.Interface) (*pbTypes.Interface, error) {\n\treturn nil, nil\n}", "func (plugin *Plugin) initIF(ctx context.Context) error {\n\tplugin.Log.Infof(\"Init Linux interface plugin\")\n\n\t// Init shared interface index mapping\n\tplugin.ifIndexes = ifaceidx.NewLinuxIfIndex(nametoidx.NewNameToIdx(plugin.Log, \"linux_if_indexes\", nil))\n\n\t// Shared interface linux calls handler\n\tplugin.ifHandler = ifLinuxcalls.NewNetLinkHandler(plugin.nsHandler, plugin.ifIndexes, plugin.Log)\n\n\t// Linux interface configurator\n\tplugin.ifLinuxNotifChan = make(chan *ifplugin.LinuxInterfaceStateNotification, 10)\n\tplugin.ifConfigurator = &ifplugin.LinuxInterfaceConfigurator{}\n\tif err := plugin.ifConfigurator.Init(plugin.Log, plugin.ifHandler, plugin.nsHandler, nsplugin.NewSystemHandler(),\n\t\tplugin.ifIndexes, plugin.ifMicroserviceNotif, plugin.ifLinuxNotifChan); err != nil {\n\t\treturn plugin.ifConfigurator.LogError(err)\n\t}\n\tplugin.ifLinuxStateUpdater = &ifplugin.LinuxInterfaceStateUpdater{}\n\tif err := plugin.ifLinuxStateUpdater.Init(ctx, plugin.Log, plugin.ifIndexes, plugin.ifLinuxNotifChan); err != nil {\n\t\treturn plugin.ifConfigurator.LogError(err)\n\t}\n\n\treturn nil\n}", "func AppendInterface(dst []byte, i interface{}) []byte {\n\tmarshaled, err := json.Marshal(i)\n\tif err != nil {\n\t\treturn AppendString(dst, fmt.Sprintf(\"marshaling error: %v\", err))\n\t}\n\treturn AppendEmbeddedJSON(dst, marshaled)\n}", "func (t *Typed) InterfaceIf(key string) (interface{}, bool) {\n\tvalue, exists := t.GetIf(key)\n\tif exists == false {\n\t\treturn nil, false\n\t}\n\treturn value, true\n}", "func (plugin *RouteConfigurator) ResolveCreatedInterface(ifName string, swIdx uint32) {\n\troutesWithIndex := plugin.rtCachedIndexes.LookupRouteAndIDByOutgoingIfc(ifName)\n\tif len(routesWithIndex) == 0 {\n\t\treturn\n\t}\n\tplugin.log.Infof(\"Route configurator: resolving new interface %v for %d routes\", ifName, len(routesWithIndex))\n\tfor _, routeWithIndex := range routesWithIndex {\n\t\troute := routeWithIndex.Route\n\t\tplugin.log.WithFields(logging.Fields{\n\t\t\t\"ifName\": ifName,\n\t\t\t\"swIdx\": swIdx,\n\t\t\t\"vrfID\": route.VrfId,\n\t\t\t\"dstIPAddr\": route.DstIpAddr,\n\t\t}).Debug(\"Remove routes from route cache - outgoing interface was added.\")\n\t\tvrf := strconv.FormatUint(uint64(route.VrfId), 10)\n\t\tif err := plugin.recreateRoute(route, vrf); err != nil {\n\t\t\tplugin.log.Errorf(\"Error recreating interface %s: %v\", ifName, err)\n\t\t}\n\t\tplugin.rtCachedIndexes.UnregisterName(routeWithIndex.RouteID)\n\t}\n}", "func (self *ScriptDef) toInterfaceVal(in string) (interface{}, error) {\n var v interface{}\n if self.Type == \"int\" || self.Type == \"float\" {\n v = float64(0)\n } else if self.Type == \"string\" || self.Type == \"unsafe\" {\n v = \"\"\n if !strings.HasPrefix(in, `\"`) {\n in = fmt.Sprintf(`\"%s\"`, in)\n }\n } else if self.Type == \"bool\" {\n v = false\n } else {\n return nil, errors.New(fmt.Sprintf(\"Unrecognized type %s for %s\", self.Type, self.Name))\n }\n err := json.Unmarshal([]byte(in), &v)\n if err != nil {\n return nil, errors.New(fmt.Sprintf(\"Unable to parse `%s` as %s (%s)\", in, self.Name, self.Type))\n }\n if self.Type == \"int\" {\n return int(v.(float64)), nil\n } else if self.Type == \"string\" {\n return escapeShellArg(v.(string)), nil\n }\n return v, nil\n}", "func (o AttachedDiskResponseOutput) Interface() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) string { return v.Interface }).(pulumi.StringOutput)\n}", "func (o IopingSpecVolumeVolumeSourceIscsiOutput) IscsiInterface() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceIscsi) *string { return v.IscsiInterface }).(pulumi.StringPtrOutput)\n}", "func (s *BasevhdlListener) EnterInterface_variable_declaration(ctx *Interface_variable_declarationContext) {\n}", "func Interface(v r.Value) interface{} {\n\tif !v.IsValid() || !v.CanInterface() || v == None {\n\t\treturn nil\n\t}\n\treturn v.Interface()\n}", "func BpfInterface(fd int, name string) (string, error) {\n\tvar iv ivalue\n\terr := ioctlPtr(fd, BIOCGETIF, unsafe.Pointer(&iv))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn name, nil\n}", "func (ns Int64) Interface() interface{} {\n\tif !ns.Valid {\n\t\treturn nil\n\t}\n\treturn ns.Int64\n}", "func (b bindingContainer) Interface(name string) (ret Interface) {\n\tret, found := b[name]\n\tif !found {\n\t\tpanic(fmt.Errorf(\"Interface \\\"%s\\\" does not exist.\", name))\n\t}\n\treturn\n}", "func (o SavedAttachedDiskResponseOutput) Interface() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SavedAttachedDiskResponse) string { return v.Interface }).(pulumi.StringOutput)\n}", "func (s *Service) RegisterInterface(iface dispatcher) error {\n\tname := iface.VarlinkGetName()\n\tif _, ok := s.interfaces[name]; ok {\n\t\treturn fmt.Errorf(\"interface '%s' already registered\", name)\n\t}\n\n\tif s.running {\n\t\treturn fmt.Errorf(\"service is already running\")\n\t}\n\ts.interfaces[name] = iface\n\ts.descriptions[name] = iface.VarlinkGetDescription()\n\ts.names = append(s.names, name)\n\n\treturn nil\n}", "func parseVariableAsHCL(name string, input string, targetType config.VariableType) (interface{}, error) {\n\t// expecting a string so don't decode anything, just strip quotes\n\tif targetType == config.VariableTypeString {\n\t\treturn strings.Trim(input, `\"`), nil\n\t}\n\n\t// return empty types\n\tif strings.TrimSpace(input) == \"\" {\n\t\tswitch targetType {\n\t\tcase config.VariableTypeList:\n\t\t\treturn []interface{}{}, nil\n\t\tcase config.VariableTypeMap:\n\t\t\treturn make(map[string]interface{}), nil\n\t\t}\n\t}\n\n\tconst sentinelValue = \"SENTINEL_TERRAFORM_VAR_OVERRIDE_KEY\"\n\tinputWithSentinal := fmt.Sprintf(\"%s = %s\", sentinelValue, input)\n\n\tvar decoded map[string]interface{}\n\terr := hcl.Decode(&decoded, inputWithSentinal)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot parse value for variable %s (%q) as valid HCL: %s\", name, input, err)\n\t}\n\n\tif len(decoded) != 1 {\n\t\treturn nil, fmt.Errorf(\"Cannot parse value for variable %s (%q) as valid HCL. Only one value may be specified.\", name, input)\n\t}\n\n\tparsedValue, ok := decoded[sentinelValue]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.\", name, input)\n\t}\n\n\tswitch targetType {\n\tcase config.VariableTypeList:\n\t\treturn parsedValue, nil\n\tcase config.VariableTypeMap:\n\t\tif list, ok := parsedValue.([]map[string]interface{}); ok {\n\t\t\treturn list[0], nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.\", name, input)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown type %s\", targetType.Printable()))\n\t}\n}", "func (t *OpenconfigQos_Qos_Interfaces) NewInterface(InterfaceId string) (*OpenconfigQos_Qos_Interfaces_Interface, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Interface == nil {\n\t\tt.Interface = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface)\n\t}\n\n\tkey := InterfaceId\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.Interface[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Interface\", key)\n\t}\n\n\tt.Interface[key] = &OpenconfigQos_Qos_Interfaces_Interface{\n\t\tInterfaceId: &InterfaceId,\n\t}\n\n\treturn t.Interface[key], nil\n}", "func SVarI(v interface{}) string {\n\t// s, err := json.Marshal ( v )\n\ts, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error:%s\", err)\n\t} else {\n\t\treturn string(s)\n\t}\n}", "func SVarI(v interface{}) string {\n\t// s, err := json.Marshal ( v )\n\ts, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error:%s\", err)\n\t} else {\n\t\treturn string(s)\n\t}\n}", "func SVarI(v interface{}) string {\n\t// s, err := json.Marshal ( v )\n\ts, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error:%s\", err)\n\t} else {\n\t\treturn string(s)\n\t}\n}", "func (g *GremlinQueryHelper) GetInterfaceMetrics(query interface{}) (map[string][]*topology.InterfaceMetric, error) {\n\tdata, err := g.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []map[string][]*topology.InterfaceMetric\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(result) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn result[0], nil\n}", "func SVarI(v interface{}) string {\n\ts, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error:%s\", err)\n\t}\n\treturn string(s)\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_InterfaceRef) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Output_InterfaceRef\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o FioSpecVolumeVolumeSourceIscsiPtrOutput) IscsiInterface() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceIscsi) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.IscsiInterface\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GetEndpointResultOutput) Interface() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) *string { return v.Interface }).(pulumi.StringPtrOutput)\n}", "func GetInterface() js.Value {\n\n\tsingleton.Do(func() {\n\t\tvar err error\n\t\tif fetchinterface, err = js.Global().GetWithErr(\"fetch\"); err != nil {\n\t\t\tfetchinterface = js.Null()\n\t\t}\n\n\t\tresponse.GetInterface()\n\t\tbaseobject.Register(fetchinterface, func(v js.Value) (interface{}, error) {\n\t\t\treturn NewFromJSObject(v)\n\t\t})\n\t})\n\n\treturn fetchinterface\n}", "func Interface(ctx context.Context, i, ch uint8) (gate, key, vel control.CV, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"midi.Interface: %v\", err)\n\t\t}\n\t}()\n\n\tdrv, err := portmididrv.New()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tins, err := drv.Ins()\n\tif len(ins) <= int(i) {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tin := ins[i]\n\tif err := in.Open(); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\trd := reader.New(reader.NoLogger())\n\n\tgateCh := make(chan modular.V)\n\tkeyCh := make(chan modular.V)\n\tvelCh := make(chan modular.V)\n\n\trd.Channel.NoteOn = func(p *reader.Position, channel, key, vel uint8) {\n\t\tif channel != ch {\n\t\t\treturn\n\t\t}\n\t\tgateCh <- 1\n\t\tkeyCh <- modular.V(key)\n\t\tvelCh <- modular.V(vel) / 127\n\t}\n\n\trd.Channel.NoteOff = func(p *reader.Position, channel, key, vel uint8) {\n\t\tif channel != ch {\n\t\t\treturn\n\t\t}\n\t\tgateCh <- 0\n\t\tvelCh <- 0\n\t}\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(gateCh)\n\t\t\tclose(keyCh)\n\t\t\tclose(velCh)\n\t\t}()\n\t\tif err := rd.ListenTo(in); err != nil {\n\t\t\tpanic(fmt.Errorf(\"midi.Interface: %v\", err))\n\t\t}\n\t}()\n\n\treturn gateCh, keyCh, velCh, nil\n}", "func interfaceDecode(dec *gob.Decoder) Pythagoras {\n\t//The decode will fail unless the concrete type on the wire has been registered.\n\t//we registered it in the calling function\n\tvar p Pythagoras\n\terr := dec.Decode(&p)\n\tif err != nil {\n\t\tlog.Fatal(\"Decode:\", err)\n\t}\n\treturn p\n}", "func (r *dedicatedRenderer) ResolveRunnerInterface(impl hubpublicapi.ImplementationRevision) (string, error) {\n\timports, rInterface := impl.Spec.Imports, impl.Spec.Action.RunnerInterface\n\tfullRef, err := hubpublicapi.ResolveActionPathFromImports(imports, rInterface)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fullRef.Path, nil\n}", "func (v Value) Interface() interface{} {\n\treturn v.iface\n}", "func (i *IPInterface) Info() []InterfaceInfo {\n\treturn []InterfaceInfo{\n\t\tInterfaceInfo{\n\t\t\tAddress: i.BridgeIP.String(),\n\t\t\tName: i.bridgeName,\n\t\t\tKind: \"bridge\",\n\t\t},\n\t\tInterfaceInfo{\n\t\t\tName: i.hostVeth,\n\t\t\tKind: \"host-veth\",\n\t\t},\n\t\tInterfaceInfo{\n\t\t\tAddress: i.SiloIP.String(),\n\t\t\tName: i.siloVeth,\n\t\t\tKind: \"silo-veth\",\n\t\t},\n\t}\n}", "func (idx *Index) InsertInterface(location extract.Location, ifc types.Interface) {\n\tidx.results = append(idx.results, &Result{\n\t\tName: ifc.Name,\n\t\tLocation: location,\n\t\tValue: &ifc,\n\t})\n\tid := len(idx.results) - 1\n\n\tidx.insertLocation(id, location)\n\n\t// Index on name.\n\tidx.textIndex.Insert(id, confidenceHigh, ifc.Name)\n\tnameTokens := cases.Split(ifc.Name)\n\tif len(nameTokens) > 1 {\n\t\tidx.textIndex.Insert(id, confidenceHigh/len(nameTokens), nameTokens...)\n\t}\n\n\t// Index on embedded interfaces.\n\tif len(ifc.Embedded) > 0 {\n\t\tfor _, embedded := range ifc.Embedded {\n\t\t\tidx.textIndex.Insert(id, confidenceMed/len(ifc.Embedded), embedded.Name)\n\t\t}\n\t\tembeddedNameTokens := []string{}\n\t\tfor _, embedded := range ifc.Embedded {\n\t\t\tif embedded.Package != \"\" {\n\t\t\t\tembeddedNameTokens = append(embeddedNameTokens, embedded.Package)\n\t\t\t}\n\t\t\tembeddedNameTokens = append(embeddedNameTokens, cases.Split(embedded.Name)...)\n\t\t}\n\t\tif len(embeddedNameTokens) > 1 {\n\t\t\tidx.textIndex.Insert(id, confidenceMed/len(embeddedNameTokens), embeddedNameTokens...)\n\t\t}\n\t}\n\n\t// Index on methods.\n\tif len(ifc.Methods) > 0 {\n\t\tfor _, method := range ifc.Methods {\n\t\t\tidx.textIndex.Insert(id, confidenceMed/len(ifc.Methods), method.Name)\n\t\t}\n\t\tmethodNameTokens := []string{}\n\t\tfor _, method := range ifc.Methods {\n\t\t\tmethodNameTokens = append(methodNameTokens, cases.Split(method.Name)...)\n\t\t}\n\t\tif len(methodNameTokens) > 1 {\n\t\t\tidx.textIndex.Insert(id, confidenceMed/len(methodNameTokens), methodNameTokens...)\n\t\t}\n\t}\n}", "func InterfaceExecute(env map[string]string, params interface{}) error {\n\tosType, ok := env[\"os\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"can not get os type\")\n\t}\n\n\troot, ok := env[\"root\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"can not get mount root type\")\n\t}\n\n\tifaceConf := params.(map[string]string)\n\n\tswitch osType {\n\tcase cloudimageeditorcore.OSCentos:\n\t\treturn setCentosInterface(root, ifaceConf)\n\n\tcase cloudimageeditorcore.OSUbuntu:\n\t\treturn setUbuntuInterface(root, ifaceConf)\n\n\tcase cloudimageeditorcore.OSUnknown:\n\t\tfallthrough\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported os type : %s\", osType)\n\t}\n}", "func (s *Session) GetInterface() *network.NetworkInterface {\n\tif s.inter != nil {\n\t\treturn s.inter\n\t}\n\n\tremAddr := s.session.RemoteAddr()\n\tuadr, ok := remAddr.(*net.UDPAddr)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tinter, _ := network.FromAddr(uadr.IP)\n\ts.inter = inter\n\treturn inter\n}", "func (self *PhysicsP2) GetBodyI(args ...interface{}) *P2Body{\n return &P2Body{self.Object.Call(\"getBody\", args)}\n}", "func (o *Wireless) SetInterface(v string) {\n\to.Interface = &v\n}", "func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterfaceInterfaceRefConfig(ctx context.Context, interfaceId string, frinxOpenconfigInterfacesInterfacerefInterfacerefConfigBodyParam FrinxOpenconfigInterfacesInterfacerefInterfacerefConfigRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/frinx-logging:interface-ref/frinx-logging:config/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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\", \"application/xml\"}\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 = &frinxOpenconfigInterfacesInterfacerefInterfacerefConfigBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\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\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (v *Value) Interface() interface{} {\n\tswitch v.Kind() {\n\tcase Long:\n\t\treturn v.Int()\n\tcase Double:\n\t\treturn v.Float()\n\tcase Bool:\n\t\treturn v.Bool()\n\tcase String:\n\t\treturn v.String()\n\tcase Array:\n\t\treturn v.Slice()\n\tcase Map, Object:\n\t\treturn v.Map()\n\t}\n\n\treturn nil\n}", "func (s *FieldStep) Interface() interface{} {\n\treturn *((*s).StructField)\n}", "func (o *IpamIPAddressesListParams) SetInterface(interfaceVar *string) {\n\to.Interface = interfaceVar\n}", "func (o *EditBankConnectionParams) SetInterface(v BankingInterface) {\n\to.Interface = &v\n}", "func InterfaceMetrics(ctx traversal.StepContext, tv *traversal.GraphTraversalV, key string) *MetricsTraversalStep {\n\tif tv.Error() != nil {\n\t\treturn NewMetricsTraversalStepFromError(tv.Error())\n\t}\n\n\tstartField := key + \".Start\"\n\ttv = tv.Dedup(ctx, \"@ID\", startField).Sort(ctx, filters.SortOrder_Ascending, startField)\n\n\tif tv.Error() != nil {\n\t\treturn NewMetricsTraversalStepFromError(tv.Error())\n\t}\n\n\ttv.GraphTraversal.RLock()\n\tdefer tv.GraphTraversal.RUnlock()\n\n\tmetrics := make(map[string][]common.Metric)\n\tit := ctx.PaginationRange.Iterator()\n\tgslice := tv.GraphTraversal.Graph.GetContext().TimeSlice\n\nnodeloop:\n\tfor _, n := range tv.GetNodes() {\n\t\tif it.Done() {\n\t\t\tbreak nodeloop\n\t\t}\n\n\t\tm, _ := n.GetField(key)\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tlastmetric, ok := m.(common.Metric)\n\t\tif !ok {\n\t\t\treturn NewMetricsTraversalStepFromError(errors.New(\"wrong interface metric type\"))\n\t\t}\n\n\t\tif gslice == nil || (lastmetric.GetStart() > gslice.Start && lastmetric.GetLast() < gslice.Last) && it.Next() {\n\t\t\tmetrics[string(n.ID)] = append(metrics[string(n.ID)], lastmetric)\n\t\t}\n\t}\n\n\treturn NewMetricsTraversalStep(tv.GraphTraversal, metrics)\n}", "func (h *IPSecVppHandler) AddTunnelInterface(tunnel *ipsec.TunnelInterfaces_Tunnel) (uint32, error) {\n\treturn h.tunnelIfAddDel(tunnel, true)\n}", "func (cs ClientState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {\n\treturn cs.ConsensusState.UnpackInterfaces(unpacker)\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_InterfaceRef) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_InterfaceRef\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func InterfacesHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tT, _ := i18n.Tfunc(\"en-US\")\n\n\t// Build the snapd REST API URL\n\tconst serviceInterfacesURL = \"/v2/interfaces\"\n\tbaseURL := url.URL{Scheme: \"http\", Host: \"localhost\", Path: serviceInterfacesURL}\n\n\ttr := &http.Transport{\n\t\tDial: snapdDialer,\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(baseURL.String())\n\tif err != nil {\n\t\tlogMessage(\"interfaces\", \"snapd-url\", err.Error())\n\t\tresponse := ErrorResponse{Type: \"error\", Status: \"Internal Error\", StatusCode: 404, Result: T(\"application_error\")}\n\t\t// Encode the response as JSON\n\t\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\t\tlog.Println(\"Error forming the error response.\")\n\t\t}\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlogMessage(\"interfaces\", \"snapd-response\", err.Error())\n\t\tresponse := ErrorResponse{Type: \"error\", Status: \"Not Found\", StatusCode: 404, Result: T(\"unknown\")}\n\t\t// Encode the response as JSON\n\t\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\t\tlog.Println(\"Error forming the error response.\")\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Fprint(w, string(body))\n}", "func (d *decoder) iface(key string, value reflect.Value, def string) error {\n\tv := d.getGlobalProvider().Get(key)\n\n\tif !v.HasValue() || v.Value() == nil {\n\t\treturn nil\n\t}\n\n\tsrc := reflect.ValueOf(v.Value())\n\tif src.Type().Implements(value.Type()) {\n\t\tvalue.Set(src)\n\t\treturn nil\n\t}\n\n\treturn errorWithKey(fmt.Errorf(\"%q doesn't implement %q\", src.Type(), value.Type()), key)\n}", "func (in *EnvoyFilter_ListenerMatch) DeepCopyInterface() interface{} {\n\treturn in.DeepCopy()\n}", "func (o IopingSpecVolumeVolumeSourceIscsiPtrOutput) IscsiInterface() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceIscsi) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.IscsiInterface\n\t}).(pulumi.StringPtrOutput)\n}", "func InterfaceString(s string) (Interface, error) {\n\tif val, ok := _InterfaceNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\n\tif val, ok := _InterfaceNameToValueMap[strings.ToLower(s)]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to Interface values\", s)\n}", "func InterfaceString(s string) (Interface, error) {\n\tif val, ok := _InterfaceNameToValueMap[s]; ok {\n\t\treturn val, nil\n\t}\n\treturn 0, fmt.Errorf(\"%s does not belong to Interface values\", s)\n}", "func (cl *AgentClient) InterfaceCreate(postData netproto.Interface) error {\n\tvar resp Response\n\n\terr := netutils.HTTPPost(\"http://\"+cl.agentURL+\"/api/interfaces/\", &postData, &resp)\n\n\treturn err\n\n}", "func Interface(ifname string) func(*NetworkTap) error {\n\treturn func(filterdev *NetworkTap) error {\n\t\terr := filterdev.SetInterface(int(filterdev.device.Fd()), ifname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (a *FrinxOpenconfigIfIpApiService) PutFrinxOpenconfigInterfacesInterfacesInterfaceRoutedVlanIpv6UnnumberedInterfaceRef(ctx context.Context, name string, frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam FrinxOpenconfigInterfacesInterfacerefInterfaceRefRequest7, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-interfaces:interfaces/frinx-openconfig-interfaces:interface/{name}/frinx-openconfig-vlan:routed-vlan/frinx-openconfig-if-ip:ipv6/frinx-openconfig-if-ip:unnumbered/frinx-openconfig-if-ip:interface-ref/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\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\", \"application/xml\"}\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 = &frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\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\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (*InterfaceTunnels) GetPath() string { return \"/api/objects/interface/tunnel/\" }", "func (_Erc1820Registry *Erc1820RegistryCallerSession) InterfaceHash(_interfaceName string) ([32]byte, error) {\n\treturn _Erc1820Registry.Contract.InterfaceHash(&_Erc1820Registry.CallOpts, _interfaceName)\n}", "func FromInterface(value interface{}) (Number, error) {\n\n\tswitch value.(type) {\n\tcase string:\n\t\tvalue = strings.Parse(value.(string))\n\t}\n\n\tswitch value.(type) {\n\tcase string:\n\t\tn, err := strconv.ParseFloat(value.(string), 64)\n\t\tif err != nil {\n\t\t\treturn NumberZero, err\n\t\t}\n\t\treturn Number(n), nil\n\tcase bool:\n\t\tif value.(bool) {\n\t\t\treturn NumberTrue, nil\n\t\t} else {\n\t\t\treturn NumberFalse, nil\n\t\t}\n\tcase int:\n\t\treturn Number(value.(int)), nil\n\tcase int8:\n\t\treturn Number(value.(int8)), nil\n\tcase int16:\n\t\treturn Number(value.(int16)), nil\n\tcase int32:\n\t\treturn Number(value.(int32)), nil\n\tcase int64:\n\t\treturn Number(value.(int64)), nil\n\tcase uint:\n\t\treturn Number(value.(uint)), nil\n\tcase uint8:\n\t\treturn Number(value.(uint8)), nil\n\tcase uint16:\n\t\treturn Number(value.(uint16)), nil\n\tcase uint32:\n\t\treturn Number(value.(uint32)), nil\n\tcase uint64:\n\t\treturn Number(value.(uint64)), nil\n\tcase float32:\n\t\treturn Number(value.(float32)), nil\n\tcase float64:\n\t\treturn Number(value.(float64)), nil\n\t}\n\n\treturn NumberZero, nil\n}", "func (dsl *PutDSL) VppInterface(val *vpp_intf.Interfaces_Interface) linux.PutDSL {\n\tdsl.vppPut.Interface(val)\n\treturn dsl\n}", "func (dsl *PutDSL) VppInterface(val *vpp_intf.Interfaces_Interface) linux.PutDSL {\n\tdsl.vppPut.Interface(val)\n\treturn dsl\n}", "func UnmarshalInfrastructureIntegrationEntityInterface(b []byte) (*InfrastructureIntegrationEntityInterface, error) {\n\tvar err error\n\n\tvar rawMessageInfrastructureIntegrationEntity map[string]*json.RawMessage\n\terr = json.Unmarshal(b, &rawMessageInfrastructureIntegrationEntity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Nothing to unmarshal\n\tif len(rawMessageInfrastructureIntegrationEntity) < 1 {\n\t\treturn nil, nil\n\t}\n\n\tvar typeName string\n\n\tif rawTypeName, ok := rawMessageInfrastructureIntegrationEntity[\"__typename\"]; ok {\n\t\terr = json.Unmarshal(*rawTypeName, &typeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch typeName {\n\t\tcase \"GenericInfrastructureEntity\":\n\t\t\tvar interfaceType GenericInfrastructureEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx InfrastructureIntegrationEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"InfrastructureAwsLambdaFunctionEntity\":\n\t\t\tvar interfaceType InfrastructureAwsLambdaFunctionEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx InfrastructureIntegrationEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\t}\n\t} else {\n\t\tkeys := []string{}\n\t\tfor k := range rawMessageInfrastructureIntegrationEntity {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"interface InfrastructureIntegrationEntity did not include a __typename field for inspection: %s\", keys)\n\t}\n\n\treturn nil, fmt.Errorf(\"interface InfrastructureIntegrationEntity was not matched against all PossibleTypes: %s\", typeName)\n}", "func BoolInterfaceVar(f *pflag.FlagSet, p interface{}, name string, value interface{}, usage string) {\n\tBoolInterfaceVarP(f, p, name, \"\", value, usage)\n}", "func (x *fastReflection_Output) Interface() protoreflect.ProtoMessage {\n\treturn (*Output)(x)\n}", "func MDTInterfaceII() *telemetry.Telemetry {\n\treturn &telemetry.Telemetry{\n\t\tNodeId: &telemetry.Telemetry_NodeIdStr{NodeIdStr: \"ios\"},\n\t\tSubscription: &telemetry.Telemetry_SubscriptionIdStr{SubscriptionIdStr: \"Sub3\"},\n\t\tEncodingPath: \"openconfig-interfaces:interfaces/interface\",\n\t\tCollectionId: 11,\n\t\tCollectionStartTime: 1597098790977,\n\t\tMsgTimestamp: 1597098790977,\n\t\tDataGpbkv: []*telemetry.TelemetryField{\n\t\t\t{\n\t\t\t\tTimestamp: 1597098791076,\n\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"keys\",\n\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"name\",\n\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_StringValue{StringValue: \"GigabitEthernet0/0/0/0\"},\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\t{\n\t\t\t\t\t\tName: \"content\",\n\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"state\",\n\t\t\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tName: \"counters\",\n\t\t\t\t\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tName: \"in-octets\",\n\t\t\t\t\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_Uint64Value{Uint64Value: 1023},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tName: \"out-octets\",\n\t\t\t\t\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_Uint64Value{Uint64Value: 872},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tTimestamp: 1597098791086,\n\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"keys\",\n\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"name\",\n\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_StringValue{StringValue: \"GigabitEthernet0/0/0/1\"},\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\t{\n\t\t\t\t\t\tName: \"content\",\n\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"state\",\n\t\t\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tName: \"counters\",\n\t\t\t\t\t\t\t\t\t\tFields: []*telemetry.TelemetryField{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tName: \"in-octets\",\n\t\t\t\t\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_Uint64Value{Uint64Value: 1223},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tName: \"out-octets\",\n\t\t\t\t\t\t\t\t\t\t\t\tValueByType: &telemetry.TelemetryField_Uint64Value{Uint64Value: 8172},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCollectionEndTime: 1597098791977,\n\t}\n}", "func (_Erc1820Registry *Erc1820RegistryCaller) InterfaceHash(opts *bind.CallOpts, _interfaceName string) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Erc1820Registry.contract.Call(opts, &out, \"interfaceHash\", _interfaceName)\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (plugin *FIBConfigurator) ResolveCreatedInterface(ifName string, ifIdx uint32, callback func(error)) error {\n\tplugin.log.Infof(\"FIB configurator: resolving registered interface %s\", ifName)\n\n\tif err := plugin.resolveRegisteredItem(callback); err != nil {\n\t\treturn err\n\t}\n\n\tplugin.log.Infof(\"FIB: resolution of created interface %s is done\", ifName)\n\treturn nil\n}", "func FromInterface(prefix string, input interface{}) (Object, error) {\n\tswitch vv := input.(type) {\n\tcase nil:\n\t\treturn NewStringObj(prefix, \"\"), nil\n\tcase string:\n\t\treturn NewStringObj(prefix, vv), nil\n\tcase bool:\n\t\treturn NewBoolObj(prefix, vv), nil\n\tcase float64:\n\t\treturn NewNumberObj(prefix, vv), nil\n\tcase map[string]interface{}:\n\t\tobj, err := NewMapObj(prefix, vv)\n\t\tif err != nil {\n\t\t\treturn nil, oops.Wrapf(err, \"unable to create MapObj for interface: %+v\", vv)\n\t\t}\n\t\treturn obj, nil\n\tcase []interface{}:\n\t\tobj, err := NewArrayObj(prefix, vv)\n\t\tif err != nil {\n\t\t\treturn nil, oops.Wrapf(err, \"unable to create ArrayObj for interface: %+v\", vv)\n\t\t}\n\t\treturn obj, nil\n\tdefault:\n\t\treturn nil, oops.Errorf(\"unable to create Object from interface: %+v\", input)\n\t}\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Tunnel) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Tunnel\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDiskResponseOutput) Interface() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDiskResponse) string {\n\t\treturn v.Interface\n\t}).(pulumi.StringOutput)\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv6) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv6\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (filterdev *NetworkTap) Interface(name string) (string, error) {\n\tvar iv ivalue\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(filterdev.device.Fd()), syscall.BIOCGETIF, uintptr(unsafe.Pointer(&iv)))\n\tif err != 0 {\n\t\treturn \"\", syscall.Errno(err)\n\t}\n\treturn name, nil\n}", "func (_Erc1820Registry *Erc1820RegistrySession) InterfaceHash(_interfaceName string) ([32]byte, error) {\n\treturn _Erc1820Registry.Contract.InterfaceHash(&_Erc1820Registry.CallOpts, _interfaceName)\n}", "func (t *OpenconfigAcl_Acl_Interfaces_Interface_InterfaceRef) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigAcl_Acl_Interfaces_Interface_InterfaceRef\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func UnmarshalAlertableEntityInterface(b []byte) (*AlertableEntityInterface, error) {\n\tvar err error\n\n\tvar rawMessageAlertableEntity map[string]*json.RawMessage\n\terr = json.Unmarshal(b, &rawMessageAlertableEntity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Nothing to unmarshal\n\tif len(rawMessageAlertableEntity) < 1 {\n\t\treturn nil, nil\n\t}\n\n\tvar typeName string\n\n\tif rawTypeName, ok := rawMessageAlertableEntity[\"__typename\"]; ok {\n\t\terr = json.Unmarshal(*rawTypeName, &typeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch typeName {\n\t\tcase \"ApmApplicationEntity\":\n\t\t\tvar interfaceType ApmApplicationEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"BrowserApplicationEntity\":\n\t\t\tvar interfaceType BrowserApplicationEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"ExternalEntity\":\n\t\t\tvar interfaceType ExternalEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"GenericInfrastructureEntity\":\n\t\t\tvar interfaceType GenericInfrastructureEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"InfrastructureAwsLambdaFunctionEntity\":\n\t\t\tvar interfaceType InfrastructureAwsLambdaFunctionEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"InfrastructureHostEntity\":\n\t\t\tvar interfaceType InfrastructureHostEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"MobileApplicationEntity\":\n\t\t\tvar interfaceType MobileApplicationEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"SyntheticMonitorEntity\":\n\t\t\tvar interfaceType SyntheticMonitorEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"ThirdPartyServiceEntity\":\n\t\t\tvar interfaceType ThirdPartyServiceEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\tcase \"WorkloadEntity\":\n\t\t\tvar interfaceType WorkloadEntity\n\t\t\terr = json.Unmarshal(b, &interfaceType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvar xxx AlertableEntityInterface = &interfaceType\n\n\t\t\treturn &xxx, nil\n\t\t}\n\t} else {\n\t\tkeys := []string{}\n\t\tfor k := range rawMessageAlertableEntity {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"interface AlertableEntity did not include a __typename field for inspection: %s\", keys)\n\t}\n\n\treturn nil, fmt.Errorf(\"interface AlertableEntity was not matched against all PossibleTypes: %s\", typeName)\n}", "func (s *ArrayStep) Interface() interface{} {\n\treturn int(*s)\n}", "func (plugin *BDConfigurator) ResolveCreatedInterface(interfaceName string, interfaceIndex uint32) error {\n\tplugin.Log.Infof(\"Resolving new interface %v\", interfaceName)\n\t// Look whether interface belongs to some bridge domain using interface-to-bd mapping\n\t_, meta, found := plugin.IfToBdIndexes.LookupIdx(interfaceName)\n\tif !found {\n\t\tplugin.Log.Debugf(\"Interface %s does not belong to any bridge domain\", interfaceName)\n\t\treturn nil\n\t}\n\t_, _, alreadyCreated := plugin.IfToBdRealStateIdx.LookupIdx(interfaceName)\n\tif alreadyCreated {\n\t\tplugin.Log.Debugf(\"Interface %s has been already configured\", interfaceName)\n\t\treturn nil\n\t}\n\tbridgeDomainIndex := meta.(*BridgeDomainMeta).BridgeDomainIndex\n\tbvi := meta.(*BridgeDomainMeta).IsInterfaceBvi\n\n\tvppcalls.VppSetInterfaceToBridgeDomain(bridgeDomainIndex, interfaceIndex, bvi, plugin.Log, plugin.vppChan,\n\t\tmeasure.GetTimeLog(vpe.SwInterfaceSetL2Bridge{}, plugin.Stopwatch))\n\t// Register interface to real state\n\tplugin.IfToBdRealStateIdx.RegisterName(interfaceName, interfaceIndex, meta)\n\n\t// Push to bridge domain state\n\tbridgeDomainName, _, found := plugin.BdIndexes.LookupName(bridgeDomainIndex)\n\tif !found {\n\t\treturn fmt.Errorf(\"unable to update status for bridge domain, index %v not found in mapping\", bridgeDomainIndex)\n\t}\n\terr := plugin.LookupBridgeDomainDetails(bridgeDomainIndex, bridgeDomainName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *LinuxInterfaceConfigurator) ResolveCreatedVPPInterface(ifConfigMetaData *vppIf.Interfaces_Interface) error {\n\tif ifConfigMetaData == nil {\n\t\treturn errors.Errorf(\"unable to resolve registered VPP interface %s, no configuration data available\",\n\t\t\tifConfigMetaData.Name)\n\t}\n\n\tif ifConfigMetaData.Type != vppIf.InterfaceType_TAP_INTERFACE {\n\t\treturn nil\n\t}\n\n\tvar hostIfName string\n\tif ifConfigMetaData.Tap != nil {\n\t\thostIfName = ifConfigMetaData.GetTap().GetHostIfName()\n\t}\n\tif hostIfName == \"\" {\n\t\thostIfName = ifConfigMetaData.GetName()\n\t}\n\tif hostIfName == \"\" {\n\t\treturn errors.Errorf(\"unable to resolve registered VPP interface %s, incomplete configuration data\",\n\t\t\tifConfigMetaData.Name)\n\t}\n\n\tvar linuxIf *interfaces.LinuxInterfaces_Interface\n\t_, data, exists := c.ifCachedConfigs.LookupIdx(hostIfName)\n\tif exists && data != nil {\n\t\tlinuxIf = data.Data\n\t}\n\n\tif err := c.configureTapInterface(hostIfName, linuxIf); err != nil {\n\t\treturn errors.Errorf(\"failed to configure linux interface %s with registered VPP interface %s: %v\",\n\t\t\tifConfigMetaData.Name, linuxIf, err)\n\t}\n\n\treturn nil\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigLacp_Lacp_Interfaces_Interface) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigLacp_Lacp_Interfaces_Interface\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.55795044", "0.51478267", "0.49027494", "0.47865677", "0.47764078", "0.47680923", "0.47650835", "0.47002855", "0.46863744", "0.4685422", "0.4671812", "0.45863968", "0.45840946", "0.45613533", "0.45384187", "0.45297757", "0.45211256", "0.45093277", "0.4499774", "0.4471015", "0.4460992", "0.44600797", "0.44539323", "0.44478852", "0.44424894", "0.44383094", "0.44190487", "0.44100285", "0.43528756", "0.4340959", "0.4330557", "0.4303997", "0.42854887", "0.42837462", "0.42809317", "0.4271921", "0.42677265", "0.426582", "0.42597327", "0.42597327", "0.42597327", "0.4250249", "0.42306435", "0.42228425", "0.42227316", "0.42181572", "0.4200161", "0.41915336", "0.41913447", "0.4180597", "0.41802606", "0.41647166", "0.4154757", "0.41319498", "0.4128486", "0.41275683", "0.41275498", "0.41144332", "0.4112859", "0.4110516", "0.41077894", "0.4107631", "0.40985417", "0.40926877", "0.40854338", "0.4082856", "0.40798143", "0.40591466", "0.40582508", "0.40550837", "0.405251", "0.4052293", "0.4051428", "0.40507913", "0.4049499", "0.404629", "0.40437025", "0.40435943", "0.40407866", "0.40407866", "0.4035453", "0.40299568", "0.40272933", "0.4026329", "0.40253657", "0.40231642", "0.40223828", "0.40191868", "0.40162736", "0.40105084", "0.40045938", "0.40034303", "0.39975134", "0.39887932", "0.39845031", "0.39828807", "0.39808124", "0.39759928", "0.39742866", "0.39711297" ]
0.7099388
0
GetStdlibFuncs returns the set of stdlib functions.
func GetStdlibFuncs() map[string]function.Function { return map[string]function.Function{ "abs": stdlib.AbsoluteFunc, "coalesce": stdlib.CoalesceFunc, "concat": stdlib.ConcatFunc, "hasindex": stdlib.HasIndexFunc, "int": stdlib.IntFunc, "jsondecode": stdlib.JSONDecodeFunc, "jsonencode": stdlib.JSONEncodeFunc, "length": stdlib.LengthFunc, "lower": stdlib.LowerFunc, "max": stdlib.MaxFunc, "min": stdlib.MinFunc, "reverse": stdlib.ReverseFunc, "strlen": stdlib.StrlenFunc, "substr": stdlib.SubstrFunc, "upper": stdlib.UpperFunc, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetAllBuiltinFunctions() []*BuiltinFunction {\n\treturn append([]*BuiltinFunction{}, builtinFuncs...)\n}", "func GetFunctions() []string {\n\tout := make([]string, len(flist))\n\tcopy(out, flist)\n\treturn out\n}", "func (l *AuthFuncListSafe) GetFuncs() []AuthFuncInstance {\n\tret := make([]AuthFuncInstance, len(l.funcList))\n\tl.listMutex.Lock()\n\tcopy(ret, l.funcList)\n\tl.listMutex.Unlock()\n\treturn ret\n}", "func StdLib() EnvOption {\n\treturn Lib(stdLibrary{})\n}", "func getAllFuncs() template.FuncMap {\n\treturn template.FuncMap{\"markDown\": markDowner, \"date\": dater.FriendlyDater, \"holder\": holder}\n}", "func isStdLib(pkg *packages.Package) bool {\n\tif pkg.Name == \"unsafe\" {\n\t\t// Special case unsafe stdlib, because it does not contain go files.\n\t\treturn true\n\t}\n\tif len(pkg.GoFiles) == 0 {\n\t\treturn false\n\t}\n\tprefix := build.Default.GOROOT\n\tsep := string(filepath.Separator)\n\tif !strings.HasSuffix(prefix, sep) {\n\t\tprefix += sep\n\t}\n\treturn strings.HasPrefix(pkg.GoFiles[0], prefix)\n}", "func (e *Evaluator) GetFunctions() []functions.Function {\n\tresult := make([]functions.Function, 0, len(e.functions))\n\tfor _, function := range e.functions {\n\t\tresult = append(result, function)\n\t}\n\treturn result\n}", "func (p *PKGBUILD) GetFunctions() (out []string) {\n\tdone := make(map[string]bool)\n\tinfos := p.info.Variables()\n\tfor _, e := range infos {\n\t\tname := e.Name()\n\t\tif !done[name] {\n\t\t\tdone[name] = true\n\t\t\tout = append(out, name)\n\t\t}\n\t}\n\treturn\n}", "func (p *Platform) GetFunctions(getOptions *platform.GetOptions) ([]platform.Function, error) {\n\tgetContainerOptions := &dockerclient.GetContainerOptions{\n\t\tLabels: map[string]string{\n\t\t\t\"nuclio-platform\": \"local\",\n\t\t\t\"nuclio-namespace\": getOptions.Common.Namespace,\n\t\t},\n\t}\n\n\t// if we need to get only one function, specify its function name\n\tif getOptions.Common.Identifier != \"\" {\n\t\tgetContainerOptions.Labels[\"nuclio-function-name\"] = getOptions.Common.Identifier\n\t}\n\n\tcontainersInfo, err := p.dockerClient.GetContainers(getContainerOptions)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to get containers\")\n\t}\n\n\tvar functions []platform.Function\n\tfor _, containerInfo := range containersInfo {\n\n\t\t// create a local.function object which wraps a dockerclient.containerInfo and\n\t\t// implements platform.Function\n\t\tfunctions = append(functions, &function{containerInfo})\n\t}\n\n\treturn functions, nil\n}", "func (t *TestCluster) ListNativeFunctions() []string {\n\treturn t.NativeFuncs\n}", "func initBuiltinFuncs(builtin *types.Package) {\n\tfns := [...]struct {\n\t\tname string\n\t\ttparams []typeTParam\n\t\tparams []typeXParam\n\t\tresult xType\n\t}{\n\t\t{\"copy\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"dst\", xtSlice}, {\"src\", xtSlice}}, types.Typ[types.Int]},\n\t\t// func [Type any] copy(dst, src []Type) int\n\n\t\t{\"close\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"c\", xtChanIn}}, nil},\n\t\t// func [Type any] close(c chan<- Type)\n\n\t\t{\"append\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"slice\", xtSlice}, {\"elems\", xtEllipsis}}, xtSlice},\n\t\t// func [Type any] append(slice []Type, elems ...Type) []Type\n\n\t\t{\"delete\", []typeTParam{{\"Key\", comparable}, {\"Elem\", any}}, []typeXParam{{\"m\", xtMap}, {\"key\", 0}}, nil},\n\t\t// func [Key comparable, Elem any] delete(m map[Key]Elem, key Key)\n\t}\n\tgbl := builtin.Scope()\n\tfor _, fn := range fns {\n\t\ttparams := newTParams(fn.tparams)\n\t\tn := len(fn.params)\n\t\tparams := make([]*types.Var, n)\n\t\tfor i, param := range fn.params {\n\t\t\ttyp := newXParamType(tparams, param.typ)\n\t\t\tparams[i] = types.NewParam(token.NoPos, builtin, param.name, typ)\n\t\t}\n\t\tvar ellipsis bool\n\t\tif tidx, ok := fn.params[n-1].typ.(int); ok && (tidx&xtEllipsis) != 0 {\n\t\t\tellipsis = true\n\t\t}\n\t\tvar results *types.Tuple\n\t\tif fn.result != nil {\n\t\t\ttyp := newXParamType(tparams, fn.result)\n\t\t\tresults = types.NewTuple(types.NewParam(token.NoPos, builtin, \"\", typ))\n\t\t}\n\t\ttsig := NewTemplateSignature(tparams, nil, types.NewTuple(params...), results, ellipsis, tokFlagApproxType)\n\t\tvar tfn types.Object = NewTemplateFunc(token.NoPos, builtin, fn.name, tsig)\n\t\tif fn.name == \"append\" { // append is a special case\n\t\t\tappendString := NewInstruction(token.NoPos, builtin, \"append\", appendStringInstr{})\n\t\t\ttfn = NewOverloadFunc(token.NoPos, builtin, \"append\", appendString, tfn)\n\t\t} else if fn.name == \"copy\" {\n\t\t\t// func [S string] copy(dst []byte, src S) int\n\t\t\ttparams := newTParams([]typeTParam{{\"S\", tstring}})\n\t\t\tdst := types.NewParam(token.NoPos, builtin, \"dst\", types.NewSlice(types.Typ[types.Byte]))\n\t\t\tsrc := types.NewParam(token.NoPos, builtin, \"src\", tparams[0])\n\t\t\tret := types.NewParam(token.NoPos, builtin, \"\", types.Typ[types.Int])\n\t\t\ttsig := NewTemplateSignature(tparams, nil, types.NewTuple(dst, src), types.NewTuple(ret), false)\n\t\t\tcopyString := NewTemplateFunc(token.NoPos, builtin, \"copy\", tsig)\n\t\t\ttfn = NewOverloadFunc(token.NoPos, builtin, \"copy\", copyString, tfn)\n\t\t}\n\t\tgbl.Insert(tfn)\n\t}\n\toverloads := [...]struct {\n\t\tname string\n\t\tfns [3]typeBFunc\n\t}{\n\t\t{\"complex\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"r\", types.UntypedFloat}, {\"i\", types.UntypedFloat}}, types.UntypedComplex},\n\t\t\t{[]typeBParam{{\"r\", types.Float32}, {\"i\", types.Float32}}, types.Complex64},\n\t\t\t{[]typeBParam{{\"r\", types.Float64}, {\"i\", types.Float64}}, types.Complex128},\n\t\t}},\n\t\t// func complex(r, i untyped_float) untyped_complex\n\t\t// func complex(r, i float32) complex64\n\t\t// func complex(r, i float64) complex128\n\n\t\t{\"real\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"c\", types.UntypedComplex}}, types.UntypedFloat},\n\t\t\t{[]typeBParam{{\"c\", types.Complex64}}, types.Float32},\n\t\t\t{[]typeBParam{{\"c\", types.Complex128}}, types.Float64},\n\t\t}},\n\t\t// func real(c untyped_complex) untyped_float\n\t\t// func real(c complex64) float32\n\t\t// func real(c complex128) float64\n\n\t\t{\"imag\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"c\", types.UntypedComplex}}, types.UntypedFloat},\n\t\t\t{[]typeBParam{{\"c\", types.Complex64}}, types.Float32},\n\t\t\t{[]typeBParam{{\"c\", types.Complex128}}, types.Float64},\n\t\t}},\n\t\t// func imag(c untyped_complex) untyped_float\n\t\t// func imag(c complex64) float32\n\t\t// func imag(c complex128) float64\n\t}\n\tfor _, overload := range overloads {\n\t\tfns := []types.Object{\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[0]),\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[1]),\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[2]),\n\t\t}\n\t\tgbl.Insert(NewOverloadFunc(token.NoPos, builtin, overload.name, fns...))\n\t}\n\t// func panic(v interface{})\n\t// func recover() interface{}\n\t// func print(args ...interface{})\n\t// func println(args ...interface{})\n\temptyIntfVar := types.NewVar(token.NoPos, builtin, \"v\", TyEmptyInterface)\n\temptyIntfTuple := types.NewTuple(emptyIntfVar)\n\temptyIntfSlice := types.NewSlice(TyEmptyInterface)\n\temptyIntfSliceVar := types.NewVar(token.NoPos, builtin, \"args\", emptyIntfSlice)\n\temptyIntfSliceTuple := types.NewTuple(emptyIntfSliceVar)\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"panic\", types.NewSignature(nil, emptyIntfTuple, nil, false)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"recover\", types.NewSignature(nil, nil, emptyIntfTuple, false)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"print\", types.NewSignature(nil, emptyIntfSliceTuple, nil, true)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"println\", types.NewSignature(nil, emptyIntfSliceTuple, nil, true)))\n\n\t// new & make are special cases, they require to pass a type.\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"new\", newInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"make\", makeInstr{}))\n\n\t// len & cap are special cases, because they may return a constant value.\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"len\", lenInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"cap\", capInstr{}))\n\n\t// unsafe\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Sizeof\", unsafeSizeofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Alignof\", unsafeAlignofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Offsetof\", unsafeOffsetofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Add\", unsafeAddInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Slice\", unsafeSliceInstr{}))\n}", "func stdlibResolver() Resolver { return stdlib{} }", "func (dp *Dumper) getFunctions() ([]functionSchema, error) {\n\tquery := \"\" +\n\t\t\"SELECT n.nspname, p.proname, l.lanname, \" +\n\t\t\" CASE WHEN l.lanname = 'internal' THEN p.prosrc ELSE pg_get_functiondef(p.oid) END as definition, \" +\n\t\t\" pg_get_function_arguments(p.oid) \" +\n\t\t\"FROM pg_proc p \" +\n\t\t\"LEFT JOIN pg_namespace n ON p.pronamespace = n.oid \" +\n\t\t\"LEFT JOIN pg_language l ON p.prolang = l.oid \" +\n\t\t\"LEFT JOIN pg_type t ON t.oid = p.prorettype \" +\n\t\t\"WHERE n.nspname NOT IN ('pg_catalog', 'information_schema');\"\n\n\tvar fs []functionSchema\n\trows, err := dp.conn.DB.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar f functionSchema\n\t\tif err := rows.Scan(&f.schemaName, &f.name, &f.language, &f.statement, &f.arguments); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.schemaName, f.name = quoteIdentifier(f.schemaName), quoteIdentifier(f.name)\n\t\tfs = append(fs, f)\n\t}\n\n\treturn fs, nil\n}", "func (p *Parser) AddBuiltInFuncs() {\n\tp.defs.Funcs = append(p.defs.Funcs,\n\t\t&oop.Fn{\n\t\t\tName: \"print\",\n\t\t\tDefaultParamCount: 2,\n\t\t\tSrc: functions.Print,\n\t\t\tParams: []oop.Param{{\n\t\t\t\tName: \"value\",\n\t\t\t\tParams: true,\n\t\t\t\tDefaultVal: oop.Val{Data: \"\", Type: oop.String},\n\t\t\t}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"println\",\n\t\t\tSrc: functions.Println,\n\t\t\tDefaultParamCount: 2,\n\t\t\tParams: []oop.Param{{\n\t\t\t\tName: \"value\",\n\t\t\t\tParams: true,\n\t\t\t\tDefaultVal: oop.Val{Data: oop.NewListModel(oop.Val{Data: \"\", Type: oop.String}), Type: oop.List},\n\t\t\t}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"input\",\n\t\t\tSrc: functions.Input,\n\t\t\tDefaultParamCount: 1,\n\t\t\tParams: []oop.Param{{\n\t\t\t\tName: \"message\",\n\t\t\t\tDefaultVal: oop.Val{Data: \"\", Type: oop.String},\n\t\t\t}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"exit\",\n\t\t\tDefaultParamCount: 1,\n\t\t\tSrc: functions.Exit,\n\t\t\tParams: []oop.Param{{\n\t\t\t\tName: \"code\",\n\t\t\t\tDefaultVal: oop.Val{Data: 0., Type: oop.Int},\n\t\t\t}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"len\",\n\t\t\tSrc: functions.Len,\n\t\t\tDefaultParamCount: 0,\n\t\t\tParams: []oop.Param{{Name: \"object\"}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"range\",\n\t\t\tDefaultParamCount: 1,\n\t\t\tSrc: functions.Range,\n\t\t\tParams: []oop.Param{\n\t\t\t\t{Name: \"start\"},\n\t\t\t\t{Name: \"to\"},\n\t\t\t\t{\n\t\t\t\t\tName: \"step\",\n\t\t\t\t\tDefaultVal: oop.Val{Data: 1., Type: oop.Int},\n\t\t\t\t},\n\t\t\t},\n\t\t}, &oop.Fn{\n\t\t\tName: \"calloc\",\n\t\t\tSrc: functions.Calloc,\n\t\t\tDefaultParamCount: 0,\n\t\t\tParams: []oop.Param{{Name: \"size\"}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"realloc\",\n\t\t\tDefaultParamCount: 0,\n\t\t\tSrc: functions.Realloc,\n\t\t\tParams: []oop.Param{{Name: \"base\"}, {Name: \"size\"}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"string\",\n\t\t\tSrc: functions.String,\n\t\t\tDefaultParamCount: 1,\n\t\t\tParams: []oop.Param{\n\t\t\t\t{Name: \"object\"},\n\t\t\t\t{\n\t\t\t\t\tName: \"type\",\n\t\t\t\t\tDefaultVal: oop.Val{Data: \"parse\", Type: oop.String},\n\t\t\t\t},\n\t\t\t},\n\t\t}, &oop.Fn{\n\t\t\tName: \"int\",\n\t\t\tSrc: functions.Int,\n\t\t\tDefaultParamCount: 1,\n\t\t\tParams: []oop.Param{\n\t\t\t\t{Name: \"object\"},\n\t\t\t\t{\n\t\t\t\t\tName: \"type\",\n\t\t\t\t\tDefaultVal: oop.Val{Data: \"parse\", Type: oop.String},\n\t\t\t\t},\n\t\t\t},\n\t\t}, &oop.Fn{\n\t\t\tName: \"float\",\n\t\t\tSrc: functions.Float,\n\t\t\tDefaultParamCount: 0,\n\t\t\tParams: []oop.Param{{Name: \"object\"}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"panic\",\n\t\t\tSrc: functions.Panic,\n\t\t\tDefaultParamCount: 0,\n\t\t\tParams: []oop.Param{{Name: \"msg\"}},\n\t\t}, &oop.Fn{\n\t\t\tName: \"type\",\n\t\t\tSrc: functions.Type,\n\t\t\tDefaultParamCount: 0,\n\t\t\tParams: []oop.Param{{Name: \"obj\"}},\n\t\t},\n\t)\n}", "func (env *Environment) Functions() []*Function {\n\tfptr := C.EnvGetNextDeffunction(env.env, nil)\n\tret := make([]*Function, 0, 10)\n\tfor fptr != nil {\n\t\tret = append(ret, createFunction(env, fptr))\n\t\tfptr = C.EnvGetNextDeffunction(env.env, fptr)\n\t}\n\treturn ret\n}", "func AddToStandardFunctions(ev *eval.Evaluator) {\n\tl := lexer.New(standardLibrary)\n\tp := parser.New(l)\n\tprogram := p.ParseProgram()\n\tev.Eval(program)\n}", "func getKsyms() ([]string, error) {\n\tf, err := ioutil.ReadFile(\"/proc/kallsyms\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Trim trailing newlines and split by newline\n\tcontent := strings.Split(strings.TrimSuffix(string(f), \"\\n\"), \"\\n\")\n\tout := make([]string, len(content))\n\n\tfor i, l := range content {\n\t\t// Replace any tabs by spaces\n\t\tl = strings.Replace(l, \"\\t\", \" \", -1)\n\n\t\t// Get the third column\n\t\tout[i] = strings.Split(l, \" \")[2]\n\t}\n\n\treturn out, nil\n}", "func builtinsDir() string {\n\treturn filepath.Join(goenv.Get(\"TINYGOROOT\"), \"lib\", \"compiler-rt\", \"lib\", \"builtins\")\n}", "func (v *Service) GetFunctions() (o []*Function) {\n\tif v != nil {\n\t\to = v.Functions\n\t}\n\treturn\n}", "func VerifyKernelFuncs(requiredKernelFuncs ...string) (map[string]struct{}, error) {\n\treturn funcCache.verifyKernelFuncs(requiredKernelFuncs)\n}", "func removeInitFuncs(pkgs []string) {\n\tfor _, pkg := range pkgs {\n\t\tparsedPkgs, _ := parser.ParseDir(token.NewFileSet(), path.Join(PluginFolder, pkg), nil, parser.ParseComments)\n\n\t\tfor _, parsedPkg := range parsedPkgs {\n\t\t\tfor filePath, file := range parsedPkg.Files {\n\t\t\t\tfor _, decl := range file.Decls {\n\t\t\t\t\tswitch decl.(type) {\n\t\t\t\t\tcase *ast.FuncDecl:\n\t\t\t\t\t\tremoveInitFunc(filePath, decl.(*ast.FuncDecl))\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func GetPublicFunctions(pkg, filePath string) ([]*types.Type, error) {\n\tbuilder := go2idlparser.New()\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := builder.AddFile(pkg, filePath, data); err != nil {\n\t\treturn nil, err\n\t}\n\tuniverse, err := builder.FindTypes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar functions []*types.Type\n\n\t// Create the AST by parsing src.\n\tfset := token.NewFileSet() // positions are relative to fset\n\tf, err := parser.ParseFile(fset, filePath, nil, 0)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed parse file to list functions: %v\", err)\n\t}\n\n\t// Inspect the AST and print all identifiers and literals.\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tvar s string\n\t\tswitch x := n.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\ts = x.Name.Name\n\t\t\t// It's a function (not method), and is public, record it.\n\t\t\tif x.Recv == nil && isPublic(s) {\n\t\t\t\tfunctions = append(functions, universe[pkg].Function(x.Name.Name))\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn functions, nil\n}", "func (p *Plugin) GetFuncs() map[string]app.Func {\n\n\treturn map[string]app.Func{\n\n\t\t\"send\": func(c app.Context) (interface{}, error) {\n\n\t\t\tif c.Has(\"message\") == false {\n\t\t\t\treturn nil, errors.New(\"message param required!\")\n\t\t\t}\n\n\t\t\treturn nil, beeep.Notify(\n\t\t\t\tc.GetOr(\"title\", c.App.Name).(string),\n\t\t\t\tc.Get(\"message\").(string),\n\t\t\t\tc.App.Path(\"icon.png\"),\n\t\t\t)\n\t\t},\n\t}\n}", "func CheckStdlib(config *StdlibConfig, analyzers []*analysis.Analyzer) (allFindings FindingSet, facts []byte, err error) {\n\tif len(config.Srcs) == 0 {\n\t\treturn nil, nil, nil\n\t}\n\n\t// Ensure all paths are normalized.\n\tfor i := 0; i < len(config.Srcs); i++ {\n\t\tconfig.Srcs[i] = path.Clean(config.Srcs[i])\n\t}\n\n\t// Calculate the root source directory. This is always a directory\n\t// named 'src', of which we simply take the first we find. This is a\n\t// bit fragile, but works for all currently known Go source\n\t// configurations.\n\t//\n\t// Note that there may be extra files outside of the root source\n\t// directory; we simply ignore those.\n\trootSrcPrefix := \"\"\n\tfor _, file := range config.Srcs {\n\t\tconst src = \"/src/\"\n\t\ti := strings.Index(file, src)\n\t\tif i == -1 {\n\t\t\t// Superfluous file.\n\t\t\tcontinue\n\t\t}\n\n\t\t// Index of first character after /src/.\n\t\ti += len(src)\n\t\trootSrcPrefix = file[:i]\n\t\tbreak\n\t}\n\n\t// Go standard library packages using Go 1.18 type parameter features.\n\t//\n\t// As of writing, analysis tooling is not updated to support type\n\t// parameters and will choke on these packages. We skip these packages\n\t// entirely for now.\n\t//\n\t// TODO(b/201686256): remove once tooling can handle type parameters.\n\tusesTypeParams := map[string]struct{}{\n\t\t\"constraints\": struct{}{}, // golang.org/issue/45458\n\t\t\"maps\": struct{}{}, // golang.org/issue/47649\n\t\t\"slices\": struct{}{}, // golang.org/issue/45955\n\t}\n\n\t// Aggregate all files by directory.\n\tpackages := make(map[string]*PackageConfig)\n\tfor _, file := range config.Srcs {\n\t\tif !strings.HasPrefix(file, rootSrcPrefix) {\n\t\t\t// Superflouous file.\n\t\t\tcontinue\n\t\t}\n\n\t\td := path.Dir(file)\n\t\tif len(rootSrcPrefix) >= len(d) {\n\t\t\tcontinue // Not a file.\n\t\t}\n\t\tpkg := d[len(rootSrcPrefix):]\n\n\t\t// Skip cmd packages and obvious test files: see above.\n\t\tif strings.HasPrefix(pkg, \"cmd/\") || strings.HasSuffix(file, \"_test.go\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := usesTypeParams[pkg]; ok {\n\t\t\tlog.Printf(\"WARNING: Skipping package %q: type param analysis not yet supported\", pkg)\n\t\t\tcontinue\n\t\t}\n\n\t\tc, ok := packages[pkg]\n\t\tif !ok {\n\t\t\tc = &PackageConfig{\n\t\t\t\tImportPath: pkg,\n\t\t\t\tGOOS: config.GOOS,\n\t\t\t\tGOARCH: config.GOARCH,\n\t\t\t\tBuildTags: config.BuildTags,\n\t\t\t\tReleaseTags: config.ReleaseTags,\n\t\t\t}\n\t\t\tpackages[pkg] = c\n\t\t}\n\t\t// Add the files appropriately. Note that they will be further\n\t\t// filtered by architecture and build tags below, so this need\n\t\t// not be done immediately.\n\t\tif strings.HasSuffix(file, \".go\") {\n\t\t\tc.GoFiles = append(c.GoFiles, file)\n\t\t} else {\n\t\t\tc.NonGoFiles = append(c.NonGoFiles, file)\n\t\t}\n\t}\n\n\t// Closure to check a single package.\n\tlocalStdlibFacts := make(stdlibFacts)\n\tlocalStdlibErrs := make(map[string]error)\n\tstdlibCachedFacts.Lookup([]string{\"\"}, func() worker.Sizer {\n\t\treturn localStdlibFacts\n\t})\n\tvar checkOne func(pkg string) error // Recursive.\n\tcheckOne = func(pkg string) error {\n\t\t// Is this already done?\n\t\tif _, ok := localStdlibFacts[pkg]; ok {\n\t\t\treturn nil\n\t\t}\n\t\t// Did this fail previously?\n\t\tif _, ok := localStdlibErrs[pkg]; ok {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Lookup the configuration.\n\t\tconfig, ok := packages[pkg]\n\t\tif !ok {\n\t\t\treturn nil // Not known.\n\t\t}\n\n\t\t// Find the binary package, and provide to objdump.\n\t\trc, err := findStdPkg(config.GOOS, config.GOARCH, pkg)\n\t\tif err != nil {\n\t\t\t// If there's no binary for this package, it is likely\n\t\t\t// not built with the distribution. That's fine, we can\n\t\t\t// just skip analysis.\n\t\t\tlocalStdlibErrs[pkg] = err\n\t\t\treturn nil\n\t\t}\n\n\t\t// Provide the input.\n\t\toldReader := objdump.Reader\n\t\tobjdump.Reader = rc // For analysis.\n\t\tdefer func() {\n\t\t\trc.Close()\n\t\t\tobjdump.Reader = oldReader // Restore.\n\t\t}()\n\n\t\t// Run the analysis.\n\t\tfindings, factData, err := CheckPackage(config, analyzers, checkOne)\n\t\tif err != nil {\n\t\t\t// If we can't analyze a package from the standard library,\n\t\t\t// then we skip it. It will simply not have any findings.\n\t\t\tlocalStdlibErrs[pkg] = err\n\t\t\treturn nil\n\t\t}\n\t\tlocalStdlibFacts[pkg] = factData\n\t\tallFindings = append(allFindings, findings...)\n\t\treturn nil\n\t}\n\n\t// Check all packages.\n\t//\n\t// Note that this may call checkOne recursively, so it's not guaranteed\n\t// to evaluate in the order provided here. We do ensure however, that\n\t// all packages are evaluated.\n\tfor pkg := range packages {\n\t\tif err := checkOne(pkg); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\t// Sanity check.\n\tif len(localStdlibFacts) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"no stdlib facts found: misconfiguration?\")\n\t}\n\n\t// Write out all findings.\n\tbuf := bytes.NewBuffer(nil)\n\tif err := localStdlibFacts.EncodeTo(buf); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error serialized stdlib facts: %v\", err)\n\t}\n\n\t// Write out all errors.\n\tfor pkg, err := range localStdlibErrs {\n\t\tlog.Printf(\"WARNING: error while processing %v: %v\", pkg, err)\n\t}\n\n\t// Return all findings.\n\treturn allFindings, buf.Bytes(), nil\n}", "func GetEventHandlers() []string {\n\thandlers := []string{\n\t\t\"onabort\",\n\t\t\"onactivate\",\n\t\t\"onafterprint\",\n\t\t\"onafterscriptexecute\",\n\t\t\"onafterupdate\",\n\t\t\"onanimationcancel\",\n\t\t\"onanimationstart\",\n\t\t\"onauxclick\",\n\t\t\"onbeforeactivate\",\n\t\t\"onbeforecopy\",\n\t\t\"onbeforecut\",\n\t\t\"onbeforedeactivate\",\n\t\t\"onbeforeeditfocus\",\n\t\t\"onbeforepaste\",\n\t\t\"onbeforeprint\",\n\t\t\"onbeforescriptexecute\",\n\t\t\"onbeforeunload\",\n\t\t\"onbeforeupdate\",\n\t\t\"onbegin\",\n\t\t\"onblur\",\n\t\t\"onbounce\",\n\t\t\"oncanplay\",\n\t\t\"oncanplaythrough\",\n\t\t\"oncellchange\",\n\t\t\"onchange\",\n\t\t\"onclick\",\n\t\t\"oncontextmenu\",\n\t\t\"oncontrolselect\",\n\t\t\"oncopy\",\n\t\t\"oncut\",\n\t\t\"oncuechange\",\n\t\t\"ondataavailable\",\n\t\t\"ondatasetchanged\",\n\t\t\"ondatasetcomplete\",\n\t\t\"ondurationchange\",\n\t\t\"ondblclick\",\n\t\t\"ondeactivate\",\n\t\t\"ondrag\",\n\t\t\"ondragdrop\",\n\t\t\"ondragend\",\n\t\t\"ondragenter\",\n\t\t\"ondragleave\",\n\t\t\"ondragover\",\n\t\t\"ondragstart\",\n\t\t\"ondrop\",\n\t\t\"onend\",\n\t\t\"onerror\",\n\t\t\"onerrorupdate\",\n\t\t\"onfilterchange\",\n\t\t\"onfinish\",\n\t\t\"onfocus\",\n\t\t\"onfocusin\",\n\t\t\"onfocusout\",\n\t\t\"onhashchange\",\n\t\t\"onhelp\",\n\t\t\"oninput\",\n\t\t\"oninvalid\",\n\t\t\"onkeydown\",\n\t\t\"onkeypress\",\n\t\t\"onkeyup\",\n\t\t\"onlayoutcomplete\",\n\t\t\"onload\",\n\t\t\"onloadend\",\n\t\t\"onloadstart\",\n\t\t\"onloadstart\",\n\t\t\"onlosecapture\",\n\t\t\"onmediacomplete\",\n\t\t\"onmediaerror\",\n\t\t\"onmessage\",\n\t\t\"onmousedown\",\n\t\t\"onmouseenter\",\n\t\t\"onmouseleave\",\n\t\t\"onmousemove\",\n\t\t\"onmouseout\",\n\t\t\"onmouseover\",\n\t\t\"onmouseup\",\n\t\t\"onmousewheel\",\n\t\t\"onmove\",\n\t\t\"onmoveend\",\n\t\t\"onmovestart\",\n\t\t\"onoffline\",\n\t\t\"ononline\",\n\t\t\"onoutofsync\",\n\t\t\"onpageshow\",\n\t\t\"onpaste\",\n\t\t\"onpause\",\n\t\t\"onplay\",\n\t\t\"onplaying\",\n\t\t\"onpointerdown\",\n\t\t\"onpointerenter\",\n\t\t\"onpointerleave\",\n\t\t\"onpointermove\",\n\t\t\"onpointerout\",\n\t\t\"onpointerover\",\n\t\t\"onpointerup\",\n\t\t\"onpopstate\",\n\t\t\"onprogress\",\n\t\t\"onpropertychange\",\n\t\t\"onreadystatechange\",\n\t\t\"onredo\",\n\t\t\"onrepeat\",\n\t\t\"onreset\",\n\t\t\"onresize\",\n\t\t\"onresizeend\",\n\t\t\"onresizestart\",\n\t\t\"onresume\",\n\t\t\"onreverse\",\n\t\t\"onrowdelete\",\n\t\t\"onrowexit\",\n\t\t\"onrowinserted\",\n\t\t\"onrowsenter\",\n\t\t\"onrowsdelete\",\n\t\t\"onrowsinserted\",\n\t\t\"onscroll\",\n\t\t\"onsearch\",\n\t\t\"onseek\",\n\t\t\"onselect\",\n\t\t\"onselectionchange\",\n\t\t\"onselectstart\",\n\t\t\"onshow\",\n\t\t\"onstart\",\n\t\t\"onstop\",\n\t\t\"onstorage\",\n\t\t\"onsubmit\",\n\t\t\"onsyncrestored\",\n\t\t\"ontimeerror\",\n\t\t\"ontimeupdate\",\n\t\t\"ontoggle\",\n\t\t\"ontouchend\",\n\t\t\"ontouchmove\",\n\t\t\"ontouchstart\",\n\t\t\"ontrackchange\",\n\t\t\"ontransitionstart\",\n\t\t\"ontransitioncancel\",\n\t\t\"ontransitionend\",\n\t\t\"ontransitionrun\",\n\t\t\"onundo\",\n\t\t\"onunhandledrejection\",\n\t\t\"onunload\",\n\t\t\"onurlflip\",\n\t\t\"onvolumechange\",\n\t\t\"onwaiting\",\n\t\t\"onwebkitanimationiteration\",\n\t\t\"onwheel\",\n\t\t\"whatthe=\\\"'onload\",\n\t\t\"onpointerrawupdate\",\n\t\t\"onpagehide\",\n\t}\n\treturn handlers\n}", "func GetSystemHandlers() map[uint32]RPCHandler {\n\treturn windowsHandlers\n}", "func EnvNS() *EnvFuncs {\n\treturn &EnvFuncs{}\n}", "func FilterFuncs() (filters []func(string) string) {\n\tfilters = append(filters, FilterParenthesis())\n\tfilters = append(filters, FilterHyphens())\n\treturn filters\n}", "func (s *BashScript) Functions() ([]*Function, error) {\n\tfuncs := make([]*Function, 0)\n\n\tfnames, err := s.FunctionNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tannotations, err := s.FunctionAnnotations()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: Make this part shared for all shell types\n\tfor _, fname := range fnames {\n\t\ts.Log.WithFields(logrus.Fields{\n\t\t\t\"func\": fname,\n\t\t}).Debugf(\"building function\")\n\n\t\tf := &Function{\n\t\t\tName: fname,\n\t\t\tOptions: cmd.NewOptionsSet(fname),\n\t\t}\n\n\t\toptions := make(map[string]*cmd.Option, 0)\n\n\t\tfor _, a := range annotations {\n\t\t\tcmdName := a.NamespaceValues[\"cmd\"]\n\t\t\tif cmdName == \"\" || cmdName != f.Name {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ts.Log.WithFields(logrus.Fields{\n\t\t\t\t\"func\": a.NamespaceValues[\"cmd\"],\n\t\t\t\t\"namespace\": a.Namespace,\n\t\t\t\t\"key\": a.Key,\n\t\t\t}).Debugf(\"handling annotation\")\n\n\t\t\tswitch a.Namespace {\n\t\t\tcase config.CommandAnnotationCmdOptionNamespace:\n\t\t\t\tname := a.NamespaceValues[\"option\"]\n\t\t\t\tif name == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif options[name] == nil {\n\t\t\t\t\toptions[name] = &cmd.Option{Type: cmd.StringOption, Name: name}\n\t\t\t\t}\n\t\t\t\tswitch a.Key {\n\t\t\t\tcase \"type\":\n\t\t\t\t\toptions[name].Type = cmd.StringToOptionType(a.Value)\n\t\t\t\tcase \"short\":\n\t\t\t\t\toptions[name].Short = a.Value\n\t\t\t\tcase \"envName\":\n\t\t\t\t\toptions[name].EnvName = a.Value\n\t\t\t\tcase \"default\":\n\t\t\t\t\toptions[name].Default = a.Value\n\t\t\t\tcase \"required\":\n\t\t\t\t\trequired, err := strconv.ParseBool(a.Value)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\toptions[name].Required = required\n\t\t\t\t\t}\n\t\t\t\tcase \"description\":\n\t\t\t\t\toptions[name].Description = a.Value\n\t\t\t\tcase \"hidden\":\n\t\t\t\t\thidden, err := strconv.ParseBool(a.Value)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\toptions[name].Hidden = hidden\n\t\t\t\t\t}\n\t\t\t\tcase \"values\":\n\t\t\t\t\tvalues := make([]cmd.OptionValue, 0)\n\t\t\t\t\tif err := json.Unmarshal([]byte(a.Value), &values); err != nil {\n\t\t\t\t\t\ts.Log.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"option\": name,\n\t\t\t\t\t\t\t\"json\": a.Value,\n\t\t\t\t\t\t}).Warn(\"error parsing json values, \", err.Error())\n\t\t\t\t\t}\n\t\t\t\t\toptions[name].Values = values\n\t\t\t\t}\n\t\t\tcase config.CommandAnnotationCmdNamespace:\n\t\t\t\tswitch a.Key {\n\t\t\t\tcase \"description\":\n\t\t\t\t\tf.Description = a.Value\n\t\t\t\tcase \"help\":\n\t\t\t\t\tf.Help = a.Value\n\t\t\t\tcase \"hidden\":\n\t\t\t\t\thidden, err := strconv.ParseBool(a.Value)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tf.Hidden = hidden\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, v := range options {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\ts.Log.WithFields(logrus.Fields{\n\t\t\t\t\t\"option\": v.Name,\n\t\t\t\t\t\"type\": v.Type,\n\t\t\t\t}).Warn(err.Error())\n\t\t\t} else {\n\t\t\t\tif err := f.Options.Add(v); err != nil {\n\t\t\t\t\ts.Log.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"option\": v.Name,\n\t\t\t\t\t\t\"type\": v.Type,\n\t\t\t\t\t}).Warn(err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfuncs = append(funcs, f)\n\t}\n\n\treturn funcs, nil\n}", "func expFunctions(baseDir string) map[string]function.Function {\n\treturn map[string]function.Function{\n\t\t\"abs\": stdlib.AbsoluteFunc,\n\t\t\"abspath\": funcs.AbsPathFunc,\n\t\t\"basename\": funcs.BasenameFunc,\n\t\t\"base64decode\": funcs.Base64DecodeFunc,\n\t\t\"base64encode\": funcs.Base64EncodeFunc,\n\t\t\"base64gzip\": funcs.Base64GzipFunc,\n\t\t\"base64sha256\": funcs.Base64Sha256Func,\n\t\t\"base64sha512\": funcs.Base64Sha512Func,\n\t\t\"bcrypt\": funcs.BcryptFunc,\n\t\t\"can\": tryfunc.CanFunc,\n\t\t\"ceil\": stdlib.CeilFunc,\n\t\t\"chomp\": stdlib.ChompFunc,\n\t\t\"cidrhost\": funcs.CidrHostFunc,\n\t\t\"cidrnetmask\": funcs.CidrNetmaskFunc,\n\t\t\"cidrsubnet\": funcs.CidrSubnetFunc,\n\t\t\"cidrsubnets\": funcs.CidrSubnetsFunc,\n\t\t\"coalesce\": funcs.CoalesceFunc,\n\t\t\"coalescelist\": stdlib.CoalesceListFunc,\n\t\t\"compact\": stdlib.CompactFunc,\n\t\t\"concat\": stdlib.ConcatFunc,\n\t\t\"contains\": stdlib.ContainsFunc,\n\t\t\"csvdecode\": stdlib.CSVDecodeFunc,\n\t\t\"dirname\": funcs.DirnameFunc,\n\t\t\"distinct\": stdlib.DistinctFunc,\n\t\t\"element\": stdlib.ElementFunc,\n\t\t\"chunklist\": stdlib.ChunklistFunc,\n\t\t\"file\": funcs.MakeFileFunc(baseDir, false),\n\t\t\"fileexists\": funcs.MakeFileExistsFunc(baseDir),\n\t\t\"fileset\": funcs.MakeFileSetFunc(baseDir),\n\t\t\"filebase64\": funcs.MakeFileFunc(baseDir, true),\n\t\t\"filebase64sha256\": funcs.MakeFileBase64Sha256Func(baseDir),\n\t\t\"filebase64sha512\": funcs.MakeFileBase64Sha512Func(baseDir),\n\t\t\"filemd5\": funcs.MakeFileMd5Func(baseDir),\n\t\t\"filesha1\": funcs.MakeFileSha1Func(baseDir),\n\t\t\"filesha256\": funcs.MakeFileSha256Func(baseDir),\n\t\t\"filesha512\": funcs.MakeFileSha512Func(baseDir),\n\t\t\"flatten\": stdlib.FlattenFunc,\n\t\t\"floor\": stdlib.FloorFunc,\n\t\t\"format\": stdlib.FormatFunc,\n\t\t\"formatdate\": stdlib.FormatDateFunc,\n\t\t\"formatlist\": stdlib.FormatListFunc,\n\t\t\"indent\": stdlib.IndentFunc,\n\t\t\"index\": funcs.IndexFunc, // stdlib.IndexFunc is not compatible\n\t\t\"join\": stdlib.JoinFunc,\n\t\t\"jsondecode\": stdlib.JSONDecodeFunc,\n\t\t\"jsonencode\": stdlib.JSONEncodeFunc,\n\t\t\"keys\": stdlib.KeysFunc,\n\t\t\"length\": funcs.LengthFunc,\n\t\t\"list\": funcs.ListFunc,\n\t\t\"log\": stdlib.LogFunc,\n\t\t\"lookup\": funcs.LookupFunc,\n\t\t\"lower\": stdlib.LowerFunc,\n\t\t\"map\": funcs.MapFunc,\n\t\t\"matchkeys\": funcs.MatchkeysFunc,\n\t\t\"max\": stdlib.MaxFunc,\n\t\t\"md5\": funcs.Md5Func,\n\t\t\"merge\": stdlib.MergeFunc,\n\t\t\"min\": stdlib.MinFunc,\n\t\t\"parseint\": stdlib.ParseIntFunc,\n\t\t\"pathexpand\": funcs.PathExpandFunc,\n\t\t\"pow\": stdlib.PowFunc,\n\t\t\"range\": stdlib.RangeFunc,\n\t\t\"regex\": stdlib.RegexFunc,\n\t\t\"regexall\": stdlib.RegexAllFunc,\n\t\t\"replace\": funcs.ReplaceFunc,\n\t\t\"reverse\": stdlib.ReverseListFunc,\n\t\t\"rsadecrypt\": funcs.RsaDecryptFunc,\n\t\t\"setintersection\": stdlib.SetIntersectionFunc,\n\t\t\"setproduct\": stdlib.SetProductFunc,\n\t\t\"setsubtract\": stdlib.SetSubtractFunc,\n\t\t\"setunion\": stdlib.SetUnionFunc,\n\t\t\"sha1\": funcs.Sha1Func,\n\t\t\"sha256\": funcs.Sha256Func,\n\t\t\"sha512\": funcs.Sha512Func,\n\t\t\"signum\": stdlib.SignumFunc,\n\t\t\"slice\": stdlib.SliceFunc,\n\t\t\"sort\": stdlib.SortFunc,\n\t\t\"split\": stdlib.SplitFunc,\n\t\t\"strrev\": stdlib.ReverseFunc,\n\t\t\"substr\": stdlib.SubstrFunc,\n\t\t\"timestamp\": funcs.TimestampFunc,\n\t\t\"timeadd\": stdlib.TimeAddFunc,\n\t\t\"title\": stdlib.TitleFunc,\n\t\t\"tostring\": funcs.MakeToFunc(cty.String),\n\t\t\"tonumber\": funcs.MakeToFunc(cty.Number),\n\t\t\"tobool\": funcs.MakeToFunc(cty.Bool),\n\t\t\"toset\": funcs.MakeToFunc(cty.Set(cty.DynamicPseudoType)),\n\t\t\"tolist\": funcs.MakeToFunc(cty.List(cty.DynamicPseudoType)),\n\t\t\"tomap\": funcs.MakeToFunc(cty.Map(cty.DynamicPseudoType)),\n\t\t\"transpose\": funcs.TransposeFunc,\n\t\t\"trim\": stdlib.TrimFunc,\n\t\t\"trimprefix\": stdlib.TrimPrefixFunc,\n\t\t\"trimspace\": stdlib.TrimSpaceFunc,\n\t\t\"trimsuffix\": stdlib.TrimSuffixFunc,\n\t\t\"try\": tryfunc.TryFunc,\n\t\t\"upper\": stdlib.UpperFunc,\n\t\t\"urlencode\": funcs.URLEncodeFunc,\n\t\t\"uuid\": funcs.UUIDFunc,\n\t\t\"uuidv5\": funcs.UUIDV5Func,\n\t\t\"values\": stdlib.ValuesFunc,\n\t\t\"yamldecode\": yaml.YAMLDecodeFunc,\n\t\t\"yamlencode\": yaml.YAMLEncodeFunc,\n\t\t\"zipmap\": stdlib.ZipmapFunc,\n\t}\n\n}", "func (e *Evaluator) AddStandardFunctions() error {\n\tif err := e.AddFunction(functions.NewFunctionAddDays()); err != nil {\n\t\treturn err\n\t}\n\tif err := e.AddFunction(functions.NewFunctionFormatDate()); err != nil {\n\t\treturn err\n\t}\n\tif err := e.AddFunction(functions.NewFunctionIf()); err != nil {\n\t\treturn err\n\t}\n\tif err := e.AddFunction(functions.NewFunctionNow()); err != nil {\n\t\treturn err\n\t}\n\tif err := e.AddFunction(functions.NewFunctionReplace()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (resource *ResourceType) Functions() []Function {\n\tfunctions := maps.Values(resource.functions)\n\n\tsort.Slice(functions, func(i int, j int) bool {\n\t\treturn functions[i].Name() < functions[j].Name()\n\t})\n\n\treturn functions\n}", "func (r *Router) RegisterStdlib(routes ...StdlibRoute) *Router {\n\tfor _, route := range routes {\n\t\tr.inner.Path(route.Path).\n\t\t\tMethods(route.Method).\n\t\t\tHandlerFunc(route.Handler)\n\t}\n\treturn r\n}", "func GetSortFuncs() map[string]func(*Pullrequest, *Pullrequest) bool {\n\ts := make(map[string]func(*Pullrequest, *Pullrequest) bool)\n\ts[\"repo\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Base.Repo.Name < p2.Base.Repo.Name\n\t}\n\ts[\"name\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Name < p2.Name\n\t}\n\ts[\"requester\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.User.Name < p2.User.Name\n\t}\n\ts[\"assignee\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Assignee.Name < p2.Assignee.Name\n\t}\n\ts[\"from\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Head.Branch < p2.Head.Branch\n\t}\n\ts[\"to\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Base.Branch < p2.Base.Branch\n\t}\n\ts[\"state\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.State < p2.State\n\t}\n\ts[\"created\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.CreatedAt.Before(p2.CreatedAt)\n\t}\n\treturn s\n}", "func (s *BashScript) FunctionNames() ([]string, error) {\n\tcallArgs := []string{\"-c\", fmt.Sprintf(\"set -e; source %s; declare -F\", s.FullPath())}\n\n\tio, buf := io.BufferedCombined()\n\n\terr := NewBash().Run(io, callArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfunctions := []string{}\n\n\tout := buf.String()\n\tfor _, fun := range strings.Split(string(out), \"\\n\") {\n\t\tif fun != \"\" {\n\t\t\tname := strings.Replace(fun, \"declare -f \", \"\", -1)\n\t\t\tfunctions = append(functions, name)\n\t\t}\n\t}\n\n\treturn functions, nil\n}", "func AllCustomFuncs() template.FuncMap {\n\tf := sprig.TxtFuncMap()\n\trt := runtaskFuncs()\n\tfor k, v := range rt {\n\t\tf[k] = v\n\t}\n\trc := runCommandFuncs()\n\tfor k, v := range rc {\n\t\tf[k] = v\n\t}\n\tver := kubever.TemplateFunctions()\n\tfor k, v := range ver {\n\t\tf[k] = v\n\t}\n\tsp := csp.TemplateFunctions()\n\tfor k, v := range sp {\n\t\tf[k] = v\n\t}\n\tps := poolselection.TemplateFunctions()\n\tfor k, v := range ps {\n\t\tf[k] = v\n\t}\n\tur := result.TemplateFunctions()\n\tfor k, v := range ur {\n\t\tf[k] = v\n\t}\n\tnod := node.TemplateFunctions()\n\tfor k, v := range nod {\n\t\tf[k] = v\n\t}\n\n\treturn f\n}", "func getSecretRelatedFuncs(ctx context.Context, logger *zap.Logger, m *metav1.ObjectMeta, fissionClient versioned.Interface) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.CoreV1().Functions(m.Namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, secret := range f.Spec.Secrets {\n\t\t\tif (secret.Name == m.Name) && (secret.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}", "func (parser *Parser) funcsDeclars() ([]*Function, error) {\n\tparser.trace(\"FUNCS DECLARS\")\n\tfunction, err := parser.funcDeclar()\n\t// Empty, is not an error\n\tif err == ErrNoMatch {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfuncs, err := parser.funcsDeclars()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append([]*Function{function}, funcs...), nil\n}", "func (t Type) Functions() []Function {\n\treturn append([]Function{}, t.functions...)\n}", "func AddEnvFuncs(f map[string]interface{}) {\n\tfor k, v := range CreateEnvFuncs(context.Background()) {\n\t\tf[k] = v\n\t}\n}", "func GetAllFunctions() map[string]func(result []mcalc.MandelIterationResult, settings *mcalc.MandelSettings) *image.RGBA {\n\treturn map[string]func(result []mcalc.MandelIterationResult, settings *mcalc.MandelSettings) *image.RGBA{\n\t\t\"grey\": CreateGreyRGBA,\n\t\t\"smooth\": CreateSmoothSimpleRGBA,\n\n\t\t\"retro\": CreateSmoothRetroRGBA,\n\t\t\"plan9\": CreateSmoothPlan9RGBA,\n\t\t\"websafe\": CreateSmoothWebSafeRGBA,\n\t\t\"sgrey\": CreateSmoothGreyRGBA,\n\t\t\"cont\": CreateSmoothContRGBA,\n\t\t\"alternate\": CreateSmoothAlternateRGBA,\n\t\t\"blackwhite\": CreateSmoothBlackWhiteRGBA,\n\t}\n}", "func loadTestFuncs(ptest *build.Package) (*testFuncs, error) {\n\tt := &testFuncs{\n\t\tPackage: ptest,\n\t}\n\tlog.Debugf(\"loadTestFuncs: %v, %v\", ptest.TestGoFiles, ptest.XTestGoFiles)\n\tfor _, file := range ptest.TestGoFiles {\n\t\tif err := t.load(filepath.Join(ptest.Dir, file), \"_test\", &t.ImportTest, &t.NeedTest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfor _, file := range ptest.XTestGoFiles {\n\t\tif err := t.load(filepath.Join(ptest.Dir, file), \"_xtest\", &t.ImportXtest, &t.NeedXtest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn t, nil\n}", "func findFuncs(name string) ([]*FuncExtent, error) {\n\tfset := token.NewFileSet()\n\tparsedFile, err := parser.ParseFile(fset, name, nil, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvisitor := &FuncVisitor{\n\t\tfset: fset,\n\t\tname: name,\n\t\tastFile: parsedFile,\n\t}\n\tast.Walk(visitor, visitor.astFile)\n\treturn visitor.funcs, nil\n}", "func GetGOPATHs() []string {\n\tgopath := os.Getenv(\"GOPATH\")\n\tvar paths []string\n\tif runtime.GOOS == \"windows\" {\n\t\tgopath = strings.Replace(gopath, \"\\\\\", \"/\", -1)\n\t\tpaths = strings.Split(gopath, \";\")\n\t} else {\n\t\tpaths = strings.Split(gopath, \":\")\n\t}\n\treturn paths\n}", "func AllSigStyles() []string {\n\tvar ret []string\n\tfor k := range psExtMap {\n\t\tret = append(ret, k)\n\t}\n\treturn ret\n}", "func NewFunctions() Functions {\n\treturn dynaml.NewFunctions()\n}", "func (app *App) TemplateFuncs(funcs ...template.FuncMap) *App {\n\tapp.templateFuncs = append(app.templateFuncs, funcs...)\n\treturn app\n}", "func (info Terminfo) FuncMap() map[string]string {\n\tr := make(map[string]string, maxFuncs)\n\tr[\"EnterCA\"] = info.Funcs[FuncEnterCA]\n\tr[\"ExitCA\"] = info.Funcs[FuncExitCA]\n\tr[\"ShowCursor\"] = info.Funcs[FuncShowCursor]\n\tr[\"HideCursor\"] = info.Funcs[FuncHideCursor]\n\tr[\"ClearScreen\"] = info.Funcs[FuncClearScreen]\n\tr[\"SGR0\"] = info.Funcs[FuncSGR0]\n\tr[\"Underline\"] = info.Funcs[FuncUnderline]\n\tr[\"Bold\"] = info.Funcs[FuncBold]\n\tr[\"Blink\"] = info.Funcs[FuncBlink]\n\tr[\"Reverse\"] = info.Funcs[FuncReverse]\n\tr[\"EnterKeypad\"] = info.Funcs[FuncEnterKeypad]\n\tr[\"ExitKeypad\"] = info.Funcs[FuncExitKeypad]\n\tr[\"EnterMouse\"] = info.Funcs[FuncEnterMouse]\n\tr[\"ExitMouse\"] = info.Funcs[FuncExitMouse]\n\treturn r\n}", "func GetGeneratedDeepCopyFuncs() []conversion.GeneratedDeepCopyFunc {\n\treturn []conversion.GeneratedDeepCopyFunc{\n\t\t{Fn: DeepCopy__Backend, InType: reflect.TypeOf(&Backend{})},\n\t\t{Fn: DeepCopy__CookieSessionAffinity, InType: reflect.TypeOf(&CookieSessionAffinity{})},\n\t\t{Fn: DeepCopy__Endpoint, InType: reflect.TypeOf(&Endpoint{})},\n\t\t{Fn: DeepCopy__SessionAffinityConfig, InType: reflect.TypeOf(&SessionAffinityConfig{})},\n\t}\n}", "func (c Completer) FunctionNames() []string {\n\tfuncs := []string{}\n\n\tc.scope.Range(func(name string, v values.Value) {\n\t\tif isFunction(v) {\n\t\t\tfuncs = append(funcs, name)\n\t\t}\n\t})\n\n\tsort.Strings(funcs)\n\n\treturn funcs\n}", "func ListFunctions(db *bolt.DB) ([]Function, error) {\n\n\tvar result = make([]Function, 0)\n\n\tdb.View(func(tx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys\n\t\tbucket := tx.Bucket([]byte(ResourceName))\n\n\t\tbucket.ForEach(func(key, value []byte) error {\n\t\t\tfmt.Printf(\"key=%s, value=%s\\n\", key, value)\n\n\t\t\tpersistedFunction := Function{}\n\t\t\tjson.Unmarshal(value, &persistedFunction)\n\n\t\t\tresult = append(result, persistedFunction)\n\t\t\tfmt.Printf(\"result: %v\\n\", result)\n\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t})\n\n\treturn result, nil\n}", "func ListFunctionsForDir(vlog, events metrics.Metrics, dir string, ctx build.Context) (PackageFunctionList, error) {\n\tvar pkgFuncs PackageFunctionList\n\tpkgFuncs.Path = dir\n\tpkgFuncs.Package, _ = srcpath.RelativeToSrc(dir)\n\n\tpkgs, err := ast.FilteredPackageWithBuildCtx(vlog, dir, ctx)\n\tif err != nil {\n\t\tif _, ok := err.(*build.NoGoError); ok {\n\t\t\treturn pkgFuncs, ErrSkipDir\n\t\t}\n\n\t\tevents.Emit(metrics.Error(err), metrics.With(\"dir\", dir))\n\t\treturn pkgFuncs, err\n\t}\n\n\tif len(pkgs) == 0 {\n\t\treturn pkgFuncs, ErrSkipDir\n\t}\n\n\tpkgItem := pkgs[0]\n\tif pkgItem.HasAnnotation(\"@ignore\") {\n\t\treturn pkgFuncs, ErrSkipDir\n\t}\n\n\tpkgHash, err := generateHash(pkgItem.Files)\n\tif err != nil {\n\t\treturn pkgFuncs, err\n\t}\n\n\tbinaryName := pkgItem.Name\n\n\tvar binaryDesc string\n\tif binAnnon, _, ok := pkgItem.AnnotationFirstFor(\"@binaryName\"); ok {\n\t\tbinaryName = binAnnon.Param(\"name\")\n\t\tif binaryName == \"\" {\n\t\t\tbinaryName = pkgItem.Name\n\t\t}\n\n\t\tif desc, ok := binAnnon.Attr(\"desc\").(string); ok {\n\t\t\tif desc != \"\" && !strings.HasSuffix(desc, \".\") {\n\t\t\t\tdesc += \".\"\n\t\t\t\tbinaryDesc = doc.Synopsis(desc)\n\t\t\t}\n\t\t}\n\t}\n\n\tif binaryDesc == \"\" {\n\t\tbinaryDesc = haiku()\n\t}\n\n\tpkgFuncs.Name = binaryName\n\tpkgFuncs.Desc = binaryDesc\n\n\tfns, err := pullFunctions(pkgItem)\n\tif err != nil {\n\t\treturn pkgFuncs, err\n\t}\n\n\tfns.Hash = pkgHash\n\tpkgFuncs.List = append(pkgFuncs.List, fns)\n\n\treturn pkgFuncs, nil\n}", "func (m *Workbook) GetFunctions()(WorkbookFunctionsable) {\n return m.functions\n}", "func SupportedActivationFunctions() []string {\n\treturn activationFunctions\n}", "func GetSupportedLanguages() []string {\n alg_count := int(C.get_num_algorithms());\n out := make([]string, alg_count)\n for x := 0; x < alg_count; x++ {\n out[x] = C.GoString(C.get_algorithm_x(C.int(x)))\n }\n return out\n}", "func generateGoPrimitiveTypesNewFuncs() ([]byte, error) {\n\tb := bytes.NewBufferString(`\nfunc newString(s string) *string {\n\treturn &s\n}\n\nfunc newInt(i int) *int {\n\treturn &i\n}\n\nfunc newFloat(f float64) *float64 {\n\treturn &f\n}\n\nfunc newBool(b bool) *bool {\n\treturn &b\n}\n\t`)\n\n\treturn format.Source(b.Bytes())\n}", "func GetAttributesForFunction(fn *fv1.Function) []attribute.KeyValue {\n\tif fn == nil {\n\t\treturn []attribute.KeyValue{}\n\t}\n\tattrs := []attribute.KeyValue{\n\t\t{Key: \"function-name\", Value: attribute.StringValue(fn.Name)},\n\t\t{Key: \"function-namespace\", Value: attribute.StringValue(fn.Namespace)},\n\t}\n\tif fn.Spec.Environment.Name != \"\" {\n\t\tattrs = append(attrs,\n\t\t\tattribute.KeyValue{Key: \"environment-name\", Value: attribute.StringValue(fn.Spec.Environment.Name)},\n\t\t\tattribute.KeyValue{Key: \"environment-namespace\", Value: attribute.StringValue(fn.Spec.Environment.Namespace)})\n\t}\n\treturn attrs\n}", "func GetReflectNamespaceList(reflectNamespaces string) []string {\n\tif reflectNamespaces == \"\" {\n\t\treturn make([]string, 0)\n\t}\n\n\tnamespaces := strings.Split(reflectNamespaces, \",\")\n\tfor i := range namespaces {\n\t\tnamespaces[i] = strings.TrimSpace(namespaces[i])\n\t}\n\n\treturn namespaces\n}", "func GetGOPATHs() []string {\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath == \"\" && strings.Compare(runtime.Version(), \"go1.8\") >= 0 {\n\t\tgopath = defaultGOPATH()\n\t}\n\treturn filepath.SplitList(gopath)\n}", "func NewFuncs(ctx context.Context, enums []xo.Enum) *Funcs {\n\tdriver, _, _ := xo.DriverSchemaNthParam(ctx)\n\tenumMap := make(map[string]xo.Enum)\n\tif driver == \"mysql\" {\n\t\tfor _, e := range enums {\n\t\t\tenumMap[e.Name] = e\n\t\t}\n\t}\n\treturn &Funcs{\n\t\tdriver: driver,\n\t\tenumMap: enumMap,\n\t\tconstraint: Constraint(ctx),\n\t\tescCols: Esc(ctx, \"columns\"),\n\t\tescTypes: Esc(ctx, \"types\"),\n\t\tengine: Engine(ctx),\n\t}\n}", "func GetInitiators() ([]*xmsv3.Ref, error) {\n\tinitiators, err := xms.GetInitiators()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn initiators.Initiators, nil\n}", "func (lib *Library) GetFunction(symbol string, rtype Type, atypes ...Type) (Function, error) {\n\tsym, err := dlopen.Symbol(lib.lib, symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Wrap(sym, rtype, atypes...)\n}", "func GetAlgorithms() (algs []string) {\n\tsigningMethodLock.RLock()\n\tdefer signingMethodLock.RUnlock()\n\n\tfor alg := range signingMethods {\n\t\talgs = append(algs, alg)\n\t}\n\treturn\n}", "func exportFuncs(wasmExportsMap map[string]js.Func) {\n\n\tfor k, v := range wasmExportsMap {\n\t\tjs.Global().Set(k, v) // set function definition on js 'window' object\n\t}\n}", "func (networkinterface *NetworkInterface) NetworkDeviceFunctions() ([]*NetworkDeviceFunction, error) {\n\treturn ListReferencedNetworkDeviceFunctions(\n\t\tnetworkinterface.GetClient(), networkinterface.networkDeviceFunctions)\n}", "func AddTemplateFuncsNamespace(ns func(d *deps.Deps) *TemplateFuncsNamespace) {\n\tTemplateFuncsNamespaceRegistry = append(TemplateFuncsNamespaceRegistry, ns)\n}", "func Funcs(init Handler, fns []ContractFunctionInterface) map[coretypes.Hname]ContractFunctionInterface {\n\tret := map[coretypes.Hname]ContractFunctionInterface{\n\t\tcoretypes.EntryPointInit: Func(\"init\", init),\n\t}\n\tfor _, f := range fns {\n\t\thname := f.Hname()\n\t\tif _, ok := ret[hname]; ok {\n\t\t\tpanic(fmt.Sprintf(\"Duplicate function: %s\", f.Name))\n\t\t}\n\n\t\thandlers := 0\n\t\tif f.Handler != nil {\n\t\t\thandlers += 1\n\t\t}\n\t\tif f.ViewHandler != nil {\n\t\t\thandlers += 1\n\t\t}\n\t\tif handlers != 1 {\n\t\t\tpanic(\"Exactly one of Handler, ViewHandler must be set\")\n\t\t}\n\n\t\tret[hname] = f\n\t}\n\treturn ret\n}", "func pullFunctionFromDeclr(pkg ast.Package, declr *ast.PackageDeclaration) ([]internals.Function, error) {\n\tvar list []internals.Function\n\n\tfor _, function := range declr.Functions {\n\t\tfn, ignore, err := pullFunction(&function, declr)\n\t\tif err != nil {\n\t\t\treturn list, err\n\t\t}\n\n\t\tif ignore {\n\t\t\tcontinue\n\t\t}\n\n\t\tlist = append(list, fn)\n\t}\n\n\treturn list, nil\n}", "func InitLibs() (*datastore.Client, *storage.BucketHandle) {\n\tVerifyEnvironment()\n\treturn InitDatastore(), InitStorage()\n}", "func generateGoTypesValidateFuncs(idx *jsonschema.Index) ([]byte, error) {\n\tw := bytes.NewBufferString(\"\\n\")\n\tfor _, k := range sortedMapKeysbyName(idx) {\n\t\tt, err := generateGoTypeValidateFunc((*idx)[k], idx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif string(t) != \"\" {\n\t\t\tfmt.Fprintf(w, \"%s\\n\", t)\n\t\t}\n\t}\n\n\treturn format.Source(w.Bytes())\n}", "func getWasmExportables() map[string]js.Func {\n\n\treturn map[string]js.Func{\n\t\t\"evaluate\": evaluator.NewEvaluator().Bind(),\n\t\t// add more funcs here\n\t}\n}", "func init() {\n\taddBuiltinFns(map[string]interface{}{\n\t\t\"run-parallel\": runParallel,\n\t\t// Exception and control\n\t\t\"fail\": fail,\n\t\t\"multi-error\": multiErrorFn,\n\t\t\"return\": returnFn,\n\t\t\"break\": breakFn,\n\t\t\"continue\": continueFn,\n\t\t\"defer\": deferFn,\n\t\t// Iterations.\n\t\t\"each\": each,\n\t\t\"peach\": peach,\n\t})\n}", "func GetFunction(name string, rtype Type, atypes ...Type) (Function, error) {\n\treturn Default.GetFunction(name, rtype, atypes...)\n}", "func (a *Application) GetServicesSupported() []string {\n\tservicesSupported := make([]string, 0, len(a.helpers))\n\tfor key := range a.helpers {\n\t\tservicesSupported = append(servicesSupported, key)\n\t}\n\treturn servicesSupported\n}", "func (info *fileInfo) addFuncPtrDecls() {\n\tgen := &ast.GenDecl{\n\t\tTokPos: info.importCPos,\n\t\tTok: token.VAR,\n\t\tLparen: info.importCPos,\n\t\tRparen: info.importCPos,\n\t}\n\tnames := make([]string, 0, len(info.functions))\n\tfor name := range info.functions {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfor _, name := range names {\n\t\tobj := &ast.Object{\n\t\t\tKind: ast.Typ,\n\t\t\tName: \"C.\" + name + \"$funcaddr\",\n\t\t}\n\t\tvalueSpec := &ast.ValueSpec{\n\t\t\tNames: []*ast.Ident{&ast.Ident{\n\t\t\t\tNamePos: info.importCPos,\n\t\t\t\tName: \"C.\" + name + \"$funcaddr\",\n\t\t\t\tObj: obj,\n\t\t\t}},\n\t\t\tType: &ast.SelectorExpr{\n\t\t\t\tX: &ast.Ident{\n\t\t\t\t\tNamePos: info.importCPos,\n\t\t\t\t\tName: \"unsafe\",\n\t\t\t\t},\n\t\t\t\tSel: &ast.Ident{\n\t\t\t\t\tNamePos: info.importCPos,\n\t\t\t\t\tName: \"Pointer\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tobj.Decl = valueSpec\n\t\tgen.Specs = append(gen.Specs, valueSpec)\n\t}\n\tinfo.Decls = append(info.Decls, gen)\n}", "func TmplFunctionsMap() template.FuncMap {\n\tfuncMap := template.FuncMap{\n\t\t\"envOrDef\": envOrDefault,\n\t\t\"env\": env,\n\t\t\"fileMD5\": fileMD5,\n\t\t\"Iterate\": Iterate,\n\t}\n\treturn funcMap\n}", "func (clcMap ClassLoaderContextMap) UsesLibs() (ulibs []string) {\n\tif clcMap != nil {\n\t\tclcs := clcMap[AnySdkVersion]\n\t\tulibs = make([]string, 0, len(clcs))\n\t\tfor _, clc := range clcs {\n\t\t\tulibs = append(ulibs, clc.Name)\n\t\t}\n\t}\n\treturn ulibs\n}", "func GetFunctionNames(test config.Test, path string) ([]string, error) {\n\tvar methodNames []string\n\n\tfileSet := token.NewFileSet() // positions are relative to fileSet\n\tfile, err := parser.ParseFile(fileSet, path, nil, parser.ParseComments)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate through all function declarations to check if any annotation matches with the\n\t// tests provided in the configuration.yml\n\tfor _, decl := range file.Decls {\n\t\tif fun, ok := decl.(*ast.FuncDecl); ok {\n\t\t\tif fun.Doc != nil && contains(\"@\"+test.Name, fun.Doc.List) {\n\t\t\t\tmethodNames = append(methodNames, fun.Name.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn methodNames, nil\n}", "func RegisteredFunctions(tags ...string) []RegisteredFunction {\n\ttm := map[string]bool{}\n\tfor _, t := range tags {\n\t\ttm[t] = true\n\t}\n\trf := make([]RegisteredFunction, 0, len(supportedVerbs))\n\tfor _, v := range supportedVerbs {\n\t\tif len(tags) == 0 || tm[v.tag] {\n\t\t\trf = append(rf, RegisteredFunction{\n\t\t\t\tFunction: v.String(),\n\t\t\t\tTag: v.tag,\n\t\t\t\tHelp: v.help,\n\t\t\t})\n\t\t}\n\t}\n\tsort.Slice(rf, func(i, j int) bool {\n\t\treturn rf[i].Function < rf[j].Function\n\t})\n\treturn rf\n}", "func (*OneofStdTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OneofStdTypes_OneofMarshaler, _OneofStdTypes_OneofUnmarshaler, _OneofStdTypes_OneofSizer, []interface{}{\n\t\t(*OneofStdTypes_Timestamp)(nil),\n\t\t(*OneofStdTypes_Duration)(nil),\n\t}\n}", "func (*OneofStdTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OneofStdTypes_OneofMarshaler, _OneofStdTypes_OneofUnmarshaler, _OneofStdTypes_OneofSizer, []interface{}{\n\t\t(*OneofStdTypes_Timestamp)(nil),\n\t\t(*OneofStdTypes_Duration)(nil),\n\t}\n}", "func RandomNS() *RandomFuncs {\n\treturn &RandomFuncs{}\n}", "func Factories() []string {\n\tfactorysMu.RLock()\n\tdefer factorysMu.RUnlock()\n\tvar list []string\n\tfor name := range factories {\n\t\tlist = append(list, name)\n\t}\n\tsort.Strings(list)\n\treturn list\n}", "func loadBuiltins(target string) (path string, err error) {\n\t// Try to load a precompiled compiler-rt library.\n\tprecompiledPath := filepath.Join(goenv.Get(\"TINYGOROOT\"), \"pkg\", target, \"compiler-rt.a\")\n\tif _, err := os.Stat(precompiledPath); err == nil {\n\t\t// Found a precompiled compiler-rt for this OS/architecture. Return the\n\t\t// path directly.\n\t\treturn precompiledPath, nil\n\t}\n\n\toutfile := \"librt-\" + target + \".a\"\n\tbuiltinsDir := builtinsDir()\n\n\tbuiltins := builtinFiles(target)\n\tsrcs := make([]string, len(builtins))\n\tfor i, name := range builtins {\n\t\tsrcs[i] = filepath.Join(builtinsDir, name)\n\t}\n\n\tif path, err := cacheLoad(outfile, commands[\"clang\"][0], srcs); path != \"\" || err != nil {\n\t\treturn path, err\n\t}\n\n\tvar cachepath string\n\terr = CompileBuiltins(target, func(path string) error {\n\t\tpath, err := cacheStore(path, outfile, commands[\"clang\"][0], srcs)\n\t\tcachepath = path\n\t\treturn err\n\t})\n\treturn cachepath, err\n}", "func (stdLibrary) ProgramOptions() []ProgramOption {\n\treturn []ProgramOption{\n\t\tFunctions(functions.StandardOverloads()...),\n\t}\n}", "func NewFunctionMap() template.FuncMap {\n\tfuncMap := engine.FuncMap()\n\tfuncMap[\"hashPassword\"] = util.HashPassword\n\tfuncMap[\"removeScheme\"] = util.RemoveScheme\n\treturn funcMap\n}", "func (ls *LState) OpenLibs() {\n\t// NB: Map iteration order in Go is deliberately randomised, so must open Load/Base\n\t// prior to iterating.\n\tfor _, lib := range luaLibs {\n\t\tls.Push(ls.NewFunction(lib.libFunc))\n\t\tls.Push(LString(lib.libName))\n\t\tls.Call(1, 0)\n\t}\n}", "func (p *Generator) GetFuncMap() template.FuncMap {\n\tf := template.FuncMap{\n\t\t\"CreateIntegrationDiagram\": p.CreateIntegrationDiagram,\n\t\t\"CreateSequenceDiagram\": p.CreateSequenceDiagram,\n\t\t\"CreateParamDataModel\": p.CreateParamDataModel,\n\t\t\"CreateReturnDataModel\": p.CreateReturnDataModel,\n\t\t\"CreateTypeDiagram\": p.CreateTypeDiagram,\n\t\t\"CreateRedoc\": p.CreateRedoc,\n\t\t\"GenerateDataModel\": p.GenerateDataModel,\n\t\t\"GetParamType\": p.GetParamType,\n\t\t\"GetReturnType\": p.GetReturnType,\n\t\t\"SourcePath\": p.SourcePath,\n\t\t\"Packages\": p.Packages,\n\t\t\"MacroPackages\": p.MacroPackages,\n\t\t\"hasPattern\": syslutil.HasPattern,\n\t\t\"ModuleAsPackages\": p.ModuleAsPackages,\n\t\t\"ModulePackageName\": ModulePackageName,\n\t\t\"SortedKeys\": SortedKeys,\n\t\t\"Attribute\": Attribute,\n\t\t\"ServiceMetadata\": ServiceMetadata,\n\t\t\"Fields\": Fields,\n\t\t\"FieldType\": FieldType,\n\t\t\"SanitiseOutputName\": SanitiseOutputName,\n\t\t\"ToLower\": strings.ToLower,\n\t\t\"ToCamel\": strcase.ToCamel,\n\t\t\"Remove\": Remove,\n\t\t\"ToTitle\": strings.ToTitle,\n\t\t\"Base\": filepath.Base,\n\t\t\"Last\": Last,\n\t}\n\tfor name, function := range sprig.FuncMap() {\n\t\tf[name] = function\n\t}\n\treturn f\n}", "func loadPosixWinKeyboardCodes() (map[string][]int64, error) {\n\tvar err error\n\n\tlookup := map[string]string{\n\t\t// mac alias\n\t\t\"VKEY_LWIN\": \"0x5B\",\n\n\t\t// no idea where these are defined in chromium code base (assuming in\n\t\t// windows headers)\n\t\t//\n\t\t// manually added here as pulled from various online docs\n\t\t\"VK_CANCEL\": \"0x03\",\n\t\t\"VK_OEM_ATTN\": \"0xF0\",\n\t\t\"VK_OEM_FINISH\": \"0xF1\",\n\t\t\"VK_OEM_COPY\": \"0xF2\",\n\t\t\"VK_DBE_SBCSCHAR\": \"0xF3\",\n\t\t\"VK_DBE_DBCSCHAR\": \"0xF4\",\n\t\t\"VK_OEM_BACKTAB\": \"0xF5\",\n\t\t\"VK_OEM_AX\": \"0xE1\",\n\t}\n\n\t// load windows key lookups\n\tbuf, err := grab(windowsKeyboardCodesH)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatches := defineRE.FindAllStringSubmatch(string(buf), -1)\n\tfor _, m := range matches {\n\t\tlookup[m[1]] = m[2]\n\t}\n\n\t// load posix and win keyboard codes\n\tkeyboardCodeMap := make(map[string][]int64)\n\terr = loadKeyboardCodes(keyboardCodeMap, lookup, keyboardCodesPosixH, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = loadKeyboardCodes(keyboardCodeMap, lookup, keyboardCodesWinH, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn keyboardCodeMap, nil\n}", "func (n *windowNode) extractWindowFunctions(s *renderNode) error {\n\tvisitor := extractWindowFuncsVisitor{\n\t\tn: n,\n\t\taggregatesSeen: make(map[*parser.FuncExpr]struct{}),\n\t}\n\n\toldRenders := s.render\n\toldColumns := s.columns\n\tnewRenders := make([]parser.TypedExpr, 0, len(oldRenders))\n\tnewColumns := make([]ResultColumn, 0, len(oldColumns))\n\tfor i := range oldRenders {\n\t\t// Add all window function applications found in oldRenders[i] to window.funcs.\n\t\ttypedExpr, numFuncsAdded, err := visitor.extract(oldRenders[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif numFuncsAdded == 0 {\n\t\t\t// No window functions in render.\n\t\t\tnewRenders = append(newRenders, oldRenders[i])\n\t\t\tnewColumns = append(newColumns, oldColumns[i])\n\t\t} else {\n\t\t\t// One or more window functions in render. Create a new render in\n\t\t\t// renderNode for each window function argument.\n\t\t\tn.windowRender[i] = typedExpr\n\t\t\tprevWindowCount := len(n.funcs) - numFuncsAdded\n\t\t\tfor i, funcHolder := range n.funcs[prevWindowCount:] {\n\t\t\t\tfuncHolder.funcIdx = prevWindowCount + i\n\t\t\t\tfuncHolder.argIdxStart = len(newRenders)\n\t\t\t\tfor _, argExpr := range funcHolder.args {\n\t\t\t\t\targ := argExpr.(parser.TypedExpr)\n\t\t\t\t\tnewRenders = append(newRenders, arg)\n\t\t\t\t\tnewColumns = append(newColumns, ResultColumn{\n\t\t\t\t\t\tName: arg.String(),\n\t\t\t\t\t\tTyp: arg.ResolvedType(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ts.resetRenderColumns(newRenders, newColumns)\n\treturn nil\n}", "func getVdcVersionedFuncsByVdcVersion(version string) vdcVersionedFuncs {\n\tf, ok := vdcVersionedFuncsByVcdVersion[version]\n\tif ok {\n\t\treturn f\n\t} else {\n\t\treturn vdcVersionedFuncsByVcdVersion[\"default\"]\n\t}\n}", "func (t *TRoot) Funcs(fnList FuncMap) *TRoot {\n\tt.template.Funcs(template.FuncMap(fnList))\n\treturn t\n}", "func Flistx() []string {\n\tmethods := []string{}\n\tfor k, _ := range fmethods {\n\t\tmethods = append(methods, k)\n\t}\n\treturn methods\n}", "func NewStdIOStreams() IOStreams {\n\tsp := spinner.New(spinner.CharSets[24], 100*time.Millisecond)\n\tsp.Writer = os.Stderr\n\n\treturn IOStreams{\n\t\tIn: os.Stdin,\n\t\tOut: os.Stdout,\n\t\tErrOut: os.Stderr,\n\n\t\tsp: sp,\n\t}\n}", "func ProvideFunctionsList(fn Functions) (fl FunctionsList) {\n\n\tfor _, f := range []SampleFunction{\n\t\tSampleFunction(fn.HTTPTransport),\n\t\tSampleFunction(fn.GRPCTransport),\n\t\tSampleFunction(fn.DebugTransport),\n\t\tSampleFunction(fn.PubSubTransport),\n\t\tSampleFunction(fn.InterruptHandler),\n\t} {\n\t\tif f.Enabled {\n\t\t\tfl = append(fl, f)\n\t\t}\n\t}\n\treturn fl\n}", "func ListFunctions(vlog, events metrics.Metrics, targetDir string, ctx build.Context) (FunctionList, error) {\n\tvar list FunctionList\n\tlist.Dir = targetDir\n\tlist.Subs = make(map[string]PackageFunctionList)\n\n\t// Build shogunate directory itself first.\n\tvar err error\n\tlist.Main, err = ListFunctionsForDir(vlog, events, targetDir, ctx)\n\tif err != nil {\n\t\tevents.Emit(metrics.Errorf(\"Failed to generate function list : %+q\", err))\n\t\treturn list, err\n\t}\n\n\tif err = vfiles.WalkDirSurface(targetDir, func(rel string, abs string, info os.FileInfo) error {\n\t\tif !info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tres, err2 := ListFunctionsForDir(vlog, events, abs, ctx)\n\t\tif err2 != nil {\n\t\t\tif err2 == ErrSkipDir {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err2\n\t\t}\n\n\t\tres.RelPath = rel\n\t\tlist.Subs[res.Path] = res\n\t\treturn nil\n\t}); err != nil {\n\t\tevents.Emit(metrics.Error(err), metrics.With(\"dir\", targetDir))\n\t\treturn list, err\n\t}\n\n\treturn list, nil\n}", "func RegisterFunctions(functions Functions) {\n\tfor name, fn := range functions {\n\t\tallFunctions[name] = fn\n\t}\n}", "func checkFuncs(t Type, pkg *Package, log *errlog.ErrorLog) error {\n\t// TODO: Ignore types defined in a different package\n\tswitch t2 := t.(type) {\n\tcase *AliasType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\tfor _, f := range t2.Funcs {\n\t\t\tif err := checkFuncs(f.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := checkFuncBody(f, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif f.DualFunc != nil {\n\t\t\t\tif err := checkFuncs(f.DualFunc.Type, pkg, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := checkFuncBody(f.DualFunc, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn checkFuncs(t2.Alias, pkg, log)\n\tcase *PointerType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.ElementType, pkg, log)\n\tcase *MutableType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.Type, pkg, log)\n\tcase *SliceType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.ElementType, pkg, log)\n\tcase *ArrayType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.ElementType, pkg, log)\n\tcase *StructType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\tif t2.BaseType != nil {\n\t\t\tif err := checkFuncs(t2.BaseType, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, iface := range t2.Interfaces {\n\t\t\tif err := checkFuncs(iface, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, f := range t2.Funcs {\n\t\t\tif err := checkFuncs(f.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := checkFuncBody(f, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif f.DualFunc != nil {\n\t\t\t\tif err := checkFuncs(f.DualFunc.Type, pkg, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := checkFuncBody(f.DualFunc, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase *UnionType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\tfor _, f := range t2.Funcs {\n\t\t\tif err := checkFuncs(f.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := checkFuncBody(f, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif f.DualFunc != nil {\n\t\t\t\tif err := checkFuncs(f.DualFunc.Type, pkg, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := checkFuncBody(f.DualFunc, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase *InterfaceType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\tfor _, b := range t2.BaseTypes {\n\t\t\tif err := checkFuncs(b, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, f := range t2.Funcs {\n\t\t\tif err := checkFuncs(f.FuncType, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase *ClosureType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.FuncType, pkg, log)\n\tcase *GroupedType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\treturn checkFuncs(t2.Type, pkg, log)\n\tcase *FuncType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\t// TODO: Check that target is acceptable\n\t\tfor _, p := range t2.In.Params {\n\t\t\tif err := checkFuncs(p.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, p := range t2.Out.Params {\n\t\t\tif err := checkFuncs(p.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase *GenericInstanceType:\n\t\tif t2.pkg != pkg || t2.TypeBase.funcsChecked || t2.equivalent != nil {\n\t\t\treturn nil\n\t\t}\n\t\tt2.funcsChecked = true\n\t\tif err := checkFuncs(t2.InstanceType, pkg, log); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, f := range t2.Funcs {\n\t\t\tif err := checkFuncs(f.Type, pkg, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpkg.Funcs = append(pkg.Funcs, f)\n\t\t\tif err := checkFuncBody(f, log); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif f.DualFunc != nil {\n\t\t\t\tif err := checkFuncs(f.DualFunc.Type, pkg, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := checkFuncBody(f.DualFunc, log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase *GenericType:\n\t\t// Do nothing\n\t\treturn nil\n\tcase *PrimitiveType:\n\t\t// Do nothing\n\t\treturn nil\n\t}\n\tpanic(\"Wrong\")\n}", "func (p *TProgram) GetTypedefs() []*TTypedef{\n\treturn p.Typedefs_\n}", "func TemplateFunctions() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"kubeVersionCompare\": Compare,\n\t\t\"kubeVersionEq\": Equals,\n\t\t\"kubeVersionGt\": GreaterThan,\n\t\t\"kubeVersionGte\": GreaterThanOrEquals,\n\t\t\"kubeVersionLt\": LessThan,\n\t\t\"kubeVersionLte\": LessThanOrEquals,\n\t}\n}" ]
[ "0.63339674", "0.6039668", "0.53328764", "0.5229742", "0.5211273", "0.52095956", "0.5207862", "0.5121755", "0.50890034", "0.50581", "0.50204414", "0.49949664", "0.4971435", "0.48926392", "0.48742077", "0.48575658", "0.48225898", "0.48183826", "0.48023942", "0.47667244", "0.47637355", "0.46805096", "0.46600932", "0.4642388", "0.46239442", "0.46145087", "0.46034682", "0.4556675", "0.4555425", "0.4539414", "0.45197895", "0.45102623", "0.4434389", "0.44134682", "0.44088018", "0.4407933", "0.43918115", "0.43769085", "0.43735024", "0.43642333", "0.4362787", "0.43336633", "0.43189883", "0.43121898", "0.42962748", "0.42339775", "0.42267543", "0.4222863", "0.42214882", "0.4219506", "0.42173558", "0.41892245", "0.41878408", "0.41820478", "0.41750568", "0.41550153", "0.41541892", "0.41530323", "0.4141342", "0.41403168", "0.41349572", "0.41268623", "0.41193044", "0.41169816", "0.4111578", "0.41075894", "0.41067266", "0.40692168", "0.4065153", "0.4063847", "0.40590617", "0.40428233", "0.403634", "0.40337914", "0.4029193", "0.4026363", "0.4023621", "0.39978778", "0.39884424", "0.3974116", "0.3974116", "0.3959122", "0.3958635", "0.39537033", "0.39503023", "0.39437932", "0.39415827", "0.39409807", "0.39367712", "0.39270276", "0.39262888", "0.3921282", "0.39159214", "0.39044517", "0.39038348", "0.38835058", "0.38829115", "0.3875241", "0.38743147", "0.3871826" ]
0.8931685
0
TODO: update hcl2 library with better diagnostics formatting for streamed configs should be arbitrary labels not JSON should not print diagnostic subject
func formattedDiagnosticErrors(diag hcl.Diagnostics) []error { var errs []error for _, d := range diag { if d.Summary == "Extraneous JSON object property" { d.Summary = "Invalid label" } err := fmt.Errorf("%s: %s", d.Summary, d.Detail) errs = append(errs, err) } return errs }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func livenessprintcfg(lv *Liveness) {\n\tfor _, bb := range lv.cfg {\n\t\tlivenessprintblock(lv, bb)\n\t}\n}", "func sessionConfigurationPayloadDisplay(data *messages.SignalConfigs) {\n\tvar result string = \"\\n\"\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"session-id\", data.MitigatingConfig.SessionId)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"heartbeat-interval\", data.MitigatingConfig.HeartbeatInterval)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"missing-hb-allowed\", data.MitigatingConfig.MissingHbAllowed)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-retransmit\", data.MitigatingConfig.MaxRetransmit)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"ack-timeout\", data.MitigatingConfig.AckTimeout)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"ack-random-factor\", data.MitigatingConfig.AckRandomFactor)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"heartbeat-interval-idle\", data.IdleConfig.HeartbeatInterval)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"missing-hb-allowed-idle\", data.IdleConfig.MissingHbAllowed)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-retransmit-idle\", data.IdleConfig.MaxRetransmit)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"ack-timeout-idle\", data.IdleConfig.AckTimeout)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"ack-random-factor-idle\", data.IdleConfig.AckRandomFactor)\n\tlog.Infoln(result)\n}", "func (engine *ConfigGenerator) Generate(forwarding *logforward.ForwardingSpec) (string, error) {\n\tlogger.DebugObject(\"Generating fluent.conf using %s\", forwarding)\n\t//sanitize here\n\tvar sourceInputLabels []string\n\tvar sourceToPipelineLabels []string\n\tvar pipelineToOutputLabels []string\n\tvar outputLabels []string\n\tvar err error\n\n\tlogTypes, appNs := gatherLogSourceTypes(forwarding.Pipelines)\n\n\tif sourceInputLabels, err = engine.generateSource(logTypes, appNs); err != nil {\n\t\tlogger.Tracef(\"Error generating source blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif sourceToPipelineLabels, err = engine.generateSourceToPipelineLabels(mapSourceTypesToPipelineNames(forwarding.Pipelines)); err != nil {\n\t\tlogger.Tracef(\"Error generating source to pipeline blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tsort.Strings(sourceToPipelineLabels)\n\tif pipelineToOutputLabels, err = engine.generatePipelineToOutputLabels(forwarding.Pipelines); err != nil {\n\t\tlogger.Tracef(\"Error generating pipeline to output labels blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif outputLabels, err = engine.generateOutputLabelBlocks(forwarding.Outputs); err != nil {\n\t\tlogger.Tracef(\"Error generating to output label blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdata := struct {\n\t\tIncludeLegacySecureForward bool\n\t\tIncludeLegacySyslog bool\n\t\tCollectInfraLogs bool\n\t\tCollectAppLogs bool\n\t\tCollectAuditLogs bool\n\t\tSourceInputLabels []string\n\t\tSourceToPipelineLabels []string\n\t\tPipelinesToOutputLabels []string\n\t\tOutputLabels []string\n\t}{\n\t\tengine.includeLegacyForwardConfig,\n\t\tengine.includeLegacySyslogConfig,\n\t\tlogTypes.Has(string(logforward.LogSourceTypeInfra)),\n\t\tlogTypes.Has(string(logforward.LogSourceTypeApp)),\n\t\tlogTypes.Has(string(logforward.LogSourceTypeAudit)),\n\t\tsourceInputLabels,\n\t\tsourceToPipelineLabels,\n\t\tpipelineToOutputLabels,\n\t\toutputLabels,\n\t}\n\tresult, err := engine.Execute(\"fluentConf\", data)\n\tif err != nil {\n\t\tlogger.Tracef(\"Error generating fluentConf\")\n\t\treturn \"\", fmt.Errorf(\"Error processing fluentConf template: %v\", err)\n\t}\n\tlogger.Tracef(\"Successfully generated fluent.conf: %v\", result)\n\treturn result, nil\n}", "func renderOVNFlowsConfig(bootstrapResult *bootstrap.BootstrapResult, data *render.RenderData) {\n\tflows := bootstrapResult.OVN.FlowsConfig\n\tif flows == nil {\n\t\treturn\n\t}\n\tif flows.Target == \"\" {\n\t\tklog.Warningf(\"ovs-flows-config configmap 'target' field can't be empty. Ignoring configuration: %+v\", flows)\n\t\treturn\n\t}\n\t// if IPFIX collectors are provided by means of both the operator configuration and the\n\t// ovs-flows-config ConfigMap, we will merge both targets\n\tif colls, ok := data.Data[\"IPFIXCollectors\"].(string); !ok || colls == \"\" {\n\t\tdata.Data[\"IPFIXCollectors\"] = flows.Target\n\t} else {\n\t\tdata.Data[\"IPFIXCollectors\"] = colls + \",\" + flows.Target\n\t}\n\tif flows.CacheMaxFlows != nil {\n\t\tdata.Data[\"IPFIXCacheMaxFlows\"] = *flows.CacheMaxFlows\n\t}\n\tif flows.Sampling != nil {\n\t\tdata.Data[\"IPFIXSampling\"] = *flows.Sampling\n\t}\n\tif flows.CacheActiveTimeout != nil {\n\t\tdata.Data[\"IPFIXCacheActiveTimeout\"] = *flows.CacheActiveTimeout\n\t}\n}", "func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec {\n\ts := map[string]hcldec.Spec{\n\t\t\"packer_build_name\": &hcldec.AttrSpec{Name: \"packer_build_name\", Type: cty.String, Required: false},\n\t\t\"packer_builder_type\": &hcldec.AttrSpec{Name: \"packer_builder_type\", Type: cty.String, Required: false},\n\t\t\"packer_debug\": &hcldec.AttrSpec{Name: \"packer_debug\", Type: cty.Bool, Required: false},\n\t\t\"packer_force\": &hcldec.AttrSpec{Name: \"packer_force\", Type: cty.Bool, Required: false},\n\t\t\"packer_on_error\": &hcldec.AttrSpec{Name: \"packer_on_error\", Type: cty.String, Required: false},\n\t\t\"packer_user_variables\": &hcldec.BlockAttrsSpec{TypeName: \"packer_user_variables\", ElementType: cty.String, Required: false},\n\t\t\"packer_sensitive_variables\": &hcldec.AttrSpec{Name: \"packer_sensitive_variables\", Type: cty.List(cty.String), Required: false},\n\t\t\"access_key\": &hcldec.AttrSpec{Name: \"access_key\", Type: cty.String, Required: false},\n\t\t\"assume_role\": &hcldec.BlockSpec{TypeName: \"assume_role\", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())},\n\t\t\"custom_endpoint_ec2\": &hcldec.AttrSpec{Name: \"custom_endpoint_ec2\", Type: cty.String, Required: false},\n\t\t\"shared_credentials_file\": &hcldec.AttrSpec{Name: \"shared_credentials_file\", Type: cty.String, Required: false},\n\t\t\"decode_authorization_messages\": &hcldec.AttrSpec{Name: \"decode_authorization_messages\", Type: cty.Bool, Required: false},\n\t\t\"insecure_skip_tls_verify\": &hcldec.AttrSpec{Name: \"insecure_skip_tls_verify\", Type: cty.Bool, Required: false},\n\t\t\"max_retries\": &hcldec.AttrSpec{Name: \"max_retries\", Type: cty.Number, Required: false},\n\t\t\"mfa_code\": &hcldec.AttrSpec{Name: \"mfa_code\", Type: cty.String, Required: false},\n\t\t\"profile\": &hcldec.AttrSpec{Name: \"profile\", Type: cty.String, Required: false},\n\t\t\"region\": &hcldec.AttrSpec{Name: \"region\", Type: cty.String, Required: false},\n\t\t\"secret_key\": &hcldec.AttrSpec{Name: \"secret_key\", Type: cty.String, Required: false},\n\t\t\"skip_region_validation\": &hcldec.AttrSpec{Name: \"skip_region_validation\", Type: cty.Bool, Required: false},\n\t\t\"skip_metadata_api_check\": &hcldec.AttrSpec{Name: \"skip_metadata_api_check\", Type: cty.Bool, Required: false},\n\t\t\"skip_credential_validation\": &hcldec.AttrSpec{Name: \"skip_credential_validation\", Type: cty.Bool, Required: false},\n\t\t\"token\": &hcldec.AttrSpec{Name: \"token\", Type: cty.String, Required: false},\n\t\t\"vault_aws_engine\": &hcldec.BlockSpec{TypeName: \"vault_aws_engine\", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())},\n\t\t\"aws_polling\": &hcldec.BlockSpec{TypeName: \"aws_polling\", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())},\n\t\t\"identifier\": &hcldec.AttrSpec{Name: \"identifier\", Type: cty.String, Required: false},\n\t\t\"keep_releases\": &hcldec.AttrSpec{Name: \"keep_releases\", Type: cty.Number, Required: false},\n\t\t\"keep_days\": &hcldec.AttrSpec{Name: \"keep_days\", Type: cty.Number, Required: false},\n\t\t\"regions\": &hcldec.AttrSpec{Name: \"regions\", Type: cty.List(cty.String), Required: false},\n\t\t\"dry_run\": &hcldec.AttrSpec{Name: \"dry_run\", Type: cty.Bool, Required: false},\n\t}\n\treturn s\n}", "func (cfg *Config) String() string { return fmt.Sprintf(\"%T:%+v\", cfg, *cfg) }", "func ConfigShow() error {\n\n\tfmt.Printf(\"\\nCurrently saved values:\\n\")\n\n\tif Config.Secure {\n\t\tfmt.Printf(\" -https\\n\")\n\t} else {\n\t\tfmt.Printf(\" -http\\n\")\n\t}\n\n\tif Config.Hub != \"\" && Config.Hub != notehub.DefaultAPIService {\n\t\tfmt.Printf(\" -hub %s\\n\", Config.Hub)\n\t}\n\tif Config.App != \"\" {\n\t\tfmt.Printf(\" -app %s\\n\", Config.App)\n\t}\n\tif Config.Product != \"\" {\n\t\tfmt.Printf(\" -product %s\\n\", Config.Product)\n\t}\n\tif Config.Device != \"\" {\n\t\tfmt.Printf(\" -device %s\\n\", Config.Device)\n\t}\n\tif Config.Root != \"\" {\n\t\tfmt.Printf(\" -root %s\\n\", Config.Root)\n\t}\n\tif Config.Cert != \"\" {\n\t\tfmt.Printf(\" -cert %s\\n\", Config.Cert)\n\t}\n\tif Config.Key != \"\" {\n\t\tfmt.Printf(\" -key %s\\n\", Config.Key)\n\t}\n\tif Config.Interface != \"\" {\n\t\tfmt.Printf(\" -interface %s\\n\", Config.Interface)\n\t\tif Config.Port == \"\" {\n\t\t\tfmt.Printf(\" -port -\\n\")\n\t\t\tfmt.Printf(\" -portconfig -\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\" -port %s\\n\", Config.Port)\n\t\t\tfmt.Printf(\" -portconfig %d\\n\", Config.PortConfig)\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func generatePromConfig(buffer map[string][]string) string {\n\tvar extLabel ExtLabels\n\tvar globalLabel = os.Getenv(\"AWS_ACCOUNT\")\n\tvar labelHandle = `monitor: ` + globalLabel\n\tyaml.Unmarshal([]byte(labelHandle), &extLabel)\n\tvar global Global\n\tglobal.ScrapeInterval = \"15s\"\n\tglobal.ExtLabels = extLabel\n\tvar scrapeCollection []ScrapeConfigs\n\tvar baseTargetHandler = `targets: [`\n\tfor key, value := range buffer {\n\t\tvar targetHandler = baseTargetHandler\n\t\tvar statConfig StaticConfigs\n\t\tfor index, ip := range value {\n\t\t\tvar buffer bytes.Buffer\n\t\t\tvar result string\n\t\t\tbuffer.WriteString(\"'\")\n\t\t\tbuffer.WriteString(ip)\n\t\t\tbuffer.WriteString(\":\")\n\t\t\tbuffer.WriteString(_cAdvisorPort)\n\t\t\tbuffer.WriteString(\"'\")\n\t\t\tresult = buffer.String()\n\t\t\ttargetHandler = targetHandler + result\n\t\t\tif index < len(value)-1 {\n\t\t\t\ttargetHandler = targetHandler + \",\"\n\t\t\t} else {\n\t\t\t\ttargetHandler = targetHandler + \"]\"\n\t\t\t}\n\t\t}\n\t\t//Popualte Static config\n\t\tstatErr := yaml.Unmarshal([]byte(targetHandler), &statConfig)\n\t\tcheck(statErr)\n\n\t\tvar scraper ScrapeConfigs\n\t\tscraper.JobName = key\n\t\tscraper.ScrapeInterval = \"10s\"\n\t\tscraper.StaticConfigs = statConfig\n\t\tscrapeCollection = append(scrapeCollection, scraper)\n\n\t\t//Reset our localized staticConfiguration struct for the next iteration\n\t\tstatConfig = StaticConfigs{}\n\t}\n\n\tvar promConfig PrometheusConfig\n\tpromConfig.Global = global\n\tpromConfig.ScrapeConfigs = scrapeCollection\n\n\td, err := yaml.Marshal(&promConfig)\n\tcheckFatal(err)\n\tresp := string(d)\n\treturn resp\n}", "func (scopedWriters *ConfigValueScopedWritersProperty) Label() string {\n\treturn \"Config value writers.\"\n}", "func (r *CheckConfigurationRead) show(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tconfigID, repoID, configName string\n\t\tbucketID, objectID, objectType string\n\t\tcapabilityID, externalID string\n\t\tbucketNULL sql.NullString\n\t\terr error\n\t\tinterval int64\n\t\tisActive, hasInheritance bool\n\t\tisChildrenOnly, isEnabled bool\n\t\tcheckConfig proto.CheckConfig\n\t)\n\n\tif err = r.stmtShow.QueryRow(\n\t\tq.CheckConfig.ID,\n\t).Scan(\n\t\t&configID,\n\t\t&repoID,\n\t\t&bucketNULL,\n\t\t&configName,\n\t\t&objectID,\n\t\t&objectType,\n\t\t&isActive,\n\t\t&hasInheritance,\n\t\t&isChildrenOnly,\n\t\t&capabilityID,\n\t\t&interval,\n\t\t&isEnabled,\n\t\t&externalID,\n\t); err == sql.ErrNoRows {\n\t\tmr.NotFound(err, q.Section)\n\t\treturn\n\t} else if err != nil {\n\t\tgoto fail\n\t}\n\n\tif bucketNULL.Valid {\n\t\tbucketID = bucketNULL.String\n\t}\n\n\tcheckConfig = proto.CheckConfig{\n\t\tID: configID,\n\t\tName: configName,\n\t\tInterval: uint64(interval),\n\t\tRepositoryID: repoID,\n\t\tBucketID: bucketID,\n\t\tCapabilityID: capabilityID,\n\t\tObjectID: objectID,\n\t\tObjectType: objectType,\n\t\tIsActive: isActive,\n\t\tIsEnabled: isEnabled,\n\t\tInheritance: hasInheritance,\n\t\tChildrenOnly: isChildrenOnly,\n\t\tExternalID: externalID,\n\t}\n\n\t// retrieve check configuration thresholds\n\tif err = r.thresholds(&checkConfig); err != nil {\n\t\tgoto fail\n\t}\n\n\tif err = r.constraints(&checkConfig); err != nil {\n\t\tgoto fail\n\t}\n\n\tif err = r.instances(&checkConfig); err != nil {\n\t\tgoto fail\n\t}\n\n\tmr.CheckConfig = append(mr.CheckConfig, checkConfig)\n\tmr.OK()\n\treturn\n\nfail:\n\tmr.ServerError(err, q.Section)\n}", "func (lis Config) String() string {\n\tattLen := 0\n\ttagLen := 0\n\n\tfor _, o := range lis {\n\t\tfor _, v := range o.List {\n\t\t\tl := len(v.Name)\n\t\t\tif attLen <= l {\n\t\t\t\tattLen = l\n\t\t\t}\n\n\t\t\tt := len(strings.Join(v.Tags, \" \"))\n\t\t\tif tagLen <= t {\n\t\t\t\ttagLen = t\n\t\t\t}\n\t\t}\n\t}\n\n\tvar buf strings.Builder\n\tfor _, o := range lis {\n\t\tif len(o.Notes) > 0 {\n\t\t\tbuf.WriteString(\"# \")\n\t\t\tbuf.WriteString(strings.Join(o.Notes, \"\\n# \"))\n\t\t\tbuf.WriteRune('\\n')\n\t\t}\n\n\t\tbuf.WriteString(\"@\")\n\t\tbuf.WriteString(o.Space)\n\t\tif len(o.Tags) > 0 {\n\t\t\tbuf.WriteRune(' ')\n\t\t\tbuf.WriteString(strings.Join(o.Tags, \" \"))\n\t\t}\n\t\tbuf.WriteRune('\\n')\n\n\t\tfor _, v := range o.List {\n\t\t\tif len(v.Notes) > 0 {\n\t\t\t\tbuf.WriteString(\"# \")\n\t\t\t\tbuf.WriteString(strings.Join(v.Notes, \"\\n# \"))\n\t\t\t\tbuf.WriteString(\"\\n\")\n\t\t\t}\n\n\t\t\tbuf.WriteString(v.Name)\n\t\t\tbuf.WriteString(strings.Repeat(\" \", attLen-len(v.Name)+1))\n\n\t\t\tif len(v.Tags) > 0 {\n\t\t\t\tt := strings.Join(v.Tags, \" \")\n\t\t\t\tbuf.WriteString(t)\n\t\t\t\tbuf.WriteString(strings.Repeat(\" \", tagLen-len(t)+1))\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(strings.Repeat(\" \", tagLen+1))\n\t\t\t}\n\n\t\t\tswitch len(v.Values) {\n\t\t\tcase 0:\n\t\t\t\tbuf.WriteString(\"\\n\")\n\t\t\tcase 1:\n\t\t\t\tbuf.WriteString(\" :\")\n\t\t\t\tbuf.WriteString(v.Values[0])\n\t\t\t\tbuf.WriteString(\"\\n\")\n\t\t\tdefault:\n\t\t\t\tbuf.WriteString(\" :\")\n\t\t\t\tbuf.WriteString(v.Values[0])\n\t\t\t\tbuf.WriteString(\"\\n\")\n\t\t\t\tfor _, s := range v.Values[1:] {\n\t\t\t\t\tbuf.WriteString(strings.Repeat(\" \", attLen+tagLen+3))\n\t\t\t\t\tbuf.WriteString(\":\")\n\t\t\t\t\tbuf.WriteString(s)\n\t\t\t\t\tbuf.WriteString(\"\\n\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbuf.WriteRune('\\n')\n\t}\n\n\treturn buf.String()\n}", "func (engine *ConfigGenerator) generateOutputLabelBlocks(outputs []logforward.OutputSpec) ([]string, error) {\n\tconfigs := []string{}\n\tlogger.Debugf(\"Evaluating %v forwarding outputs...\", len(outputs))\n\tfor _, output := range outputs {\n\t\tlogger.Debugf(\"Generate output type %v\", output.Type)\n\t\toutputTemplateName := \"outputLabelConf\"\n\t\tvar storeTemplateName string\n\t\tswitch output.Type {\n\t\tcase logforward.OutputTypeElasticsearch:\n\t\t\tstoreTemplateName = \"storeElasticsearch\"\n\t\tcase logforward.OutputTypeForward:\n\t\t\tstoreTemplateName = \"forward\"\n\t\t\toutputTemplateName = \"outputLabelConfNoCopy\"\n\t\tcase logforward.OutputTypeSyslog:\n\t\t\tif engine.useOldRemoteSyslogPlugin {\n\t\t\t\tstoreTemplateName = \"storeSyslogOld\"\n\t\t\t} else {\n\t\t\t\tstoreTemplateName = \"storeSyslog\"\n\t\t\t}\n\t\t\toutputTemplateName = \"outputLabelConfNoRetry\"\n\t\tdefault:\n\t\t\tlogger.Warnf(\"Pipeline targets include an unrecognized type: %q\", output.Type)\n\t\t\tcontinue\n\t\t}\n\t\tconf := newOutputLabelConf(engine.Template, storeTemplateName, output)\n\t\tresult, err := engine.Execute(outputTemplateName, conf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error generating fluentd config Processing template outputLabelConf: %v\", err)\n\t\t}\n\t\tconfigs = append(configs, result)\n\t}\n\tlogger.Debugf(\"Generated output configurations: %v\", configs)\n\treturn configs, nil\n}", "func (*SinkConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_stat_sinks_open_telemetry_v3_open_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (d *HephyCmd) ConfigList(appID string, format string) error {\n\ts, appID, err := load(d.ConfigFile, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig, err := config.List(s.Client, appID)\n\tif d.checkAPICompatibility(s.Client, err) != nil {\n\t\treturn err\n\t}\n\n\tkeys := sortKeys(config.Values)\n\n\tvar configOutput *bytes.Buffer = new(bytes.Buffer)\n\n\tswitch format {\n\tcase \"oneline\":\n\t\tfor i, key := range keys {\n\t\t\tsep := \" \"\n\t\t\tif i == len(keys)-1 {\n\t\t\t\tsep = \"\\n\"\n\t\t\t}\n\t\t\tfmt.Fprintf(configOutput, \"%s=%s%s\", key, config.Values[key], sep)\n\t\t}\n\tcase \"diff\":\n\t\tfor _, key := range keys {\n\t\t\tfmt.Fprintf(configOutput, \"%s=%s\\n\", key, config.Values[key])\n\t\t}\n\tdefault:\n\t\tfmt.Fprintf(configOutput, \"=== %s Config\\n\", appID)\n\n\t\tconfigMap := make(map[string]string)\n\n\t\t// config.Values is type interface, so it needs to be converted to a string\n\t\tfor _, key := range keys {\n\t\t\tconfigMap[key] = fmt.Sprintf(\"%v\", config.Values[key])\n\t\t}\n\n\t\tfmt.Fprint(configOutput, prettyprint.PrettyTabs(configMap, 6))\n\t}\n\n\td.Print(configOutput)\n\treturn nil\n}", "func (tc *TrackedContainer) parseLabelsAsConfig() {\n\trex, err := regexp.Compile(\"^\" + regexp.QuoteMeta(\"telegraf.sd.config.\") + \"(.+)$\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor label, value := range tc.Container.Labels {\n\t\tmatches := rex.FindAllStringSubmatch(label, -1)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tshortName := matches[0][1]\n\t\ttc.Config[shortName] = value\n\t}\n}", "func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }", "func (d *dexterOIDChttp) showK8sConfig(w http.ResponseWriter, token *oauth2.Token) error {\n\tidToken := token.Extra(\"id_token\").(string)\n\n\tparsed, err := jwt.ParseSigned(idToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse token: %s\", err)\n\t}\n\n\tcustomClaim := &customClaim{}\n\tclaims := &jwt.Claims{}\n\n\terr = parsed.UnsafeClaimsWithoutVerification(claims, customClaim)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get user details from token: %s\", err)\n\t}\n\n\t// Use e-mail claim if configuration wasn't discovered in kubeconfig\n\tauthName := customClaim.Email\n\tif d.authName != \"\" {\n\t\tauthName = d.authName\n\t}\n\n\t// construct the authinfo struct\n\tauthInfo := &clientCmdApi.AuthInfo{\n\t\tAuthProvider: &clientCmdApi.AuthProviderConfig{\n\t\t\tName: \"oidc\",\n\t\t\tConfig: map[string]string{\n\t\t\t\t\"client-id\": d.clientID,\n\t\t\t\t\"client-secret\": d.clientSecret,\n\t\t\t\t\"id-token\": idToken,\n\t\t\t\t\"idp-issuer-url\": claims.Issuer,\n\t\t\t\t\"refresh-token\": token.RefreshToken,\n\t\t\t},\n\t\t},\n\t}\n\n\t// contruct the config snippet\n\tconfig := &clientCmdApi.Config{\n\t\tAuthInfos: map[string]*clientCmdApi.AuthInfo{authName: authInfo},\n\t}\n\n\tif d.kubeConfig != \"\" {\n\t\t// write the config\n\t\ttempKubeConfig, err := ioutil.TempFile(\"\", \"\")\n\t\tdefer os.Remove(tempKubeConfig.Name())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create tempfile: %s\", err)\n\t\t}\n\n\t\t// write snipped to temporary file\n\t\tclientcmd.WriteToFile(*config, tempKubeConfig.Name())\n\n\t\t// setup the order for the file load\n\t\tloadingRules := clientcmd.ClientConfigLoadingRules{\n\t\t\tPrecedence: []string{tempKubeConfig.Name(), d.kubeConfig},\n\t\t}\n\n\t\t// merge the configs\n\t\tconfig, err = loadingRules.Load()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge configurations: %s\", err)\n\t\t}\n\t}\n\n\t// create a JSON representation\n\tjson, err := k8sRuntime.Encode(clientCmdLatest.Codec, config)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to runtime encode config: %s\", err)\n\t}\n\n\tdata := strings.Replace(string(json), \"your-email\", authName, -1)\n\n\t// convert JSON to YAML\n\toutput, err := yaml.JSONToYAML([]byte(data))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert JSON to YAML: %s\", err)\n\t}\n\n\t// show the result\n\t//log.Infof(\"Here's the config snippet that would be merged with your config: \\n%v\", string(output))\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(output))\n\n\treturn nil\n}", "func (e *Engine) display(m *nats.Msg) {\n\tsubjectSize := len(m.Subject)\n\tif subjectSize > e.longestSubSize {\n\t\te.longestSubSize = subjectSize\n\t}\n\tpaddingSize := e.longestSubSize - subjectSize\n\tpadding := strings.Repeat(\" \", paddingSize)\n\n\tvar text string\n\tswitch e.format {\n\tcase \"docker-logs\":\n\t\t// Use colorized Docker logging output format\n\t\tl := make(map[string]interface{})\n\t\terr := json.Unmarshal(m.Data, &l)\n\t\tif err != nil {\n\t\t\ttext = fmt.Sprintf(\"%s%s | %s\\n\", m.Subject, padding, err)\n\t\t\treturn\n\t\t}\n\n\t\tif e.showTimestamp {\n\t\t\ttext = fmt.Sprintf(\"%s%s | %-30s -- %s\\n\", hashColor(m.Subject), padding, l[\"time\"], l[\"text\"])\n\t\t} else {\n\t\t\ttext = fmt.Sprintf(\"%s%s | %s\\n\", hashColor(m.Subject), padding, l[\"text\"])\n\t\t}\n\tcase \"raw\":\n\t\ttext = fmt.Sprintf(\"%s%s | %s\\n\", hashColor(m.Subject), padding, string(m.Data))\n\tdefault:\n\t\t// Unsupported format\n\t\tlog.Fatalf(\"Unsupported output format\")\n\t}\n\n\tlog.Printf(text)\n\n\treturn\n}", "func (c config) Verbosity() int { return c.verbose }", "func (e EvalConfig) String() string {\n\tvar b bytes.Buffer\n\tif e.Scheduler != nil {\n\t\tfmt.Fprintf(&b, \"scheduler %T\", e.Scheduler)\n\t}\n\tif e.Snapshotter != nil {\n\t\tfmt.Fprintf(&b, \" snapshotter %T\", e.Snapshotter)\n\t}\n\tif e.Repository != nil {\n\t\trepo := fmt.Sprintf(\"%T\", e.Repository)\n\t\tif u := e.Repository.URL(); u != nil {\n\t\t\trepo += fmt.Sprintf(\",url=%s\", u)\n\t\t}\n\t\tfmt.Fprintf(&b, \" repository %s\", repo)\n\t}\n\tif e.Assoc != nil {\n\t\tfmt.Fprintf(&b, \" assoc %s\", e.Assoc)\n\t}\n\tif e.Predictor != nil {\n\t\tfmt.Fprintf(&b, \" predictor %T\", e.Predictor)\n\t}\n\n\tvar flags []string\n\tif e.CacheMode == infra2.CacheOff {\n\t\tflags = append(flags, \"nocache\")\n\t} else {\n\t\tif e.CacheMode.Reading() {\n\t\t\tflags = append(flags, \"cacheread\")\n\t\t}\n\t\tif e.CacheMode.Writing() {\n\t\t\tflags = append(flags, \"cachewrite\")\n\t\t}\n\t}\n\tif e.RecomputeEmpty {\n\t\tflags = append(flags, \"recomputeempty\")\n\t} else {\n\t\tflags = append(flags, \"norecomputeempty\")\n\t}\n\tif e.BottomUp {\n\t\tflags = append(flags, \"bottomup\")\n\t} else {\n\t\tflags = append(flags, \"topdown\")\n\t}\n\tif e.PostUseChecksum {\n\t\tflags = append(flags, \"postusechecksum\")\n\t}\n\tfmt.Fprintf(&b, \" flags %s\", strings.Join(flags, \",\"))\n\tfmt.Fprintf(&b, \" flowconfig %s\", e.Config)\n\tfmt.Fprintf(&b, \" cachelookuptimeout %s\", e.CacheLookupTimeout)\n\tfmt.Fprintf(&b, \" imagemap %v\", e.ImageMap)\n\tif e.DotWriter != nil {\n\t\tfmt.Fprintf(&b, \" dotwriter(%T)\", e.DotWriter)\n\t}\n\treturn b.String()\n}", "func printConfig(ctx context.BenchCtx, tarantoolConnection *tarantool.Connection) {\n\tfmt.Printf(\"%s\\n\", tarantoolConnection.Greeting().Version)\n\tfmt.Printf(\"Parameters:\\n\")\n\tfmt.Printf(\"\\tURL: %s\\n\", ctx.URL)\n\tfmt.Printf(\"\\tuser: %s\\n\", ctx.User)\n\tfmt.Printf(\"\\tconnections: %d\\n\", ctx.Connections)\n\tfmt.Printf(\"\\tsimultaneous requests: %d\\n\", ctx.SimultaneousRequests)\n\tfmt.Printf(\"\\tduration: %d seconds\\n\", ctx.Duration)\n\tfmt.Printf(\"\\tkey size: %d bytes\\n\", ctx.KeySize)\n\tfmt.Printf(\"\\tdata size: %d bytes\\n\", ctx.DataSize)\n\tfmt.Printf(\"\\tinsert: %d percentages\\n\", ctx.InsertCount)\n\tfmt.Printf(\"\\tselect: %d percentages\\n\", ctx.SelectCount)\n\tfmt.Printf(\"\\tupdate: %d percentages\\n\\n\", ctx.UpdateCount)\n\n\tfmt.Printf(\"Data schema\\n\")\n\tw := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)\n\tfmt.Fprintf(w, \"|\\tkey\\t|\\tvalue\\n\")\n\tfmt.Fprintf(w, \"|\\t------------------------------\\t|\\t------------------------------\\n\")\n\tfmt.Fprintf(w, \"|\\trandom(%d)\\t|\\trandom(%d)\\n\", ctx.KeySize, ctx.DataSize)\n\tw.Flush()\n}", "func (*Config) Descriptor() ([]byte, []int) {\n\treturn file_app_log_config_proto_rawDescGZIP(), []int{1}\n}", "func (nsac KubeNodeCollector) Describe(ch chan<- *prometheus.Desc) {\n\tdisabledMetrics := nsac.metricsConfig.GetDisabledMetricsMap()\n\n\tif _, disabled := disabledMetrics[\"kube_node_status_capacity\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_capacity\", \"Node resource capacity.\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_capacity_memory_bytes\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_capacity_memory_bytes\", \"node capacity memory bytes\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_capacity_cpu_cores\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_capacity_cpu_cores\", \"node capacity cpu cores\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_allocatable\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_allocatable\", \"The allocatable for different resources of a node that are available for scheduling.\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_allocatable_cpu_cores\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_allocatable_cpu_cores\", \"The allocatable cpu cores.\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_allocatable_memory_bytes\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_allocatable_memory_bytes\", \"The allocatable memory in bytes.\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_labels\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_labels\", \"all labels for each node prefixed with label_\", []string{}, nil)\n\t}\n\tif _, disabled := disabledMetrics[\"kube_node_status_condition\"]; !disabled {\n\t\tch <- prometheus.NewDesc(\"kube_node_status_condition\", \"The condition of a cluster node.\", []string{}, nil)\n\t}\n}", "func logConfig(myid int, myConf *Config) {\n\tvar conf MyConfig\n\tfile, _ := os.Open(\"config/log_config.json\")\n\tdecoder := json.NewDecoder(file)\n\terr := decoder.Decode(&conf)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\n\tfoundMyId := false\n\t//initializing config structure from jason file.\n\tfor _, srv := range conf.Details {\n\t\tif srv.Id == myid {\n\t\t\tfoundMyId = true\n\t\t\tmyConf.Id = myid\n\t\t\tmyConf.LogDir = srv.LogDir\n\t\t\tmyConf.ElectionTimeout = srv.ElectionTimeout\n\t\t\tmyConf.HeartbeatTimeout = srv.HeartbeatTimeout\n\t\t}\n\t}\n\tif !foundMyId {\n\t\tfmt.Println(\"Expected this server's id (\\\"%d\\\") to be present in the configuration\", myid)\n\t}\n}", "func parseConfig(verbose int) {\n\n\tconfigFilePath = os.Getenv(\"ALERT_CONFIG_PATH\") // ALERT_CONFIG_PATH Environment Variable storing config filepath.\n\tdefaultConfigFilePath := os.Getenv(\"HOME\") + \"/.alertconfig.json\"\n\n\t//Defaults in case no config file is provided\n\tconfigJSON.CMSMONURL = \"https://cms-monitoring.cern.ch/alertmanager\"\n\tconfigJSON.Names = []string{\"NAMES\", \"LABELS\", \"ANNOTATIONS\"}\n\tconfigJSON.Columns = []string{\"NAME\", \"SERVICE\", \"TAG\", \"SEVERITY\", \"STARTS\", \"ENDS\", \"DURATION\"}\n\tconfigJSON.Attributes = []string{\"service\", \"tag\", \"severity\"}\n\tconfigJSON.Verbose = verbose\n\tconfigJSON.SeverityLevels = make(map[string]int)\n\tconfigJSON.SeverityLevels[\"info\"] = 0\n\tconfigJSON.SeverityLevels[\"warning\"] = 1\n\tconfigJSON.SeverityLevels[\"medium\"] = 2\n\tconfigJSON.SeverityLevels[\"high\"] = 3\n\tconfigJSON.SeverityLevels[\"critical\"] = 4\n\tconfigJSON.SeverityLevels[\"urgent\"] = 5\n\tconfigJSON.httpTimeout = 3 // 3 seconds timeout for http\n\n\tif *generateConfig {\n\t\tconfig, err := json.MarshalIndent(configJSON, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Default Config Value can't be parsed from configJSON struct, error: %s\", err)\n\t\t}\n\t\tfilePath := defaultConfigFilePath\n\t\tif len(flag.Args()) > 0 {\n\t\t\tfilePath = flag.Args()[0]\n\t\t}\n\n\t\terr = os.WriteFile(filePath, config, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to generate Config File, error: %s\", err)\n\t\t}\n\t\tfmt.Printf(\"A new configuration file %s was generated.\\n\", filePath)\n\t\treturn\n\t}\n\n\tif configFilePath != \"\" {\n\t\topenConfigFile(configFilePath)\n\t} else if defaultConfigFilePath != \"\" {\n\t\topenConfigFile(defaultConfigFilePath)\n\t}\n\n\t// we we were given verbose from command line we should overwrite its value in config\n\tif verbose > 0 {\n\t\tconfigJSON.Verbose = verbose\n\t}\n\n\tif configJSON.Verbose > 0 {\n\t\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\t} else {\n\t\tlog.SetFlags(log.LstdFlags)\n\t}\n\n\t// if we were given the token we will use it\n\tif token != \"\" {\n\t\tconfigJSON.Token = token\n\t}\n\tif configJSON.Verbose > 1 {\n\t\tlog.Printf(\"Configuration:\\n%+v\\n\", configJSON)\n\t}\n}", "func (*CommonExtensionConfig_TapDSConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_common_tap_v2alpha_common_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*SharedSentryConfig) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_protos_mconfig_mconfigs_proto_rawDescGZIP(), []int{1}\n}", "func (s HlsConfiguration) GoString() string {\n\treturn s.String()\n}", "func (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tc.config.getAllDescs(ch)\n}", "func (c Configs) Diagnostics() (*diagnostics.Diagnostics, error) {\n\td := &diagnostics.Diagnostics{\n\t\tColumns: []string{\"enabled\", \"bind-address\", \"database\", \"retention-policy\", \"batch-size\", \"batch-pending\", \"batch-timeout\"},\n\t}\n\n\tfor _, cc := range c {\n\t\tif !cc.Enabled {\n\t\t\td.AddRow([]interface{}{false})\n\t\t\tcontinue\n\t\t}\n\n\t\tr := []interface{}{true, cc.BindAddress, cc.Database, cc.RetentionPolicy, cc.BatchSize, cc.BatchPending, cc.BatchTimeout}\n\t\td.AddRow(r)\n\t}\n\n\treturn d, nil\n}", "func detailPrint() {\n\n\tif alert, ok := alertDetails[name]; ok {\n\t\tlabelsKeys := getkeys(alertDetails[name].Labels)\n\t\tsort.Strings(labelsKeys)\n\n\t\tfor _, each := range labelsKeys {\n\t\t\tswitch {\n\t\t\tcase detailPrintHelper(each, []string{\"alertname\"}):\n\t\t\t\tfmt.Printf(\"%s: %s\\n\", configJSON.Names[0], alertDetails[name].Labels[each])\n\t\t\t\tfmt.Printf(\"%s\\n\", configJSON.Names[1])\n\t\t\tcase detailPrintHelper(each, configJSON.Attributes):\n\t\t\t\tfmt.Printf(\"\\t%s: %s\\n\", each, alertDetails[name].Labels[each])\n\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"%s\\n\", configJSON.Names[2])\n\t\tfor key, value := range alert.Annotations {\n\t\t\tfmt.Printf(\"\\t%s: %s\\n\", key, value)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s alert not found\\n\", name)\n\t}\n\n}", "func printEndpointLabels(lbls *labels.OpLabels) {\n\tlog.WithField(logfields.Labels, logfields.Repr(*lbls)).Debug(\"All Labels\")\n\tw := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0)\n\n\tfor _, v := range lbls.IdentityLabels() {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\n\", v, \"Enabled\")\n\t}\n\n\tfor _, v := range lbls.Disabled {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\n\", v, \"Disabled\")\n\t}\n\tw.Flush()\n}", "func (*SqlServerAuditConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{31}\n}", "func (c *SecurityGroupCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Defined\n\tch <- c.EnableDefault\n\tch <- c.ProjectDefault\n\tch <- c.Stateful\n\tch <- c.InboundDefault\n\tch <- c.OutboundDefault\n\tch <- c.Servers\n\tch <- c.Created\n\tch <- c.Modified\n}", "func (*OpenCensusConfig) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{0}\n}", "func (val *ConfigValueProperty) Label() string {\n\treturn \"Configuration content\"\n}", "func (*HealthPingConfig) Descriptor() ([]byte, []int) {\n\treturn file_app_observatory_burst_config_proto_rawDescGZIP(), []int{1}\n}", "func printConfig() error {\n\n\t//读取配置\n\tabsFile := filepath.Join(configFilePath, configFileName)\n\tc, err := config.NewConfig(\"json\", absFile)\n\tif err != nil {\n\t\treturn errors.New(\"config file not create,please run: wmd config -s <symbol> \")\n\t}\n\n\tapiURL := c.String(\"apiURL\")\n\twalletPath := c.String(\"walletPath\")\n\tthreshold := c.String(\"threshold\")\n\t//minSendAmount := c.String(\"minSendAmount\")\n\t//minFees := c.String(\"minFees\")\n\tsumAddress := c.String(\"sumAddress\")\n\n\tfmt.Printf(\"-----------------------------------------------------------\\n\")\n\tfmt.Printf(\"Wallet API URL: %s\\n\", apiURL)\n\tfmt.Printf(\"Wallet Data FilePath: %s\\n\", walletPath)\n\tfmt.Printf(\"Summary Address: %s\\n\", sumAddress)\n\tfmt.Printf(\"Summary Threshold: %s\\n\", threshold)\n\t//fmt.Printf(\"Min Send Amount: %s\\n\", minSendAmount)\n\t//fmt.Printf(\"Transfer Fees: %s\\n\", minFees)\n\tfmt.Printf(\"-----------------------------------------------------------\\n\")\n\n\treturn nil\n\n}", "func (o KafkaConnectorOutput) Config() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *KafkaConnector) pulumi.StringMapOutput { return v.Config }).(pulumi.StringMapOutput)\n}", "func (*ConfigRequest_V1_System_GatherLogs) Descriptor() ([]byte, []int) {\n\treturn file_config_deployment_config_request_proto_rawDescGZIP(), []int{0, 0, 0, 2}\n}", "func (src *HNCConfiguration) ConvertTo(dstRaw conversion.Hub) error {\n\tdst := dstRaw.(*v1a2.HNCConfiguration)\n\n\t// Spec\n\tsrcSpecTypes := src.Spec.Types\n\tdstSpecRscs := []v1a2.ResourceSpec{}\n\tfor _, st := range srcSpecTypes {\n\t\tdr := v1a2.ResourceSpec{}\n\t\t// Hack the group from APIVersion by removing the version, e.g.\n\t\t// 1) \"rbac.authorization.k8s.io/v1\" => \"rbac.authorization.k8s.io\";\n\t\t// 2) \"v1\" => \"\" (for core type).\n\t\tgv := strings.Split(st.APIVersion, \"/\")\n\t\tif len(gv) == 2 {\n\t\t\tdr.Group = gv[0]\n\t\t}\n\t\t// Hack the resource from Kind by using the lower case and plural form, e.g.\n\t\t// 1) \"Role\" => \"roles\"\n\t\t// 2) \"NetworkPolicy\" => \"networkpolicies\"\n\t\tlk := strings.ToLower(st.Kind)\n\t\tif strings.HasSuffix(lk, \"y\") {\n\t\t\tlk = strings.TrimSuffix(lk, \"y\") + \"ie\"\n\t\t}\n\t\tdr.Resource = lk + \"s\"\n\t\tdtm, ok := toV1A2[st.Mode]\n\t\tif !ok {\n\t\t\t// This should never happen with the enum schema validation.\n\t\t\tdtm = v1a2.Ignore\n\t\t}\n\t\tdr.Mode = dtm\n\t\t// We will only convert non-enforced types since in v1a2 we removed the\n\t\t// enforced types from spec. Having enforced types configured in the spec\n\t\t// would cause 'MultipleConfigurationsForType' condition.\n\t\tif !v1a2.IsEnforcedType(dr) {\n\t\t\tdstSpecRscs = append(dstSpecRscs, dr)\n\t\t}\n\t}\n\tdst.Spec.Resources = dstSpecRscs\n\n\t// We don't need to convert status because controllers will update it.\n\tdst.Status = v1a2.HNCConfigurationStatus{}\n\n\t// rote conversion - ObjectMeta\n\tdst.ObjectMeta = src.ObjectMeta\n\n\treturn nil\n}", "func (*ExternalSchedulerConfig) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_swarming_proto_config_pools_proto_rawDescGZIP(), []int{7}\n}", "func (*CommonExtensionConfig_TapDSConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_common_tap_v3_common_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*LightstepConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_trace_v3_lightstep_proto_rawDescGZIP(), []int{0}\n}", "func CommonLabels(m map[string]string) LoggerOption { return commonLabels(m) }", "func (dc *deploymentconfigurationCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- descDeploymentConfigurationCreated\n\tch <- descDeploymentConfigurationStatusReadyReplicas\n\tch <- descDeploymentConfigurationStatusAvailableReplicas\n}", "func (s LabelingJobOutputConfig) GoString() string {\n\treturn s.String()\n}", "func Config(alwaysPrintSExprs bool) {\n\tprintSExpr = alwaysPrintSExprs\n}", "func (c Config) Summary() string {\n\thost, _ := ServerAddrFromPath(c.Source)\n\treturn fmt.Sprintf(\"URL Prefix: %s\\nSource: %s\\nHost: %s\\nUser: %s\\nDomain: %s\", c.URLPrefix, c.Source, host, c.User, c.Domain)\n}", "func (*SqlServerAuditConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{65}\n}", "func printConfig() {\r\n\tfmt.Println(\"\\n--- Application configuration ---\")\r\n\tfor key, value := range appConfig {\r\n\t\tfmt.Println(fmt.Sprintf(\"\\tkey: %s, value: %v\", key, value));\r\n\t}\r\n\tfmt.Println(\"---------------------------------\")\r\n}", "func (*noOpConntracker) Describe(ch chan<- *prometheus.Desc) {}", "func validateMetricConfig(metricConfigs Metrics) error {\n\tlogFields := map[string]interface{}{}\n\tlogFields[\"metric_config\"] = metricConfigs\n\n\tfor i := 0; i < len(metricConfigs); i++ {\n\t\tlogFields[\"namespace_config\"] = metricConfigs[i].Namespace\n\n\t\t//check namespace - required parameter\n\t\tif !checkSetParameter(metricConfigs[i].Namespace) {\n\t\t\tlogFields[\"parameter\"] = metricNamespace\n\t\t\terr := fmt.Errorf(missingRequiredParameter, metricNamespace)\n\t\t\tlog.WithFields(logFields).Warn(err)\n\t\t\treturn err\n\t\t}\n\t\t//validate namespace configuration\n\t\tif err := validateNamespace(metricConfigs[i].Namespace); err != nil {\n\t\t\tlogFields[\"parameter\"] = metricNamespace\n\t\t\tlog.WithFields(logFields).Warn(err)\n\t\t\treturn err\n\t\t}\n\n\t\tlastNamespacePart := metricConfigs[i].Namespace[len(metricConfigs[i].Namespace)-1]\n\t\tif lastNamespacePart.Source != NsSourceString {\n\t\t\tlogFields[\"parameter\"] = metricNamespace\n\t\t\terr := fmt.Errorf(\"The last namespace element must have `source` set to `string`\")\n\t\t\tlog.WithFields(logFields).Warn(err)\n\t\t\treturn err\n\t\t}\n\n\t\t//check OID - required parameter\n\t\tif !checkSetParameter(metricConfigs[i].Oid) {\n\t\t\tlogFields[\"parameter\"] = metricOid\n\t\t\terr := fmt.Errorf(missingRequiredParameter, metricOid)\n\t\t\tlog.WithFields(logFields).Warn(err)\n\t\t\treturn err\n\t\t}\n\n\t\t//set default mode option if empty\n\t\tif !checkSetParameter(metricConfigs[i].Mode) {\n\t\t\tmetricConfigs[i].Mode = ModeSingle\n\t\t}\n\n\t\t//check possible options for mode parameter\n\t\tif !checkPossibleOptions(metricConfigs[i].Mode, modeOptions) {\n\t\t\tlogFields[\"parameter\"] = metricMode\n\t\t\terr := fmt.Errorf(incorrectValueOfParameter, metricConfigs[i].Mode, modeOptions)\n\t\t\tlog.WithFields(logFields).Warn(err)\n\t\t\treturn err\n\t\t}\n\n\t\t//set default value for scale if scale is not configured\n\t\tif !checkSetParameter(metricConfigs[i].Scale) {\n\t\t\tmetricConfigs[i].Scale = 1.0\n\t\t}\n\t}\n\treturn nil\n}", "func GenerateConfigMaps(instance *sfv1alpha1.SplunkForwarder, namespacedName types.NamespacedName, clusterid string) []*corev1.ConfigMap {\n\tret := []*corev1.ConfigMap{}\n\n\tmetadataCM := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"osd-monitored-logs-metadata\",\n\t\t\tNamespace: namespacedName.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": namespacedName.Name,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": strconv.FormatInt(instance.Generation, 10),\n\t\t\t},\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"local.meta\": `\n[]\naccess = read : [ * ], write : [ admin ]\nexport = system\n`,\n\t\t},\n\t}\n\tret = append(ret, metadataCM)\n\n\tinputsStr := \"\"\n\n\tfor _, input := range instance.Spec.SplunkInputs {\n\t\t// No path passed in, skip it\n\t\tif input.Path == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tinputsStr += \"[monitor://\" + input.Path + \"]\\n\"\n\t\tif input.SourceType != \"\" {\n\t\t\tinputsStr += \"sourcetype = \" + input.SourceType + \"\\n\"\n\t\t} else {\n\t\t\tinputsStr += \"sourcetype = _json\\n\"\n\t\t}\n\n\t\tif input.Index != \"\" {\n\t\t\tinputsStr += \"index = \" + input.Index + \"\\n\"\n\t\t} else {\n\t\t\tinputsStr += \"index = main\\n\"\n\t\t}\n\n\t\tif input.WhiteList != \"\" {\n\t\t\tinputsStr += \"whitelist = \" + input.WhiteList + \"\\n\"\n\t\t}\n\n\t\tif input.BlackList != \"\" {\n\t\t\tinputsStr += \"blacklist = \" + input.BlackList + \"\\n\"\n\t\t}\n\n\t\tif clusterid != \"\" {\n\t\t\tinputsStr += \"_meta = clusterid::\" + clusterid + \"\\n\"\n\t\t}\n\n\t\tinputsStr += \"disabled = false\\n\"\n\t\tinputsStr += \"\\n\"\n\t}\n\n\tlocalCM := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"osd-monitored-logs-local\",\n\t\t\tNamespace: namespacedName.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": namespacedName.Name,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": strconv.FormatInt(instance.Generation, 10),\n\t\t\t},\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"app.conf\": `\n[install]\nstate = enabled\n\n[package]\ncheck_for_updates = false\n\n[ui]\nis_visible = false\nis_manageable = false\n`,\n\t\t\t\"inputs.conf\": inputsStr,\n\t\t},\n\t}\n\n\tret = append(ret, localCM)\n\n\treturn ret\n}", "func (c *Collector) Describe(chan<- *prometheus.Desc) {}", "func main() {\n\tvar (\n\t\t//port = flag.Int(\"port\", 7472, \"HTTP listening port for Prometheus metrics\")\n\t\t//name = flag.String(\"name\", \"lb-ippool\", \"configmap name in default namespace\")\n\t\tpath = flag.String(\"config\", \"\", \"config file\")\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolute path to the kubeconfig file (only needed when running outside of k8s)\")\n\t)\n\n\tflag.Parse()\n\tif len(*path) == 0 {\n\t\tklog.Fatalf(fmt.Sprintf(\"config file is required\"))\n\t}\n\n\trestConfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: corev1.New(clientset.CoreV1().RESTClient()).Events(\"\")})\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"lb-controller\"})\n\tqueue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())\n\n\t// INFO: (1) 与 router server 建立 bgp session\n\ts := getSpeaker(*path)\n\n\tsvcWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), \"services\",\n\t\tmetav1.NamespaceAll, fields.Everything())\n\tsvcIndexer, svcInformer := cache.NewIndexerInformer(svcWatcher, &v1.Service{}, 0, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tqueue.Add(svcKey(key))\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Infof(fmt.Sprintf(\"update %s\", key))\n\t\t\t//}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Infof(fmt.Sprintf(\"delete %s\", key))\n\t\t\t//}\n\t\t},\n\t}, cache.Indexers{})\n\n\tepWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), \"endpoints\",\n\t\tmetav1.NamespaceAll, fields.Everything())\n\tepIndexer, epInformer := cache.NewIndexerInformer(epWatcher, &v1.Endpoints{}, 0, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Info(key)\n\t\t\t//}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\t//if err == nil {\n\t\t\t//\tklog.Info(key)\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Info(key)\n\t\t\t//}\n\t\t},\n\t}, cache.Indexers{})\n\n\tstopCh := make(chan struct{})\n\tgo svcInformer.Run(stopCh)\n\tgo epInformer.Run(stopCh)\n\tif !cache.WaitForCacheSync(stopCh, svcInformer.HasSynced, epInformer.HasSynced) {\n\t\tklog.Fatalf(fmt.Sprintf(\"time out waiting for cache sync\"))\n\t}\n\n\tsync := func(key interface{}, queue workqueue.RateLimitingInterface) error {\n\t\tdefer queue.Done(key)\n\n\t\tswitch k := key.(type) {\n\t\tcase svcKey:\n\t\t\tsvc, exists, err := svcIndexer.GetByKey(string(k))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn fmt.Errorf(\"not exist\")\n\t\t\t}\n\t\t\tendpoints, exists, err := epIndexer.GetByKey(string(k))\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"failed to get endpoints\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn fmt.Errorf(\"not exist\")\n\t\t\t}\n\n\t\t\tif svc.(*v1.Service).Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\trecorder.Eventf(svc.(*v1.Service), v1.EventTypeNormal, \"SetBalancer\", \"advertise svc ip\")\n\t\t\ts.SetBalancer(string(k), svc.(*v1.Service), endpoints.(*v1.Endpoints))\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unknown key type for %s %T\", key, key))\n\t\t}\n\t}\n\n\tfor {\n\t\tkey, quit := queue.Get()\n\t\tif quit {\n\t\t\treturn\n\t\t}\n\n\t\terr := sync(key, queue)\n\t\tif err != nil {\n\t\t\tklog.Error(err)\n\t\t} else {\n\t\t\tqueue.Forget(key)\n\t\t}\n\t}\n}", "func (hc *Hailconfig) List() error {\n\tcols, _ := consolesize.GetConsoleSize()\n\tmaxLenAlias := 25\n\tmaxLenCommand := 80\n\tmaxLenDescription := 25\n\tif cols > 10 {\n\t\tmaxLenAlias = cols/4 - 5\n\t\tmaxLenCommand = cols / 2\n\t\tmaxLenDescription = cols/4 - 5\n\t}\n\n\tt := table.NewWriter()\n\tt.SetOutputMirror(os.Stdout)\n\tt.AppendHeader(table.Row{\"Alias\", \"Command\", \"Description\"})\n\tt.SetColumnConfigs([]table.ColumnConfig{\n\t\t{\n\t\t\tName: \"Alias\",\n\t\t\tWidthMin: 5,\n\t\t\tWidthMax: maxLenAlias,\n\t\t},\n\t\t{\n\t\t\tName: \"Command\",\n\t\t\tWidthMin: 10,\n\t\t\tWidthMax: maxLenCommand,\n\t\t}, {\n\t\t\tName: \"Description\",\n\t\t\tWidthMin: 5,\n\t\t\tWidthMax: maxLenDescription,\n\t\t},\n\t})\n\t//t.SetAllowedRowLength(90)\n\tfor alias, script := range hc.Scripts {\n\t\tt.AppendRow([]interface{}{alias, script.Command, script.Description})\n\t\tt.AppendSeparator()\n\t}\n\tt.Render()\n\treturn nil\n}", "func AddIndependentPropertyGeneratorsForSysctlConfig_STATUS(gens map[string]gopter.Gen) {\n\tgens[\"FsAioMaxNr\"] = gen.PtrOf(gen.Int())\n\tgens[\"FsFileMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"FsInotifyMaxUserWatches\"] = gen.PtrOf(gen.Int())\n\tgens[\"FsNrOpen\"] = gen.PtrOf(gen.Int())\n\tgens[\"KernelThreadsMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreNetdevMaxBacklog\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreOptmemMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreRmemDefault\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreRmemMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreSomaxconn\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreWmemDefault\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetCoreWmemMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4IpLocalPortRange\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"NetIpv4NeighDefaultGcThresh1\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4NeighDefaultGcThresh2\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4NeighDefaultGcThresh3\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpFinTimeout\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpKeepaliveProbes\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpKeepaliveTime\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpMaxSynBacklog\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpMaxTwBuckets\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetIpv4TcpTwReuse\"] = gen.PtrOf(gen.Bool())\n\tgens[\"NetIpv4TcpkeepaliveIntvl\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetNetfilterNfConntrackBuckets\"] = gen.PtrOf(gen.Int())\n\tgens[\"NetNetfilterNfConntrackMax\"] = gen.PtrOf(gen.Int())\n\tgens[\"VmMaxMapCount\"] = gen.PtrOf(gen.Int())\n\tgens[\"VmSwappiness\"] = gen.PtrOf(gen.Int())\n\tgens[\"VmVfsCachePressure\"] = gen.PtrOf(gen.Int())\n}", "func (conf *Config) Print() {\n\tlog.Info().Str(\"app\", version.AppVersion).Str(\"commit\", version.Commit).Msg(\"version\")\n\tlog.Info().Int(\"port\", conf.Port).Msg(\"metrics endpoint port\")\n\tlog.Info().Str(\"namespace\", conf.Namespace).Str(\"subsystem\", conf.Subsystem).Str(\"name\", conf.Name).Msg(\"metric name\")\n\tlog.Info().Str(\"label\", conf.LabelName).Msg(\"label name\")\n\tlog.Info().Str(\"file\", conf.LabelFile).Msg(\"label values file\")\n}", "func (*interfaceCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- receiveBytesDesc\n\tch <- receivePacketsDesc\n\tch <- receiveErrorsDesc\n\tch <- receiveDropsDesc\n\tch <- transmitBytesDesc\n\tch <- transmitPacketsDesc\n\tch <- transmitDropsDesc\n\tch <- transmitErrorsDesc\n\tch <- ipv6receiveBytesDesc\n\tch <- ipv6receivePacketsDesc\n\tch <- ipv6transmitBytesDesc\n\tch <- ipv6transmitPacketsDesc\n\tch <- adminStatusDesc\n\tch <- operStatusDesc\n\tch <- errorStatusDesc\n}", "func (*TemplateConfigStreamResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_alert_v1_services_gen_proto_rawDescGZIP(), []int{13}\n}", "func (m *ConfigurationResponse) String() (result string) {\n\tresult = \"\\n \\\"ietf-dots-signal-channel:signal-config\\\":\\n\"\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"mitigating-config\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"heartbeat-interval\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.MitigatingConfig.HeartbeatInterval.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.MitigatingConfig.HeartbeatInterval.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.MitigatingConfig.HeartbeatInterval.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"missing-hb-allowed\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.MitigatingConfig.MissingHbAllowed.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.MitigatingConfig.MissingHbAllowed.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.MitigatingConfig.MissingHbAllowed.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"max-retransmit\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.MitigatingConfig.MaxRetransmit.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.MitigatingConfig.MaxRetransmit.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.MitigatingConfig.MaxRetransmit.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"ack-timeout\")\n\tmin_float, _ := m.SignalConfigs.MitigatingConfig.AckTimeout.MinValue.Round(2).Float64()\n\tmax_float, _ := m.SignalConfigs.MitigatingConfig.AckTimeout.MaxValue.Round(2).Float64()\n\tcurrent_float, _ := m.SignalConfigs.MitigatingConfig.AckTimeout.CurrentValue.Round(2).Float64()\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"min-value-decimal\", min_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"max-value-decimal\", max_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"current-value-decimal\", current_float)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"ack-random-factor\")\n\tmin_float, _ = m.SignalConfigs.MitigatingConfig.AckRandomFactor.MinValue.Round(2).Float64()\n\tmax_float, _ = m.SignalConfigs.MitigatingConfig.AckRandomFactor.MaxValue.Round(2).Float64()\n\tcurrent_float, _ = m.SignalConfigs.MitigatingConfig.AckRandomFactor.CurrentValue.Round(2).Float64()\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"min-value-decimal\", min_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"max-value-decimal\", max_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"current-value-decimal\", current_float)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"idle-config\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"heartbeat-interval\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.IdleConfig.HeartbeatInterval.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.IdleConfig.HeartbeatInterval.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.IdleConfig.HeartbeatInterval.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"missing-hb-allowed\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.IdleConfig.MissingHbAllowed.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.IdleConfig.MissingHbAllowed.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.IdleConfig.MissingHbAllowed.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"max-retransmit\")\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"min-value\", m.SignalConfigs.IdleConfig.MaxRetransmit.MinValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"max-value\", m.SignalConfigs.IdleConfig.MaxRetransmit.MaxValue)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %d\\n\", \"current-value\", m.SignalConfigs.IdleConfig.MaxRetransmit.CurrentValue)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"ack-timeout\")\n\tmin_float, _ = m.SignalConfigs.IdleConfig.AckTimeout.MinValue.Round(2).Float64()\n\tmax_float, _ = m.SignalConfigs.IdleConfig.AckTimeout.MaxValue.Round(2).Float64()\n\tcurrent_float, _ = m.SignalConfigs.IdleConfig.AckTimeout.CurrentValue.Round(2).Float64()\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"min-value-decimal\", min_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"max-value-decimal\", max_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"current-value-decimal\", current_float)\n\n\tresult += fmt.Sprintf(\" \\\"%s\\\":\\n\", \"ack-random-factor\")\n\tmin_float, _ = m.SignalConfigs.IdleConfig.AckRandomFactor.MinValue.Round(2).Float64()\n\tmax_float, _ = m.SignalConfigs.IdleConfig.AckRandomFactor.MaxValue.Round(2).Float64()\n\tcurrent_float, _ = m.SignalConfigs.IdleConfig.AckRandomFactor.CurrentValue.Round(2).Float64()\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"min-value-decimal\", min_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"max-value-decimal\", max_float)\n\tresult += fmt.Sprintf(\" \\\"%s\\\": %f\\n\", \"current-value-decimal\", current_float)\n\treturn\n}", "func (*TraceConfig) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{1}\n}", "func (*InsightsConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{19}\n}", "func (*AdminConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_common_tap_v2alpha_common_proto_rawDescGZIP(), []int{1}\n}", "func (*IamPolicyAnalysisOutputConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{29}\n}", "func AddIndependentPropertyGeneratorsForKubeletConfig_STATUS(gens map[string]gopter.Gen) {\n\tgens[\"AllowedUnsafeSysctls\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"ContainerLogMaxFiles\"] = gen.PtrOf(gen.Int())\n\tgens[\"ContainerLogMaxSizeMB\"] = gen.PtrOf(gen.Int())\n\tgens[\"CpuCfsQuota\"] = gen.PtrOf(gen.Bool())\n\tgens[\"CpuCfsQuotaPeriod\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"CpuManagerPolicy\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"FailSwapOn\"] = gen.PtrOf(gen.Bool())\n\tgens[\"ImageGcHighThreshold\"] = gen.PtrOf(gen.Int())\n\tgens[\"ImageGcLowThreshold\"] = gen.PtrOf(gen.Int())\n\tgens[\"PodMaxPids\"] = gen.PtrOf(gen.Int())\n\tgens[\"TopologyManagerPolicy\"] = gen.PtrOf(gen.AlphaString())\n}", "func (*CommonExtensionConfig_TapDSConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_common_tap_v4alpha_common_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*SDSConfig) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_ssl_ssl_proto_rawDescGZIP(), []int{3}\n}", "func (*ClientMonitoringConfig) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_cipd_api_config_v1_config_proto_rawDescGZIP(), []int{0}\n}", "func (c Config) PrintHumanConfigArgs() {\n\twebhookURLDisplay := \"\"\n\tif c.WebhookURL != \"\" {\n\t\twebhookURLDisplay = \"<provided-not-displayed>\"\n\t}\n\t// intentionally did not log webhook configuration as there may be secrets\n\tlog.Info().Msgf(\n\t\t\"aws-node-termination-handler arguments: \\n\"+\n\t\t\t\"\\tdry-run: %t,\\n\"+\n\t\t\t\"\\tnode-name: %s,\\n\"+\n\t\t\t\"\\tpod-name: %s,\\n\"+\n\t\t\t\"\\tpod-namespace: %s,\\n\"+\n\t\t\t\"\\tmetadata-url: %s,\\n\"+\n\t\t\t\"\\tkubernetes-service-host: %s,\\n\"+\n\t\t\t\"\\tkubernetes-service-port: %s,\\n\"+\n\t\t\t\"\\tdelete-local-data: %t,\\n\"+\n\t\t\t\"\\tignore-daemon-sets: %t,\\n\"+\n\t\t\t\"\\tpod-termination-grace-period: %d,\\n\"+\n\t\t\t\"\\tnode-termination-grace-period: %d,\\n\"+\n\t\t\t\"\\tenable-scheduled-event-draining: %t,\\n\"+\n\t\t\t\"\\tenable-spot-interruption-draining: %t,\\n\"+\n\t\t\t\"\\tenable-sqs-termination-draining: %t,\\n\"+\n\t\t\t\"\\tdelete-sqs-msg-if-node-not-found: %t,\\n\"+\n\t\t\t\"\\tenable-rebalance-monitoring: %t,\\n\"+\n\t\t\t\"\\tenable-rebalance-draining: %t,\\n\"+\n\t\t\t\"\\tmetadata-tries: %d,\\n\"+\n\t\t\t\"\\tcordon-only: %t,\\n\"+\n\t\t\t\"\\ttaint-node: %t,\\n\"+\n\t\t\t\"\\ttaint-effect: %s,\\n\"+\n\t\t\t\"\\texclude-from-load-balancers: %t,\\n\"+\n\t\t\t\"\\tjson-logging: %t,\\n\"+\n\t\t\t\"\\tlog-level: %s,\\n\"+\n\t\t\t\"\\twebhook-proxy: %s,\\n\"+\n\t\t\t\"\\twebhook-headers: %s,\\n\"+\n\t\t\t\"\\twebhook-url: %s,\\n\"+\n\t\t\t\"\\twebhook-template: %s,\\n\"+\n\t\t\t\"\\tuptime-from-file: %s,\\n\"+\n\t\t\t\"\\tenable-prometheus-server: %t,\\n\"+\n\t\t\t\"\\tprometheus-server-port: %d,\\n\"+\n\t\t\t\"\\temit-kubernetes-events: %t,\\n\"+\n\t\t\t\"\\tkubernetes-events-extra-annotations: %s,\\n\"+\n\t\t\t\"\\taws-region: %s,\\n\"+\n\t\t\t\"\\tqueue-url: %s,\\n\"+\n\t\t\t\"\\tcheck-tag-before-draining: %t,\\n\"+\n\t\t\t\"\\tmanaged-tag: %s,\\n\"+\n\t\t\t\"\\tuse-provider-id: %t,\\n\"+\n\t\t\t\"\\taws-endpoint: %s,\\n\",\n\t\tc.DryRun,\n\t\tc.NodeName,\n\t\tc.PodName,\n\t\tc.PodNamespace,\n\t\tc.MetadataURL,\n\t\tc.KubernetesServiceHost,\n\t\tc.KubernetesServicePort,\n\t\tc.DeleteLocalData,\n\t\tc.IgnoreDaemonSets,\n\t\tc.PodTerminationGracePeriod,\n\t\tc.NodeTerminationGracePeriod,\n\t\tc.EnableScheduledEventDraining,\n\t\tc.EnableSpotInterruptionDraining,\n\t\tc.EnableSQSTerminationDraining,\n\t\tc.DeleteSqsMsgIfNodeNotFound,\n\t\tc.EnableRebalanceMonitoring,\n\t\tc.EnableRebalanceDraining,\n\t\tc.MetadataTries,\n\t\tc.CordonOnly,\n\t\tc.TaintNode,\n\t\tc.TaintEffect,\n\t\tc.ExcludeFromLoadBalancers,\n\t\tc.JsonLogging,\n\t\tc.LogLevel,\n\t\tc.WebhookProxy,\n\t\t\"<not-displayed>\",\n\t\twebhookURLDisplay,\n\t\t\"<not-displayed>\",\n\t\tc.UptimeFromFile,\n\t\tc.EnablePrometheus,\n\t\tc.PrometheusPort,\n\t\tc.EmitKubernetesEvents,\n\t\tc.KubernetesEventsExtraAnnotations,\n\t\tc.AWSRegion,\n\t\tc.QueueURL,\n\t\tc.CheckTagBeforeDraining,\n\t\tc.ManagedTag,\n\t\tc.UseProviderId,\n\t\tc.AWSEndpoint,\n\t)\n}", "func (*Label) Descriptor() ([]byte, []int) {\n\treturn file_config_v1_resources_proto_rawDescGZIP(), []int{2}\n}", "func (s ClarifyExplainerConfig) GoString() string {\n\treturn s.String()\n}", "func batchLabel(batched, streamed bool) string {\n\tif streamed {\n\t\treturn \"streamed\"\n\t} else if batched {\n\t\treturn \"batched\"\n\t}\n\treturn \"single\"\n}", "func (a *Parser) PrintConfig(w io.Writer) {\n\tif len(a.seq) > 0 {\n\t\tfmt.Fprintf(w, \"\\nSpecial characters:\\n\")\n\t\tfor _, s := range [5]specConstant{SpecSymbolPrefix, SpecOpenQuote, SpecCloseQuote, SpecSeparator, SpecEscape} {\n\t\t\tfmt.Fprintf(w, \" %c %s\\n\", a.config.GetSpecial(s), specialDescription[s])\n\t\t}\n\t\tfmt.Fprintf(w, \"\\nBuilt-in operators:\\n\")\n\n\t\treverse := make(map[opConstant]string, len(a.config.opDict))\n\t\tfor n, v := range a.config.opDict {\n\t\t\treverse[v] = n\n\t\t}\n\t\ttext := make(map[opConstant]string, len(a.config.opDict))\n\t\ttext[OpCond] = \"conditional parsing (if, then, else)\"\n\t\ttext[OpDump] = \"print parameters and symbols on standard error (comment)\"\n\t\ttext[OpImport] = \"import environment variables as symbols\"\n\t\ttext[OpInclude] = \"include a file or extract name-values (keys, extractor)\"\n\t\ttext[OpMacro] = \"expand symbols\"\n\t\ttext[OpReset] = \"remove symbols\"\n\t\ttext[OpSkip] = \"do not parse the value (= comment out)\"\n\n\t\tprint := func(name, doc string) {\n\t\t\tif len(name) > 8 {\n\t\t\t\tfmt.Fprintf(w, \" %s\\n\", name)\n\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", \"\", doc)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", name, doc)\n\t\t\t}\n\t\t}\n\t\tprint(reverse[OpCond], text[OpCond])\n\t\tprint(reverse[OpDump], text[OpDump])\n\t\tprint(reverse[OpImport], text[OpImport])\n\t\tprint(reverse[OpInclude], text[OpInclude])\n\t\tprint(reverse[OpMacro], text[OpMacro])\n\t\tprint(reverse[OpReset], text[OpReset])\n\t\tprint(reverse[OpSkip], text[OpSkip])\n\t}\n}", "func (c *Config) Diagnostics() (*diagnostics.Diagnostics, error) {\n\treturn diagnostics.RowFromMap(map[string]interface{}{\n\t\t\"reporting-disabled\": c.ReportingDisabled,\n\t\t\"bind-address\": c.BindAddress,\n\t}), nil\n}", "func (config *EnvoyCPConfig) String() string {\n\n\t// We must remove db password from configuration before showing\n\tredactedConfig := config\n\tredactedConfig.Database.Password = \"[redacted]\"\n\n\tconfigAsYAML, err := yaml.Marshal(redactedConfig)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(configAsYAML)\n}", "func ScrubConfig(target interface{}, values ...string) string {\n\tconf := fmt.Sprintf(\"Config: %+v\", target)\n\tfor _, value := range values {\n\t\tconf = strings.Replace(conf, value, \"<Filtered>\", -1)\n\t}\n\treturn conf\n}", "func (opt Options) PrintConfig(w io.Writer) error {\n\tt1, _ := template.New(\"webhook\").Funcs(sprig.TxtFuncMap()).Parse(webhook)\n\terr := t1.Execute(w, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt2, _ := template.New(\"csr\").Funcs(sprig.TxtFuncMap()).Parse(csr)\n\terr = t2.Execute(w, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt3, _ := template.New(\"deployment\").Funcs(sprig.TxtFuncMap()).Parse(webhookDeployment)\n\terr = t3.Execute(w, opt)\n\treturn err\n}", "func (*SubscriberConfig) Descriptor() ([]byte, []int) {\n\treturn file_network_api_proto_rawDescGZIP(), []int{0}\n}", "func TestLoadingConfigMinSeverityNumberLogs(t *testing.T) {\n\ttestDataLogPropertiesInclude := &LogMatchProperties{\n\t\tSeverityNumberProperties: &LogSeverityNumberMatchProperties{\n\t\t\tMin: logSeverity(\"INFO\"),\n\t\t\tMatchUndefined: true,\n\t\t},\n\t}\n\n\ttestDataLogPropertiesExclude := &LogMatchProperties{\n\t\tSeverityNumberProperties: &LogSeverityNumberMatchProperties{\n\t\t\tMin: logSeverity(\"ERROR\"),\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config_logs_min_severity.yaml\"))\n\trequire.NoError(t, err)\n\n\ttests := []struct {\n\t\tid component.ID\n\t\texpected *Config\n\t}{\n\t\t{\n\t\t\tid: component.NewIDWithName(\"filter\", \"include\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tLogs: LogFilters{\n\t\t\t\t\tInclude: testDataLogPropertiesInclude,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: component.NewIDWithName(\"filter\", \"exclude\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tLogs: LogFilters{\n\t\t\t\t\tExclude: testDataLogPropertiesExclude,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: component.NewIDWithName(\"filter\", \"includeexclude\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tLogs: LogFilters{\n\t\t\t\t\tInclude: testDataLogPropertiesInclude,\n\t\t\t\t\tExclude: testDataLogPropertiesExclude,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.id.String(), func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig()\n\n\t\t\tsub, err := cm.Sub(tt.id.String())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, component.UnmarshalConfig(sub, cfg))\n\n\t\t\tassert.NoError(t, component.ValidateConfig(cfg))\n\t\t\tassert.Equal(t, tt.expected, cfg)\n\t\t})\n\t}\n}", "func (*EvaluationConfig_SmartReplyConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2_conversation_model_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*AlertConfigStreamResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_alert_v1_services_gen_proto_rawDescGZIP(), []int{7}\n}", "func (*InsightsConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{42}\n}", "func (*CollectionResultsConf) Descriptor() ([]byte, []int) {\n\treturn file_benchmonitor_benchmonitor_proto_rawDescGZIP(), []int{2}\n}", "func initConfig() error {\n\tvar err error\n\n\tflag.StringVar(&config.qMgrName, \"ibmmq.queueManager\", \"\", \"Queue Manager name\")\n\tflag.StringVar(&config.replyQ, \"ibmmq.replyQueue\", \"SYSTEM.DEFAULT.MODEL.QUEUE\", \"Model Queue used for reply queues to collect data\")\n\n\tflag.StringVar(&config.monitoredQueues, \"ibmmq.monitoredQueues\", \"\", \"Patterns of queues to monitor\")\n\tflag.StringVar(&config.monitoredQueuesFile, \"ibmmq.monitoredQueuesFile\", \"\", \"File with patterns of queues to monitor\")\n\tflag.StringVar(&config.metaPrefix, \"metaPrefix\", \"\", \"Override path to monitoring resource topic\")\n\n\tflag.StringVar(&config.monitoredChannels, \"ibmmq.monitoredChannels\", \"\", \"Patterns of channels to monitor\")\n\tflag.StringVar(&config.monitoredChannelsFile, \"ibmmq.monitoredChannelsFile\", \"\", \"File with patterns of channels to monitor\")\n\n\tflag.BoolVar(&config.cc.ClientMode, \"ibmmq.client\", false, \"Connect as MQ client\")\n\n\tflag.StringVar(&config.cc.UserId, \"ibmmq.userid\", \"\", \"UserId for MQ connection\")\n\t// If password is not given on command line (and it shouldn't be) then there's a prompt for stdin\n\tflag.StringVar(&config.cc.Password, \"ibmmq.password\", \"\", \"Password for MQ connection\")\n\n\tflag.StringVar(&config.httpListenPort, \"ibmmq.httpListenPort\", defaultPort, \"HTTP Listener\")\n\tflag.StringVar(&config.httpMetricPath, \"ibmmq.httpMetricPath\", \"/metrics\", \"Path to exporter metrics\")\n\n\tflag.StringVar(&config.logLevel, \"log.level\", \"error\", \"Log level - debug, info, error\")\n\tflag.StringVar(&config.namespace, \"namespace\", defaultNamespace, \"Namespace for metrics\")\n\n\tflag.StringVar(&config.pollInterval, \"pollInterval\", defaultPollInterval, \"Frequency of checking channel status\")\n\n\t// The locale ought to be discoverable from the environment, but making it an explicit config\n\t// parameter for now to aid testing, to override, and to ensure it's given in the MQ-known format\n\t// such as \"Fr_FR\"\n\tflag.StringVar(&config.locale, \"locale\", \"\", \"Locale for translated metric descriptions\")\n\n\tflag.BoolVar(&config.qStatus, \"ibmmq.qStatus\", false, \"Add queue status polling\")\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 {\n\t\terr = fmt.Errorf(\"Extra command line parameters given\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tif err == nil {\n\t\tif config.monitoredQueuesFile != \"\" {\n\t\t\tconfig.monitoredQueues, err = mqmetric.ReadPatterns(config.monitoredQueuesFile)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Failed to parse monitored queues file - %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err == nil {\n\t\tif config.monitoredChannelsFile != \"\" {\n\t\t\tconfig.monitoredChannels, err = mqmetric.ReadPatterns(config.monitoredChannelsFile)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Failed to parse monitored channels file - %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err == nil {\n\t\tif config.cc.UserId != \"\" && config.cc.Password == \"\" {\n\t\t\t// TODO: If stdin is a tty, then disable echo. Done differently on Windows and Unix\n\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\tfmt.Printf(\"Enter password: \\n\")\n\t\t\tscanner.Scan()\n\t\t\tconfig.cc.Password = scanner.Text()\n\t\t}\n\t}\n\n\tif err == nil {\n\t\tconfig.pollIntervalDuration, err = time.ParseDuration(config.pollInterval)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Invalid value for interval parameter: %v\", err)\n\t\t}\n\t}\n\n\tif err == nil {\n\t\terr = mqmetric.VerifyPatterns(config.monitoredQueues)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Invalid value for monitored queues: %v\", err)\n\t\t}\n\t}\n\n\tif err == nil {\n\t\terr = mqmetric.VerifyPatterns(config.monitoredChannels)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Invalid value for monitored channels: %v\", err)\n\t\t}\n\t}\n\n\treturn err\n}", "func (s ExplainerConfig) GoString() string {\n\treturn s.String()\n}", "func (*StatusMessage) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1}\n}", "func (*TargetsConf) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_targets_gce_proto_config_proto_rawDescGZIP(), []int{0}\n}", "func (*Config_Warning) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{5, 0}\n}", "func (*vpwsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- vpwsStatus\n\tch <- vpwsSid\n}", "func (*LoggerCfg) Descriptor() ([]byte, []int) {\n\treturn file_src_common_app_cfgs_proto_rawDescGZIP(), []int{1}\n}", "func (o TrustConfigOutput) Labels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *TrustConfig) pulumi.StringMapOutput { return v.Labels }).(pulumi.StringMapOutput)\n}", "func (*NsJailConfig) Descriptor() ([]byte, []int) {\n\treturn file_nsjail_config_proto_rawDescGZIP(), []int{3}\n}", "func (*TranslateConfig) Descriptor() ([]byte, []int) {\n\treturn file_sogou_speech_mt_v1_mt_proto_rawDescGZIP(), []int{1}\n}", "func (*LabelDescriptor) Descriptor() ([]byte, []int) {\n\treturn edgelq_logging_proto_v1alpha2_common_proto_rawDescGZIP(), []int{0}\n}", "func (*AdminConfig) Descriptor() ([]byte, []int) {\n\treturn file_envoy_extensions_common_tap_v3_common_proto_rawDescGZIP(), []int{1}\n}", "func printConfiguration(clustercfg *kubeadmapi.ClusterConfiguration, w io.Writer, printer output.Printer) {\n\t// Short-circuit if cfg is nil, so we can safely get the value of the pointer below\n\tif clustercfg == nil {\n\t\treturn\n\t}\n\n\tcfgYaml, err := configutil.MarshalKubeadmConfigObject(clustercfg, kubeadmapiv1.SchemeGroupVersion)\n\tif err == nil {\n\t\tprinter.Fprintln(w, \"[upgrade/config] Configuration used:\")\n\n\t\tscanner := bufio.NewScanner(bytes.NewReader(cfgYaml))\n\t\tfor scanner.Scan() {\n\t\t\tprinter.Fprintf(w, \"\\t%s\\n\", scanner.Text())\n\t\t}\n\t}\n}", "func (s LabelingJobOutputConfig) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (*LogSpecification) Descriptor() ([]byte, []int) {\n\treturn file_app_log_config_proto_rawDescGZIP(), []int{0}\n}" ]
[ "0.5392613", "0.52665323", "0.5203146", "0.517607", "0.5156359", "0.5143609", "0.5123836", "0.5108068", "0.51062155", "0.505844", "0.5052689", "0.50522065", "0.49690512", "0.49609175", "0.49579698", "0.4954872", "0.49535882", "0.4927243", "0.49067572", "0.49041545", "0.48764473", "0.4863357", "0.48582423", "0.4833522", "0.4828651", "0.48153785", "0.48108807", "0.4801047", "0.47803375", "0.47750115", "0.477344", "0.4772112", "0.47688222", "0.47638264", "0.4750553", "0.47479302", "0.4745487", "0.47419116", "0.4737707", "0.47311834", "0.472609", "0.47225806", "0.47202438", "0.47139218", "0.47126895", "0.47126764", "0.47052553", "0.47016498", "0.47012675", "0.46971813", "0.4695245", "0.46897122", "0.46896884", "0.4682591", "0.4681887", "0.46807364", "0.46758753", "0.46740294", "0.4673985", "0.4673858", "0.46724355", "0.46718195", "0.46637765", "0.4662739", "0.4654023", "0.46525916", "0.46521926", "0.46486598", "0.46464223", "0.46457005", "0.4640109", "0.4638936", "0.46336004", "0.46260083", "0.46139666", "0.46136507", "0.46125656", "0.4612202", "0.46099657", "0.4609642", "0.4600701", "0.45982286", "0.45945075", "0.45920745", "0.45802748", "0.45775053", "0.45751026", "0.45750478", "0.45710945", "0.45697007", "0.45684767", "0.4567813", "0.45676294", "0.45653042", "0.45621368", "0.45617908", "0.45565906", "0.45565522", "0.45525298", "0.45521304" ]
0.49092495
18
KindFromSides determine which can of triangule is the three dots it recieves as an argument.
func KindFromSides(a, b, c float64) Kind { t := []float64{a, b, c} sort.Float64s(t) for _, value := range t { if value <= 0 || math.IsNaN(value) || math.IsInf(value, 0) { return NaT } } if t[2] > t[1]+t[0] { return NaT } if t[0] == t[1] && t[1] == t[2] { return Equ } if t[0] == t[1] || t[1] == t[2] { return Iso } if t[0] != t[1] && t[1] != t[2] && t[2] != t[0] { return Sca } return NaT }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func KindFromSides(a, b, c float64) Kind {\n\thasValidSides := isValidLength(a) && isValidLength(b) && isValidLength(c)\n\tviolatesTriangleInequality := a > b+c || b > a+c || c > a+b\n\tif !hasValidSides || violatesTriangleInequality {\n\t\treturn NaT\n\t}\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\tif a == b || a == c || b == c {\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\n\tvar k Kind\n\n\tif a == b && a == c {\n\t\tk = Equ\n\t} else {\n\t\tif a == b || b == c || a == c {\n\t\t\tk = Iso\n\t\t} else {\n\t\t\tk = Sca\n\t\t}\n\t}\n\t// we're stuck on the issue of triangle inequality, 2a == b + c. this \"proof\" doesn't make sense since triangle (6, 4, 5) surely is a triangle.\n\tif (a <= 0) || (b <= 0) || (c <= 0) || !(a+b == c) || !(b+c == a) || !(a+c == b) {\n\t\tk = NaT\n\t}\n\n\treturn k\n}", "func KindFromSides(a, b, c float64) Kind {\n\n\tvar k Kind\n\n\t// to be a triangle at all, all sides have to be of length > 0\n\tif a <= 0 || b <= 0 || c <= 0 {\n\t\tk = NaT\n\t\treturn k\n\t}\n\t// handle Nan and Inf\n\t// https://play.golang.org/p/qHXIoj-JMAw 0 checks for -Inf and +Inf\n\tif math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c) ||\n\t\tmath.IsInf(a, 0) || math.IsInf(b, 0) || math.IsInf(c, 0) {\n\t\tk = NaT\n\t\treturn k\n\t}\n\n\t// the sum of the lengths of any two sides must be greater than or equal to\n\t// the length of the third side\n\tif a+b < c || a+c < b || b+c < a {\n\t\tk = NaT\n\t\treturn k\n\t}\n\t// degenerate triangle, a straight line\n\t// still want to know how many sides are the same though.\n\t// ie triangle_test.go:81: Triangle with sides, 2, 4, 2 = 0, want 2\n\tif a+b == c || a+c == b || b+c == a {\n\t\tk = NaT\n\t}\n\n\t// how many are the same?\n\tab1 := a == b\n\tac2 := a == c\n\tbc3 := b == c\n\n\tif ab1 && ac2 && bc3 {\n\t\tk = Equ\n\t} else if ab1 || ac2 || bc3 {\n\t\tk = Iso\n\t} else {\n\t\tk = Sca\n\t}\n\n\treturn k\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif !isTriangle(a, b, c) {\n\t\treturn NaT\n\t}\n\n\tif a == b && a == c {\n\t\treturn Equ\n\t}\n\n\tif a == b || a == c || b == c {\n\t\treturn Iso\n\t}\n\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n if !isTriangle(a,b,c) {\n return NaT\n }\n if a == b && a == c && b == c {\n return Equ\n }\n\n if a == b || a == c || b == c {\n return Iso\n }\n\n return Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tdefer trackTime.TrackTime(time.Now())\n\n\tswitch {\n\n\t// Not a triangle\n\tcase a+b < c || a+c < b || b+c < a,\n\t\ta == 0 || b == 0 || c == 0,\n\t\tmath.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c),\n\t\tmath.IsInf(a, 0) || math.IsInf(b, 0) || math.IsInf(c, 0):\n\t\treturn NaT\n\n\t// Equilateral\n\tcase a == b && a == c:\n\t\treturn Equ\n\n\t// Isosceles\n\tcase a == b || b == c || a == c:\n\t\treturn Iso\n\n\t// Scalene\n\tdefault:\n\t\treturn Sca\n\t}\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif a+b > c && a+c > b && b+c > a {\n\t\tif a == b || b == c || a == c {\n\t\t\tif a == b && b == c {\n\t\t\t\treturn Equ\n\t\t\t} else {\n\t\t\t\treturn Iso\n\t\t\t}\n\t\t} else {\n\t\t\treturn Sca\n\t\t}\n\t} else {\n\t\treturn NaT\n\t}\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif !isTriangle(a, b, c) {\n\t\treturn NaT\n\t}\n\n\tif isEquilateral(a, b, c) {\n\t\treturn Equ\n\t}\n\n\tif isIsosceles(a, b, c) {\n\t\treturn Iso\n\t}\n\n\tif isScalene(a, b, c) {\n\t\treturn Sca\n\t}\n\n\treturn NaT\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif !validNumbers(a, b, c) || a+b <= c || a+c <= b || b+c <= a {\n\t\treturn NaT\n\t}\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\tif a == b || b == c || c == a {\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tsides := [3]float64{a, b, c}\n\tsort.Float64s(sides[:])\n\n\tfor _, val := range sides {\n\t\tif val <= 0 || math.IsNaN(val) || math.IsInf(val, 0) {\n\t\t\treturn NaT\n\t\t}\n\t}\n\n\tif !verifyTriangleInequality(sides) {\n\t\treturn NaT\n\t}\n\n\tswitch {\n\tcase isEquilateral(sides):\n\t\treturn Equ\n\tcase isIsoceles(sides):\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) (k Kind) {\n\tvalidSides := a > 0 && b > 0 && c > 0 &&\n\t\t!math.IsInf(a, 1) && !math.IsInf(b, 1) && !math.IsInf(c, 1)\n\ttriangleInequality := (a+b >= c) && (a+c >= b) && (b+c >= a)\n\tisTriangle := validSides && triangleInequality\n\tif !isTriangle {\n\t\tk = NaT\n\t} else if a == b && b == c {\n\t\tk = Equ\n\t} else if a != b && b != c && a != c {\n\t\tk = Sca\n\t} else {\n\t\tk = Iso\n\t}\n\treturn\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar k Kind\n\tsides := []float64{a, b, c}\n\tsort.Float64s(sides)\n\tfmt.Println((sides))\n\ttriangleEquality := sides[0]+sides[1] >= sides[2] && sides[0] >= 0\n\n\tswitch {\n\tcase !triangleEquality || sides[0] == 0 || sides[2] == math.Inf(1):\n\t\tk = NaT\n\tcase sides[0]+sides[1] == sides[2]:\n\t\tk = Deg\n\tcase sides[0] == sides[1] && sides[0] == sides[2]:\n\t\tk = Equ\n\tcase sides[1] == sides[2] && sides[0] < sides[1] && sides[0] < sides[2]:\n\t\tk = Iso\n\tcase sides[0] != sides[1] && sides[0] != sides[2]:\n\t\tk = Sca\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown case! %f, %f, %f\", a, b, c))\n\t}\n\n\treturn k\n}", "func KindFromSides(a, b, c float64) (k Kind) {\n\n\tif !isValid(a, b, c) {\n\t\treturn NaT\n\t}\n\n\tif a == b {\n\t\tk++\n\t}\n\tif a == c {\n\t\tk++\n\t}\n\tif b == c {\n\t\tk++\n\t}\n\treturn\n}", "func KindFromSides(a, b, c float64) Kind {\n\n\t// Check for Not-a-Number and Infinity values\n\tif math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c) || math.IsInf(a, 0) || math.IsInf(b, 0) || math.IsInf(c, 0) {\n\t\treturn NaT\n\t}\n\n\t// Triangle inequality theorem (sum of two sides should be greater than third)\n\t// Better to sort the sides by length, so that we can just compare sum of smallest pair\n\t// Exception here is a 'line' is allowed (sum of two sides equal to third)\n\tvar sides sort.Float64Slice = []float64{a, b, c}\n\tsides.Sort()\n\tif sides[0]+sides[1] < sides[2] {\n\t\treturn NaT\n\t}\n\n\t// Check for -ve values\n\tif a <= 0 || b <= 0 || c <= 0 {\n\t\treturn NaT\n\t}\n\n\t// If all sides are equal\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\n\t// If any two sides are equal\n\tif a == b || b == c || c == a {\n\t\treturn Iso\n\t}\n\n\t// If none of the sides are equal\n\tif a != b && b != c && c != a {\n\t\treturn Sca\n\t}\n\n\treturn NaT\n\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif math.IsNaN(a+b+c) || math.IsInf(a+b+c, 0) {\n\t\treturn NaT // Due to some NaN or Inf values\n\t}\n\tif a <= 0 || b <= 0 || c <= 0 || a+b < c || a+c < b || b+c < a {\n\t\treturn NaT\n\t}\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\tif a == b || a == c || b == c {\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar isValid = func(n float64) bool {\n\t\treturn !(n == 0 || math.IsNaN(n) || math.IsInf(n, 1) || math.IsInf(n, -1))\n\t}\n\tif !(isValid(a) && isValid(b) && isValid(c)) {\n\t\treturn NaT\n\t}\n\tif a+b < c || a+c < b || b+c < a {\n\t\treturn NaT\n\t}\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\tif a == b || a == c || b == c {\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) (k Kind) {\n\n\tif any(\n\t\t[]float64{a, b, c},\n\t\tfunc(f float64) bool {\n\t\t\treturn f <= 0 || math.IsNaN(f) || math.IsInf(f, 1)\n\t\t},\n\t) {\n\t\treturn\n\t}\n\n\tif a+b < c || b+c < a || a+c < b {\n\t\treturn\n\t}\n\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\n\tif a == b || b == c || a == c {\n\t\treturn Iso\n\t}\n\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif a <= 0 || b <= 0 || c <= 0 {\n\t\treturn NaT\n\t}\n\tif a+b < c || b+c < a || c+a < b {\n\t\treturn NaT\n\t}\n\tif math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c) {\n\t\treturn NaT\n\t}\n\tif math.IsInf(a, 0) || math.IsInf(b, 0) || math.IsInf(c, 0) {\n\t\treturn NaT\n\t}\n\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\tif a == b || b == c || a == c {\n\t\treturn Iso\n\t}\n\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tif isNaT(a, b, c) {\n\t\treturn NaT\n\t}\n\n\tif a == b && b == c {\n\t\treturn Equ\n\t}\n\n\tif a == b || a == c || b == c {\n\t\treturn Iso\n\t}\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tswitch {\n\tcase math.IsNaN(a) || math.IsNaN(b) || math.IsNaN(c),\n\t\tmath.IsInf(a, 0) || math.IsInf(b, 0) || math.IsInf(c, 0):\n\t\treturn NaT\n\tcase a <= 0 || b <= 0 || c <= 0,\n\t\ta+b < c || b+c < a || a+c < b:\n\t\treturn NaT\n\tcase a == b && b == c:\n\t\treturn Equ\n\tcase a == b || b == c || a == c:\n\t\treturn Iso\n\tdefault:\n\t\treturn Sca\n\t}\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar k Kind = NaT\n\n\tif math.IsInf(a+b+c, 0) {\n\t\tk = NaT\n\t} else if math.IsNaN(a + b + c) {\n\t\tk = NaT\n\t} else if (a+b < c) || (a+c < b) || (b+c < a) {\n\t\tk = NaT\n\t} else if a <= 0 || b <= 0 || c <= 0 {\n\t\tk = NaT\n\t} else if a == b && b == c {\n\t\tk = Equ\n\t} else if a == b || a == c || b == c {\n\t\tk = Iso\n\t} else if a != b && a != c && b != c {\n\t\tk = Sca\n\t}\n\treturn k\n}", "func KindFromSides(a, b, c float64) Kind {\n\tsides := []float64{a, b, c}\n\tsort.Sort(sort.Float64Slice(sides))\n\n\tswitch {\n\tcase math.IsNaN(sides[0]) || sides[0] <= 0 || sides[2] == math.Inf(1) || sides[2] > sides[0]+sides[1]:\n\t\treturn NaT\n\tcase sides[0] == sides[1] && sides[0] == sides[2] && sides[1] == sides[2]:\n\t\treturn Equ\n\tcase sides[0] == sides[1] || sides[1] == sides[2] || sides[0] == sides[2]:\n\t\treturn Iso\n\t}\n\n\treturn Sca\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar k Kind\n\tif !isNaturalNumber(a) || !isNaturalNumber(b) || !isNaturalNumber(c) {\n\t\treturn NaT\n\t}\n\tsides := sidesOrderedBySize(a, b, c)\n\tswitch {\n\tcase isEquilateral(sides):\n\t\tk = Equ\n\tcase isScalene(sides):\n\t\tk = Sca\n\tcase isIsosceles(sides):\n\t\tk = Iso\n\tdefault:\n\t\tk = NaT\n\t}\n\n\treturn k\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar k Kind = Sca\n\tif !isTraingle(a, b, c) {\n\t\tk = NaT\n\t} else if a == b && b == c {\n\t\tk = Equ\n\t} else if a == b || b == c || c == a {\n\t\tk = Iso\n\t}\n\treturn k\n}", "func KindFromSides(a, b, c float64) Kind {\n\tvar k Kind\n\n\tswitch {\n\tcase math.IsNaN(a + b + c):\n\t\tk = NaT\n\tcase math.IsInf(a+b+c, 1) || math.IsInf(a+b+c, -1):\n\t\tk = NaT\n\tcase a <= 0 || b <= 0 || c <= 0:\n\t\tk = NaT\n\tcase a+b < c || b+c < a || a+c < b:\n\t\tk = NaT\n\tcase a == b && b == c:\n\t\tk = Equ\n\tcase a == b || b == c || a == c:\n\t\tk = Iso\n\tdefault:\n\t\tk = Sca\n\t}\n\n\treturn k\n}", "func CategorizeTriangle(sides []float64) (string, error) {\n\n\tif !ValidateTriangle(sides) {\n\t\treturn \"\", errors.New(NotATriangleErrorMsg)\n\t}\n\n\t// here we are counting how many sides of the same length we got\n\tsideCounter := map[float64]int{}\n\tcurrentCategory := ScaTriangleType\n\tfor i := range sides {\n\t\tsideCounter[sides[i]] += 1\n\n\t\t// check how many sides have the same length\n\t\t// and determine the type of the triangle\n\t\tif sideCounter[sides[i]] == 2 {\n\t\t\tcurrentCategory = IsoTriangleType\n\t\t} else if sideCounter[sides[i]] == 3 {\n\t\t\tcurrentCategory = EqTriangleType\n\t\t}\n\t}\n\n\treturn currentCategory, nil\n\n}", "func getSides(sides string) int {\n\tif sides == \"\" {\n\t\treturn 20\n\t}\n\n\ts, err := strconv.Atoi(sides)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn s\n}", "func IsThreeOfAKind(cs [5]Card) *Hand {\n\tsort.Sort(sort.Reverse(ByCard(cs[:])))\n\n\trankCount := make(map[CardRank]int)\n\tfor _, c := range cs {\n\t\trankCount[c.Rank]++\n\t}\n\n\tisHand := false\n\ttieBreakers := make([]CardRank, 0)\n\tfor rank, count := range rankCount {\n\t\tif count == 3 {\n\t\t\tisHand = true\n\t\t\ttieBreakers = append(tieBreakers, rank)\n\t\t}\n\t}\n\n\tif isHand == false {\n\t\treturn nil\n\t}\n\n\t// Add kickers\n\tfor _, c := range cs {\n\t\tif rankCount[c.Rank] != 3 {\n\t\t\ttieBreakers = append(tieBreakers, c.Rank)\n\t\t}\n\t}\n\n\treturn &Hand{\n\t\tRank: ThreeOfAKind,\n\t\tTieBreakers: tieBreakers,\n\t}\n}", "func (r *Rule) Kind() string {\n\tvar names []string\n\texpr := r.Call.X\n\tfor {\n\t\tx, ok := expr.(*DotExpr)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tnames = append(names, x.Name)\n\t\texpr = x.X\n\t}\n\tx, ok := expr.(*Ident)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\tnames = append(names, x.Name)\n\t// Reverse the elements since the deepest expression contains the leading literal\n\tfor l, r := 0, len(names)-1; l < r; l, r = l+1, r-1 {\n\t\tnames[l], names[r] = names[r], names[l]\n\t}\n\treturn strings.Join(names, \".\")\n}", "func SubSides(eq string) int {\n var equalsIndex int = strings.Index(eq, \"=\")\n var lhs string = eq[0:equalsIndex]\n var rhs string = eq[equalsIndex + 1:]\n var side1 float64 = NotateToDouble(Pemdas(lhs))\n var side2 float64 = NotateToDouble(Pemdas(rhs))\n //fmt.Printf(\"rhs %s = %f\\n\", rhs, side2)\n if side1 > side2 {\n return -1\n } else if (side1 < side2) {\n return 1\n } else {\n return 0\n }\n}", "func getDotType(index int) DotType {\n\tx := int(index / 3)\n\ty := int(index % 3)\n\t/*\n\t\tThe dexter diagonal would be the one from upper left to lower right, and\n\t\tthe sinister diagonal the other one.\n\t*/\n\tonDexterDiagonal := x == y\n\tonSinisterDiagonal := (x + y) == 2\n\tif onDexterDiagonal && onSinisterDiagonal {\n\t\treturn CENTER\n\t} else if onDexterDiagonal || onSinisterDiagonal {\n\t\treturn CORNER\n\t} else {\n\t\treturn SIDE\n\t}\n}", "func sideString(side blas.Side) string {\n\tswitch side {\n\tcase blas.Left:\n\t\treturn \"Left\"\n\tcase blas.Right:\n\t\treturn \"Right\"\n\t}\n\treturn \"unknown side\"\n}", "func Side(a, b, p *Point) OnSide {\n\tab := &Point{\n\t\tLat: b.Lat - a.Lat,\n\t\tLon: b.Lon - a.Lon,\n\t}\n\tap := &Point{\n\t\tLat: p.Lat - a.Lat,\n\t\tLon: p.Lon - a.Lon,\n\t}\n\n\tm := ab.Lon*ap.Lat - ab.Lat*ap.Lon\n\tif m > 0 {\n\t\treturn LeftSide\n\t}\n\tif m < 0 {\n\t\treturn RightSide\n\t}\n\treturn MiddleSide\n}", "func (m *ChannelModeKinds) getKind(mode rune) int {\n\treturn m.kinds[mode]\n}", "func ValidateTriangle(sides []float64) bool {\n\t// made this check in case function will be used somewhere else\n\t// for the usage in this particular app can be commented\n\tif len(sides) != 3 {\n\t\treturn false\n\t}\n\n\t// make it in a loop fashion\n\t// could be done via strict indexing in array\n\tfor i := range sides {\n\t\tsum := 0.0\n\t\tfor j := range sides {\n\t\t\tif i != j {\n\t\t\t\tsum += sides[j]\n\t\t\t}\n\t\t}\n\n\t\tif sum <= sides[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func FourOfaKind(handMap map[string]int) (string, []string) {\n\tvar rank string\n\tvar cardsOut []string\n\n\tif len(handMap) == 2 {\n\t\tfor k, val := range handMap {\n\t\t\tif val == 4 {\n\t\t\t\trank = \"four-of-a-kind\"\n\t\t\t\tcardsOut = append([]string{k, k, k, k}, cardsOut...)\n\t\t\t} else {\n\t\t\t\tcardsOut = append(cardsOut, k)\n\t\t\t}\n\t\t}\n\t}\n\treturn rank, cardsOut\n}", "func getKindFlows(m *api.Message, s *sessionManager) (Flow, bool) {\n\tk := m.GetKind()\n\tvalue, ok := s.telego.kindFlows[k]\n\treturn value, ok\n}", "func kindType(rse string) string {\n\tname := strings.ToLower(rse)\n\tif strings.Contains(name, \"_tape\") || strings.Contains(name, \"_mss\") || strings.Contains(name, \"_export\") {\n\t\treturn \"TAPE\"\n\t}\n\treturn \"DISK\"\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union_String) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union() {\n}", "func (t Tri) InsideTri(p Point) bool {\n\ta := Cross(t.Points[0], t.Points[1], p)\n\tb := Cross(t.Points[1], t.Points[2], p)\n\tc := Cross(t.Points[2], t.Points[0], p)\n\tif a > 0 && b > 0 && c > 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union_String) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union() {\n}", "func (m NoSides) GetSide() (v enum.Side, err quickfix.MessageRejectError) {\n\tvar f field.SideField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (p *Part) MakeTri() {\n\tr := p.R\n\tfmt.Println(\"Ring: \", r.Len())\n\tvar t Tri\n\tfor r.Len() > 3 {\n\t\tif r.Convex() {\n\t\t\tif r.checkEar() {\n\t\t\t\tt = Tri{Abbr: p.Abbr, State: p.State, Part: p, Points: [3]Point{r.Prev().Value.(Point), r.Value.(Point), r.Next().Value.(Point)}}\n\t\t\t\tt.SetBounds()\n\t\t\t\tp.Tris = append(p.Tris, t)\n\t\t\t\tr.Ring = r.Prev()\n\t\t\t\tr.Unlink(1)\n\t\t\t\t//fmt.Println(\"Length Remaining: \", r.Len())\n\t\t\t}\n\t\t}\n\t\tr.Ring = r.Next()\n\t}\n\tt = Tri{Abbr: p.Abbr, State: p.State, Part: p, Points: [3]Point{r.Prev().Value.(Point), r.Value.(Point), r.Next().Value.(Point)}}\n\tt.SetBounds()\n\tp.Tris = append(p.Tris, t)\n}", "func (r Rules) GoString() string {\n\tvar s []string\n\tif r&ASCIIOnly != 0 {\n\t\ts = append(s, \"ASCIIOnly\")\n\t}\n\tif r&ValidUTF8 != 0 {\n\t\ts = append(s, \"ValidUTF8\")\n\t}\n\tif r&URLUnescaped != 0 {\n\t\ts = append(s, \"URLUnescaped\")\n\t}\n\tif r&ShellSafe != 0 {\n\t\ts = append(s, \"ShellSafe\")\n\t}\n\tif r&ArgumentSafe != 0 {\n\t\ts = append(s, \"ShellSafe\")\n\t}\n\tif r&WindowsSafe != 0 {\n\t\ts = append(s, \"WindowsSafe\")\n\t}\n\tif r&NotHidden != 0 {\n\t\ts = append(s, \"NotHidden\")\n\t}\n\trem := r &^ (ASCIIOnly | ValidUTF8 | URLUnescaped | ShellSafe | ArgumentSafe | WindowsSafe | NotHidden)\n\tif rem == 0 {\n\t\tif len(s) == 0 {\n\t\t\treturn \"Any\"\n\t\t}\n\t\treturn strings.Join(s, \"|\")\n\t}\n\ts = append(s, fmt.Sprintf(\"0x%02x\", rem))\n\treturn strings.Join(s, \"|\")\n}", "func (s *DatabaseServerV3) GetKind() string {\n\treturn s.Kind\n}", "func IsFourOfAKind(cs [5]Card) *Hand {\n\trankCount := make(map[CardRank]int)\n\tfor _, c := range cs {\n\t\trankCount[c.Rank]++\n\t}\n\n\tisHand := false\n\thandStrength := Two\n\tkicker := Two\n\n\tfor rank, count := range rankCount {\n\t\tif count == 4 {\n\t\t\tisHand = true\n\t\t\thandStrength = rank\n\t\t}\n\n\t\tif count == 1 {\n\t\t\tkicker = rank\n\t\t}\n\t}\n\n\tif isHand == false {\n\t\treturn nil\n\t}\n\n\treturn &Hand{\n\t\tRank: FourOfAKind,\n\t\tTieBreakers: []CardRank{handStrength, kicker},\n\t}\n}", "func treeTRI( triArray[] string, arrayPos int) int{\n\n//Function check to see if the there is any shapes in the in the listArray\n//if not it changes the structures as it moves to the end\n\tif listArray[0] != \"TRI\" { \n\t\t\tlistArray[1]= \"<inst>\"\n\t\t\tlistArray[0] = \"TRI\"\n\t\tarrayPos++\n\t\t\n// Called the function so it can be processed with the valid format \t\n\t\ttreeTRI(triArray[0:],arrayPos)\t\n\t}else{ if listArray[1] == \"\" || listArray[1] == \"<inst>\"{ // after transforming it is place in a format that can be parsed \n\t\t\tif triArray[arrayPos] == \"TRI\"{ // Ensure we are not Validating a Shape\n\t\t\t\tarrayPos++\n\t\t\t}\n\t\t\t\n\t\t\t// Retrieve the Coordinated from the array\n\t\t\t// Proceeding to the next value\n\t\t\tvar curCoord string=triArray[arrayPos]\n\t\t\tarrayPos++\n\t\t\tvar secCoord string=triArray[arrayPos]\n\t\t\tarrayPos++\n\t\t\tvar triCoord string=triArray[arrayPos]\n\t\t\t\n\t\t\t// Using Slices we get each Values \n\t\t\tx:=curCoord[0:1]\n\t\t\ty:=curCoord[1:2]\t\t\t\n\t\t\tyy:=secCoord[1:2]\n\t\t\txx:=secCoord[0:1]\t\t\t\n\t\t\txxx:=triCoord[0:1]\n\t\t\tyyy:=triCoord[1:2]\n\t\t\t\n\t\t\t//The Printing format for the lower part of the tree\n\t\t\tfmt.Printf(\"\\n |\\n\")\n\t\t\tfmt.Printf(\"TRI\\n/ \\\\\\n\")\n\t\t\tfmt.Printf(\"<coord>,<coord>,<coord>\\n\")\n\t\t\tfmt.Printf(\"<x><y>,<x><y>,<x><y>\\n\"+x+\" \"+y+\" \"+xx+\" \"+yy+\" \"+xxx+\" \"+yyy)\n\t\t\tlistArray[0] = \"<inst>\"\n\t\t\tlistArray[1] = \"<inst_list>\"\n\t\t\t\n\t\t\ttempCount=tempCount-1\n\t\t\t\tif(tempCount >= 0){\t\t\t\t\n\t\t\t\t\tlistArray[tempCount]=\"\"\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t}\n\t\t }\n\t\n\treturn arrayPos\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union_Uint32) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union() {\n}", "func isRightAngleTriangle(p1, p2 Point) bool {\n\t// v1, v2\n\tif p1.x*p2.x + p1.y*p2.y == 0 {\n\t\treturn true\n\t}\n\n\t// v1, v3\n\tif p1.x*(p2.x - p1.x) + p1.y*(p2.y - p1.y) == 0 {\n\t\treturn true\n\t}\n\n\t// v2, v3\n\tif p2.x*(p2.x - p1.x) + p2.y*(p2.y - p1.y) == 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func verifyTriangleInequality(sides [3]float64) bool {\n\treturn sides[2] <= sides[1]+sides[0]\n}", "func (t TransposeTri) Triangle() (int, TriKind) {\n\tn, upper := t.Triangular.Triangle()\n\treturn n, !upper\n}", "func Kinds() []Kind {\n\tvar out []Kind\n\tfor k := range kinds {\n\t\tout = append(out, k)\n\t}\n\treturn out\n}", "func CriticalKinds() []string {\n\tck := make([]string, 0, 6)\n\tck = append(ck, constant.RulesKind)\n\tck = append(ck, constant.AttributeManifestKind)\n\tck = append(ck, constant.AdapterKind)\n\tck = append(ck, constant.TemplateKind)\n\tck = append(ck, constant.InstanceKind)\n\tck = append(ck, constant.HandlerKind)\n\treturn ck\n}", "func ReferenceKind(fromKind, toKind string) string {\n\treturn fmt.Sprintf(\"%s-%s\", fromKind, toKind)\n}", "func rightTriplet(variable,a,b,c int) bool {\n\tif isPytha(a,b,c){\n\t\tif triplet(variable,a,b,c){\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func getApplicableKindsForPolicy(p *v1alpha1.Policy) []string {\n\tkindsMap := map[string]interface{}{}\n\tkinds := []string{}\n\t// iterate over the rules an identify all kinds\n\tfor _, rule := range p.Spec.Rules {\n\t\tfor _, k := range rule.ResourceDescription.Kinds {\n\t\t\tkindsMap[k] = nil\n\t\t}\n\t}\n\n\t// get the kinds\n\tfor k := range kindsMap {\n\t\tkinds = append(kinds, k)\n\t}\n\treturn kinds\n}", "func (o Op) IsSlice3() bool", "func (o DataCollectionRuleOutput) Kind() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataCollectionRule) pulumi.StringPtrOutput { return v.Kind }).(pulumi.StringPtrOutput)\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union_Uint32) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union() {\n}", "func GetPieceType(square uint8) int {\n\treturn int((square & PieceMask) >> 5)\n}", "func (ds *DatabaseService) GetParentsOfKind(concept *Concept, kinds ...Identifier) ([]*Concept, error) {\n\trelations, err := ds.FetchParentRelationships(concept)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconceptIDs := make([]int, 0, len(relations))\n\tfor _, relation := range relations {\n\t\tfor _, kind := range kinds {\n\t\t\tif relation.Type == kind {\n\t\t\t\tconceptIDs = append(conceptIDs, int(relation.Target))\n\t\t\t}\n\t\t}\n\t}\n\treturn ds.FetchConcepts(conceptIDs...)\n}", "func (t Triplet) Perimeter() int {\n\treturn t[0] + t[1] + t[2]\n}", "func (m modeKinds) kind(mode rune) int {\n\tm.RLock()\n\tdefer m.RUnlock()\n\n\treturn m.channelModes[mode]\n}", "func (this *Poly) getType() int {\n\treturn this.areaAndtype >> 6\n}", "func isCompoundKind(kind reflect.Kind) bool {\n\tswitch kind {\n\tcase reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union_E_OpenconfigSegmentRouting_AdjacencySid_SidId) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_AdjacencySid_SidId_Union() {\n}", "func (p *Position) setupSide(str string, color uint8) *Position {\n\tinvalid := func (move string, color uint8) {\n\t\t// Don't panic.\n\t\tpanic(fmt.Sprintf(\"Invalid notation '%s' for %s\\n\", move, C(color)))\n\t}\n\n\tfor _, move := range strings.Split(str, `,`) {\n\t\tif move[0] == 'M' {\n\t\t\tp.color = color\n\t\t} else {\n\t\t\tarr := reMove.FindStringSubmatch(move)\n\t\t\tif len(arr) == 0 {\n\t\t\t\tinvalid(move, color)\n\t\t\t}\n\t\t\tsquare := square(int(arr[3][0]-'1'), int(arr[2][0]-'a'))\n\n\t\t\tswitch move[0] {\n\t\t\tcase 'K':\n\t\t\t\tp.pieces[square] = king(color)\n\t\t\tcase 'Q':\n\t\t\t\tp.pieces[square] = queen(color)\n\t\t\tcase 'R':\n\t\t\t\tp.pieces[square] = rook(color)\n\t\t\tcase 'B':\n\t\t\t\tp.pieces[square] = bishop(color)\n\t\t\tcase 'N':\n\t\t\t\tp.pieces[square] = knight(color)\n\t\t\tcase 'E':\n\t\t\t\tp.enpassant = uint8(square)\n\t\t\tcase 'C':\n\t\t\t\tif (square == C1 + int(color)) || (square == C8 + int(color)) {\n\t\t\t\t\tp.castles |= castleQueenside[color]\n\t\t\t\t} else if (square == G1 + int(color)) || (square == G8 + int(color)) {\n\t\t\t\t\tp.castles |= castleKingside[color]\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// When everything else fails, read the instructions.\n\t\t\t\tp.pieces[square] = pawn(color)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn p\n}", "func (this *DtNavMesh) findConnectingPolys(va, vb []float32, tile *DtMeshTile, side int, con []DtPolyRef, conarea []float32, maxcon int) int {\n\tif tile == nil {\n\t\treturn 0\n\t}\n\n\tvar amin, amax [2]float32\n\tcalcSlabEndPoints(va, vb, amin[:], amax[:], side)\n\tapos := getSlabCoord(va, side)\n\n\t// Remove links pointing to 'side' and compact the links array.\n\tvar bmin, bmax [2]float32\n\tm := DT_EXT_LINK | (uint16)(side)\n\tn := 0\n\n\tbase := this.GetPolyRefBase(tile)\n\n\tfor i := 0; i < int(tile.Header.PolyCount); i++ {\n\t\tpoly := &tile.Polys[i]\n\t\tnv := int(poly.VertCount)\n\t\tfor j := 0; j < nv; j++ {\n\t\t\t// Skip edges which do not point to the right side.\n\t\t\tif poly.Neis[j] != m {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvc := tile.Verts[poly.Verts[j]*3:]\n\t\t\tvd := tile.Verts[poly.Verts[(j+1)%nv]*3:]\n\t\t\tbpos := getSlabCoord(vc, side)\n\n\t\t\t// Segments are not close enough.\n\t\t\tif DtAbsFloat32(apos-bpos) > 0.01 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Check if the segments touch.\n\t\t\tcalcSlabEndPoints(vc, vd, bmin[:], bmax[:], side)\n\n\t\t\tif !overlapSlabs(amin[:], amax[:], bmin[:], bmax[:], 0.01, tile.Header.WalkableClimb) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Add return value.\n\t\t\tif n < maxcon {\n\t\t\t\tconarea[n*2+0] = DtMaxFloat32(amin[0], bmin[0])\n\t\t\t\tconarea[n*2+1] = DtMinFloat32(amax[0], bmax[0])\n\t\t\t\tcon[n] = base | (DtPolyRef)(i)\n\t\t\t\tn++\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn n\n}", "func TestLargestPerimeterTriangle(t *testing.T) {\n\tvar cases = []struct {\n\t\tinput []int\n\t\toutput int\n\t}{\n\t\t{\n\t\t\tinput: []int{1, 2, 1},\n\t\t\toutput: 0,\n\t\t},\n\t\t{\n\t\t\tinput: []int{3, 2, 3, 4},\n\t\t\toutput: 10,\n\t\t},\n\t\t{\n\t\t\tinput: []int{2, 1, 2},\n\t\t\toutput: 5,\n\t\t},\n\t\t{\n\t\t\tinput: []int{3, 6, 2, 3},\n\t\t\toutput: 8,\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\tx := largestPerimeter(c.input)\n\t\tif x != c.output {\n\t\t\tt.Fail()\n\t\t}\n\t}\n}", "func convKindStr(v interface{}) string { return reflectKindStr(convKind(v)) }", "func (o NetworkPolicyOutput) Kind() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkPolicy) pulumi.StringOutput { return v.Kind }).(pulumi.StringOutput)\n}", "func checkWay() string {\n\tif commons.Flags.Way == \"\" {\n\t\treturn \"required way of packet --way string\\n\"\n\t} else if (commons.Flags.Way != \"ingress\") && (commons.Flags.Way != \"egress\") {\n\t\treturn \"invalid way of packet (ingress or egress)\\n\"\n\t}\n\treturn \"\"\n}", "func (m NoSides) HasSide() bool {\n\treturn m.Has(tag.Side)\n}", "func (o FirewallPolicyRuleResponseOutput) Kind() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FirewallPolicyRuleResponse) string { return v.Kind }).(pulumi.StringOutput)\n}", "func canMakeTwoTopOneLeft(p int) bool {\n\tif p <= 8 {\n\t\treturn false\n\t}\n\n\tswitch p {\n\tcase 16, 24, 32, 40, 48, 56, 64, 15, 23, 31, 39, 47, 55, 63:\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *TriDense) Triangle() (n int, kind TriKind) {\n\treturn t.mat.N, t.triKind()\n}", "func (o CrossVersionObjectReferenceOutput) Kind() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReference) string { return v.Kind }).(pulumi.StringOutput)\n}", "func (o CrossVersionObjectReferenceOutput) Kind() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CrossVersionObjectReference) string { return v.Kind }).(pulumi.StringOutput)\n}", "func (me TClipFillRuleType) IsEvenodd() bool { return me.String() == \"evenodd\" }", "func trimIncompleteKind(mask string) (string, error) {\n\tmask = strings.Trim(mask, \"()\")\n\tks := strings.Split(mask, \"|\")\n\tif len(ks) == 1 {\n\t\treturn ks[0], nil\n\t}\n\tif len(ks) == 2 && ks[0] == \"null\" {\n\t\treturn ks[1], nil\n\t}\n\treturn \"\", fmt.Errorf(\"invalid incomplete kind: %s\", mask)\n\n}", "func (*NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union_E_OpenconfigSegmentRouting_PrefixSid_SidId) Is_NetworkInstance_Protocol_Isis_Interface_Level_Af_SegmentRouting_PrefixSid_SidId_Union() {\n}", "func (s *AppServerV3) GetKind() string {\n\treturn s.Kind\n}", "func getShapeFromPiece(p Piece) Shape {\n\tvar retShape Shape\n\tswitch p {\n\tcase LPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 1, col: 2},\n\t\t\tPoint{row: 0, col: 0},\n\t\t}\n\tcase IPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 1, col: 2},\n\t\t\tPoint{row: 1, col: 3},\n\t\t}\n\tcase OPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 0, col: 0},\n\t\t\tPoint{row: 0, col: 1},\n\t\t}\n\tcase TPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 1, col: 2},\n\t\t\tPoint{row: 0, col: 1},\n\t\t}\n\tcase SPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 0, col: 0},\n\t\t\tPoint{row: 0, col: 1},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 1, col: 2},\n\t\t}\n\tcase ZPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 1, col: 1},\n\t\t\tPoint{row: 0, col: 1},\n\t\t\tPoint{row: 0, col: 2},\n\t\t}\n\tcase JPiece:\n\t\tretShape = Shape{\n\t\t\tPoint{row: 1, col: 0},\n\t\t\tPoint{row: 0, col: 1},\n\t\t\tPoint{row: 0, col: 0},\n\t\t\tPoint{row: 0, col: 2},\n\t\t}\n\tdefault:\n\t\tpanic(\"getShapeFromPiece(Piece): Invalid piece entered\")\n\t}\n\treturn retShape\n\n}", "func (gn *Gen) GenTriSyllables() {\n\ts := \"\"\n\tfor i := 0; i < 3; i++ {\n\t\tfor _, syl1 := range gn.Syl1 {\n\t\t\tfor _, syl2 := range gn.Syl2 {\n\t\t\t\tfor _, syl3 := range gn.Syl3 {\n\t\t\t\t\tif i == 0 {\n\t\t\t\t\t\ts = syl3 + \" \" + syl1 + \" \" + syl2\n\t\t\t\t\t} else if i == 1 {\n\t\t\t\t\t\ts = syl1 + \" \" + syl2 + \" \" + syl3\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts = syl2 + \" \" + syl3 + \" \" + syl1\n\t\t\t\t\t}\n\t\t\t\t\tgn.TriSyls = append(gn.TriSyls, s)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (o Op) IsSlice3() bool {\n\tswitch o {\n\tcase OSLICE, OSLICEARR, OSLICESTR:\n\t\treturn false\n\tcase OSLICE3, OSLICE3ARR:\n\t\treturn true\n\t}\n\tFatalf(\"IsSlice3 op %v\", o)\n\treturn false\n}", "func GetEdgeKind(e *scpb.Edge) string {\n\tif k := e.GetGenericKind(); k != \"\" {\n\t\treturn k\n\t}\n\treturn EdgeKindString(e.GetKytheKind())\n}", "func sliceKind(val reflect.Value) reflect.Kind {\n\tswitch val.Type().Elem().Kind() {\n\tcase reflect.Ptr:\n\t\treturn ptrKind(val.Type().Elem())\n\t}\n\treturn val.Type().Elem().Kind()\n}", "func GetKind(node *yaml.RNode, path string) string {\n\treturn GetStringField(node, path, \"kind\")\n}", "func OrRelkind(relType internal.RelType) string {\n\tvar s string\n\tswitch relType {\n\tcase internal.Table:\n\t\ts = \"TABLE\"\n\tcase internal.View:\n\t\ts = \"VIEW\"\n\tdefault:\n\t\tpanic(\"unsupported RelType\")\n\t}\n\treturn s\n}", "func getPizzaSlice(a, b Coordinate) stl.Triangle {\n\treturn stl.Triangle {\n\t\tNormal: stl.Vec3{ 0,0,1 },\n\t\tVertices: [3]stl.Vec3{\n\t\t\tstl.Vec3{ 0,0,0 },\n\t\t\tstl.Vec3{ float32(a.X), float32(a.Y), 0 },\n\t\t\tstl.Vec3{ float32(b.X), float32(b.Y), 0 },\n\t\t},\n\t}\n}", "func KindStrings() []string {\n\tstrs := make([]string, len(_KindNames))\n\tcopy(strs, _KindNames)\n\treturn strs\n}", "func getDatastoreKind(kind reflect.Type) (dsKind string) {\n\tdsKind = kind.String()\n\tif li := strings.LastIndex(dsKind, \".\"); li >= 0 {\n\t\t//Format kind to be in a standard format used for datastore\n\t\tdsKind = dsKind[li+1:]\n\t}\n\treturn\n}", "func (o SecurityPolicyRuleResponseOutput) Kind() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleResponse) string { return v.Kind }).(pulumi.StringOutput)\n}", "func guessEntityTypeFromHoleQuestion(hole string) (string, string) {\n\tvar types []string\n\tsplits := strings.Split(hole, \".\")\n\tfor _, t := range splits {\n\t\tfor _, r := range resourcesTypesWithPlural {\n\t\t\tif t == r {\n\t\t\t\ttypes = append(types, cloud.SingularizeResource(r))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tvar prop string\n\tif len(splits) == 2 {\n\t\tprop = splits[1]\n\t}\n\n\tif l := len(types); l == 1 {\n\t\treturn types[0], prop\n\t} else if l == 2 {\n\t\treturn types[1], \"\"\n\t}\n\n\treturn \"\", \"\"\n}", "func (o *TeamConfiguration) GetKind() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Kind\n}", "func (p Primitive) Kind() Kind { return Kind(p) }", "func (o *ReconciliationTarget) GetKind() string {\n\tif o == nil || o.Kind == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Kind\n}", "func (s Side) DecryptSide() Side {\n\treturn s ^ 1 // flips bit, so 0 becomes 1, 1 becomes 0\n}", "func maxSideLength(mat [][]int, threshold int) int {\n\t// acc[i][j]: the accumulated sum right and bottom of point (i, j)\n\tm, n := len(mat), len(mat[0])\n acc := make([][]int, m+1)\n for i := range acc {\n \tacc[i] = make([]int, n+1)\n\t}\n\tfor i:=m-1; i>=0; i-- {\n\t\tfor j:=n-1; j>=0; j-- {\n\t\t\tacc[i][j] = mat[i][j]+acc[i+1][j]+acc[i][j+1]-acc[i+1][j+1]\n\t\t}\n\t}\n\t// binary search for low=0 and high=min(m,n). for each mid,\n\t// check if there exists one square with side length <= threshold\n\t// time is m*n*log(min(m,n))\n\tlo, hi := 1, m+1\n\tif m>n {\n\t\thi = n+1\n\t}\n\tfor lo<hi {\n\t\tmid := (lo+hi)/2\n\t\texist := false\n\t\touter: for i:=0; i+mid<=m; i++ {\n\t\t\tfor j:=0; j+mid<=n; j++ {\n\t\t\t\tarea := acc[i][j]-acc[i+mid][j]-acc[i][j+mid]+acc[i+mid][j+mid]\n\t\t\t\tif area<=threshold {\n\t\t\t\t\texist = true\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// we want the max value of that CAN. so we search the first CAN'T. the candidate is 1 to n,\n\t\t// so we let lo=1, hi=n+1. the loop end with lo=hi with first that CAN'T. so lo-1 is max value that CAN.\n\t\tif exist {\n\t\t\tlo = mid+1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\treturn lo-1\n}", "func (m NoSides) GetSideComplianceID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SideComplianceIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}" ]
[ "0.7428459", "0.7388428", "0.7368537", "0.73600346", "0.73186207", "0.72892696", "0.7226378", "0.72238153", "0.7183931", "0.7165797", "0.7119315", "0.706905", "0.7056189", "0.70155865", "0.7012035", "0.69348544", "0.6934534", "0.6876252", "0.6867299", "0.6852648", "0.68488026", "0.68463326", "0.681286", "0.67928195", "0.67565185", "0.55572903", "0.5162161", "0.47873023", "0.47343004", "0.46162936", "0.46110913", "0.460961", "0.45101917", "0.44791374", "0.4425032", "0.4415202", "0.44119596", "0.4365178", "0.43524945", "0.43377972", "0.4317612", "0.42916667", "0.4282875", "0.423996", "0.4223357", "0.4220827", "0.42158002", "0.42140362", "0.42108744", "0.4201842", "0.41757336", "0.41728184", "0.4170449", "0.41687164", "0.41651922", "0.41605547", "0.41603586", "0.41452667", "0.41412744", "0.4133386", "0.41327906", "0.41120312", "0.41117573", "0.40864483", "0.40832785", "0.4075135", "0.40688583", "0.40660855", "0.403141", "0.40236083", "0.40169832", "0.4016406", "0.40103814", "0.40002468", "0.3983548", "0.3979704", "0.39786798", "0.39786798", "0.39769965", "0.3975705", "0.39730012", "0.39656627", "0.39654624", "0.3964257", "0.39528129", "0.39422163", "0.3937845", "0.39362156", "0.39354512", "0.3927585", "0.3923459", "0.3905534", "0.39042208", "0.38885835", "0.388665", "0.38843867", "0.3882269", "0.38768557", "0.387639", "0.3871563" ]
0.66230834
25
NewSimpleController create an instance of Controller
func NewSimpleController(cfg *Config, crd CRD, handler Handler) Controller { if cfg == nil { cfg = &Config{} } cfg.setDefaults() // queue queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) resourceEventHandlerFuncs := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { queue.Add(key) } }, UpdateFunc: func(old interface{}, new interface{}) { key, err := cache.MetaNamespaceKeyFunc(new) if err == nil { queue.Add(key) } }, DeleteFunc: func(obj interface{}) { // IndexerInformer uses a delta queue, therefore for deletes we have to use this // key function. key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err == nil { queue.Add(key) } }, } // indexer and informer indexer, informer := cache.NewIndexerInformer( crd.GetListerWatcher(), crd.GetObject(), 0, resourceEventHandlerFuncs, cache.Indexers{}) // Create the SimpleController Instance return &SimpleController{ cfg: cfg, informer: informer, indexer: indexer, queue: queue, handler: handler, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewController() *Controller {\n controller := Controller{}\n\n return &controller\n}", "func NewController() *Controller {\n\treturn &Controller{wrapper: NewWrapper()}\n}", "func NewController() Controller {\n\treturn &controller{}\n}", "func New() *Controller {\n\treturn &Controller{}\n}", "func NewController() *Controller {\n\treturn &Controller{Logger: logger.NewLogger()}\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tprojectCtl: project.Ctl,\n\t}\n}", "func NewController() *Controller {\n\treturn &Controller{}\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tClient: client.NewClient(),\n\t}\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tprojectMgr: project.Mgr,\n\t\tmetaMgr: metamgr.NewDefaultProjectMetadataManager(),\n\t\tallowlistMgr: allowlist.NewDefaultManager(),\n\t}\n}", "func NewController(ctx context.Context) *Controller {\n\treturn &Controller{\n\t\tctx: ctx,\n\t\texplorerClient: newClientConn(1000, 10000),\n\t\trecordClient: newClientConn(1000, 10000),\n\t\tsubTree: make(chan *URLEntry, 1000),\n\t\trecord: make(chan *URLEntry, 1000),\n\t\turlCache: make(map[string]*URLEntry),\n\t\texplorerStat: newRoutineStat(0),\n\t\trecordStat: newRoutineStat(0),\n\t}\n}", "func NewController(backendPool pool.Interface) *Controller {\n\treturn &Controller{\n\t\tbackendPool: backendPool,\n\t}\n}", "func NewController() *Controller {\n\treturn &Controller{\n\t\tClouds: make(map[string]CloudProvider),\n\t\t// WorkerOptions: NewWorkerOptions(),\n\t\tprovisionErr: NewErrCloudProvision(),\n\t}\n}", "func NewController(exec boil.ContextExecutor) Controller {\n\trepo := &personRepository{executor: exec}\n\tsvc := &personService{repo: repo}\n\tpc := &personController{service: svc}\n\treturn pc\n}", "func New(b *base.Controller, moduleID string, uu userUsecases.Usecase) *Controller {\n\treturn &Controller{\n\t\tb,\n\t\tmoduleID,\n\t\tuu,\n\t}\n}", "func NewController(cfg *config.Config) (*Controller, error) {\n\tsrv, err := service.NewService(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Controller{\n\t\tService: srv,\n\t}, nil\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tiManager: instance.Mgr,\n\t\tpManager: policy.Mgr,\n\t\tscheduler: scheduler.Sched,\n\t\texecutionMgr: task.NewExecutionManager(),\n\t}\n}", "func NewController(m driver.StackAnalysisInterface) *Controller {\n\treturn &Controller{\n\t\tm: m,\n\t}\n}", "func NewController(name string) *Controller {\n\treturn &Controller{\n\t\tRoutes: NewRoutes(name),\n\t}\n}", "func NewController(productService contract.ProductService) *Controller {\n\tonce.Do(func() {\n\t\tinstance = &Controller{\n\t\t\tproductService: productService,\n\t\t}\n\t})\n\treturn instance\n}", "func NewController() controller.Controller {\n\treturn &Controller{}\n}", "func NewController(dao Dao) *Controller {\n\treturn &Controller{Dao: dao}\n}", "func NewController(js JobsController, pa Parser, do Downloader, bo Boruter, dr Dryader,\n) *Controller {\n\tc := &Controller{\n\t\tjobs: js,\n\t\tparser: pa,\n\t\tdownloader: do,\n\t\tboruter: bo,\n\t\tdryader: dr,\n\t\tfinish: make(chan int),\n\t}\n\tc.looper.Add(1)\n\tgo c.loop()\n\treturn c\n}", "func New(b *base.Controller, moduleID string, cu categoryUsecases.Usecase) *Controller {\n\treturn &Controller{\n\t\tb,\n\t\tmoduleID,\n\t\tcu,\n\t}\n}", "func NewController(userService user.Service) chi.Router {\n\tc := Controller{userService}\n\tr := chi.NewRouter()\n\n\tr.Post(\"/\", c.AddUser)\n\tr.Get(\"/{userID}\", c.GetUser)\n\tr.Put(\"/{userID}/name\", c.UpdateName)\n\n\treturn r\n}", "func NewController(client kubernetes.Interface) *Controller {\n\tshared := informers.NewSharedInformerFactory(client, time.Second*30)\n\tinform := shared.Apps().V1().Deployments()\n\tcontrl := &Controller{\n\t\tclient: client,\n\t\tinformer: inform.Informer(),\n\t\tlister: inform.Lister(),\n\t\tlogger: logrus.New(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"regitseel\"),\n\t}\n\n\tinform.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: contrl.enqueue,\n\t\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\t\tcontrl.enqueue(new)\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\td := obj.(*appsv1.Deployment)\n\t\t\t\tif err := contrl.delete(d); err != nil {\n\t\t\t\t\tcontrl.logger.Errorf(\"failed to delete from api: %v\", d.Name)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t)\n\n\treturn contrl\n}", "func NewController(settings core.Settings, clock core.Clock, qsoList QSOList, bandmap Bandmap, asyncRunner core.AsyncRunner) *Controller {\n\tresult := &Controller{\n\t\tclock: clock,\n\t\tview: new(nullView),\n\t\tlogbook: new(nullLogbook),\n\t\tcallinfo: new(nullCallinfo),\n\t\tvfo: new(nullVFO),\n\t\tasyncRunner: asyncRunner,\n\t\tqsoList: qsoList,\n\t\tbandmap: bandmap,\n\n\t\tstationCallsign: settings.Station().Callsign.String(),\n\t}\n\tresult.refreshTicker = ticker.New(result.refreshUTC)\n\tresult.updateExchangeFields(settings.Contest())\n\treturn result\n}", "func NewController(repository Repository) Controller {\n\treturn controller{repository: repository}\n}", "func NewController(t mockConstructorTestingTNewController) *Controller {\n\tmock := &Controller{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewController(t mockConstructorTestingTNewController) *Controller {\n\tmock := &Controller{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewController(todoService todo.UseCase) *Controller {\n\treturn &Controller{\n\t\ttodoService: todoService,\n\t}\n}", "func NewController(brigade brigade.Service) Controller {\n\treturn &controller{\n\t\tbrigade: brigade,\n\t}\n}", "func NewController(db *sql.DB) *Controller {\n\treturn &Controller{db: db}\n}", "func New(cfg *config.TrexConfig) *Controller {\n\treturn &Controller{\n\t\tcfg: cfg,\n\t}\n}", "func NewController(app AppInterface) *Controller {\n\tc := new(Controller)\n\n\t// for debug logs\n\t// log.SetLevel(log.DebugLevel)\n\n\t// Save the handler\n\tc.app = app\n\treturn c\n}", "func New(\n\tu UseCase,\n\tlogger *logrus.Logger,\n\tr *render.Render,\n) *Controller {\n\treturn &Controller{u, logger, r}\n}", "func NewController(runner pitr.Runner, cluster cluster.Controller) Controller {\n\treturn Controller{\n\t\trunner: runner,\n\t\tcluster: cluster,\n\t}\n}", "func New(s *service.Service) *Controller {\n\tlogger.Println(\"New controller instance was initialized\")\n\treturn &Controller{\n\t\tservice: s,\n\t}\n}", "func New(ctx context.Context, config *config.ServerConfig, h *render.Renderer) *Controller {\n\tlogger := logging.FromContext(ctx)\n\n\treturn &Controller{\n\t\tconfig: config,\n\t\th: h,\n\t\tlogger: logger,\n\t}\n}", "func NewController() node.Initializer {\n\treturn controller{}\n}", "func NewController(t *testing.T) (*gomock.Controller, context.Context) {\n\tctx := context.Background()\n\treturn gomock.WithContext(ctx, t)\n}", "func NewController(s *SessionInfo, timeout time.Duration) *Controller {\n\tif timeout == 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\trng := rand.New(rand.NewSource(time.Now().UnixNano() + rand.Int63()))\n\treturn &Controller{\n\t\tsessionInfo: s,\n\t\ttimeout: timeout,\n\n\t\tswitches: map[string][]uint32{},\n\t\tswitchIndices: map[string]int{},\n\n\t\tseqID: uint16(rng.Int63()),\n\t}\n}", "func New() *Controller {\n\treturn &Controller{\n\t\tValidatePayload: ValidatePayload,\n\t}\n}", "func NewController(betService BetService) *Controller {\n\treturn &Controller{\n\t\tbetService: betService,\n\t}\n}", "func (m *Module) NewController(name string, constructor interface{}) {\n\ttransformedFunc, err := MakeFuncInjectable(constructor)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tm.Call(\"controller\", name, transformedFunc)\n}", "func NewController() Controller {\n\treturn &controller{\n\t\treservedExpiration: defaultReservedExpiration,\n\t\tquotaMgr: quota.Mgr,\n\t}\n}", "func New(s *store.Store, conf *config.Config) (*Controller, error) {\n\t// init yakeen\n\tyak, err := yakeen.New(conf.Gateway.Token, conf.Gateway.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//init oauth\n\toauth, err := oauth.New(conf.Oauth.Consumers, conf.Oauth.DBPath, conf.Gateway.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//init nic\n\tn, err := nic.New(conf.Nic.CallerID, conf.Gateway.URL, oauth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//init Scfhs\n\tsc, err := scfhs.New(conf.Scfhs.URL, conf.Scfhs.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcont := &Controller{\n\t\tstore: s,\n\t\tyakeen: yak,\n\t\tnic: n,\n\t\tSc: sc,\n\t\tfeatures: conf.Features,\n\t}\n\treturn cont, nil\n}", "func NewController(address string) controller.Controller {\n\treturn &Controller{address, nil}\n}", "func New(client vpnkit.Client, services corev1client.ServicesGetter) *Controller {\n\treturn &Controller{\n\t\tservices: services,\n\t\tclient: client,\n\t}\n}", "func NewController(sessionFinder SessionFinder) Controller {\n\treturn Controller{\n\t\tsessionFinder: sessionFinder,\n\t}\n}", "func NewController(ctx context.Context, keypfx string, cli state.Repository) *Controller {\n\tctx, cancel := context.WithCancel(ctx)\n\tc := &Controller{\n\t\tkeypfx: fmt.Sprintf(\"%s/task-coordinator/%s\", keypfx, version),\n\t\tcli: cli,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tdonec: make(chan struct{}),\n\t}\n\tgo c.run()\n\treturn c\n}", "func NewController(cfg config.KstreamConfig) *Controller {\n\tproviders := []TraceProvider{\n\t\t{\n\t\t\t// core system events\n\t\t\tetw.KernelLoggerSession,\n\t\t\tetw.KernelTraceControlGUID,\n\t\t\t0x0, // no keywords for system provider\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t// supplies the `OpenProcess` and `OpenThread` events\n\t\t\tetw.KernelAuditAPICallsSession,\n\t\t\tetw.KernelAuditAPICallsGUID,\n\t\t\t0x0, // no keywords, so we accept all events\n\t\t\tcfg.EnableAuditAPIEvents,\n\t\t},\n\t\t{\n\t\t\tetw.DNSClientSession,\n\t\t\tetw.DNSClientGUID,\n\t\t\t0x0, // enables DNS query/reply events\n\t\t\tcfg.EnableDNSEvents,\n\t\t},\n\t}\n\tcontroller := &Controller{\n\t\tkstreamConfig: cfg,\n\t\ttraces: make([]TraceSession, 0),\n\t\tproviders: providers,\n\t}\n\treturn controller\n}", "func NewController(logger *log.Logger, storageApiURL string, config resources.UbiquityPluginConfig) (*Controller, error) {\n\n\tremoteClient, err := remote.NewRemoteClient(logger, storageApiURL, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Controller{logger: logger, Client: remoteClient, exec: utils.NewExecutor()}, nil\n}", "func NewController(repository storage.Repository, resourceBaseURL string, objectType types.ObjectType, objectBlueprint func() types.Object) *BaseController {\n\treturn &BaseController{\n\t\trepository: repository,\n\t\tresourceBaseURL: resourceBaseURL,\n\t\tobjectBlueprint: objectBlueprint,\n\t\tobjectType: objectType,\n\t}\n}", "func New(ctx context.Context, config *config.CleanupConfig, db *database.Database, h *render.Renderer) *Controller {\n\tlogger := logging.FromContext(ctx)\n\treturn &Controller{\n\t\tconfig: config,\n\t\tdb: db,\n\t\th: h,\n\t\tlogger: logger,\n\t}\n}", "func NewController(bookmarkservice *services.BookmarkService, bookmarkcategoryservice *services.BookmarkCategoryService, auth *AuthController) *Controller {\n\treturn &Controller{\n\t\tbmsrv: bookmarkservice,\n\t\tauth: auth,\n\t\tbmcsrv: bookmarkcategoryservice,\n\t}\n}", "func NewController(client CopilotClient, store model.ConfigStore, logger logger, timeout, checkInterval time.Duration) *Controller {\n\treturn &Controller{\n\t\tclient: client,\n\t\tstore: store,\n\t\tlogger: logger,\n\t\ttimeout: timeout,\n\t\tcheckInterval: checkInterval,\n\t\tstorage: storage{\n\t\t\tvirtualServices: make(map[string]*model.Config),\n\t\t\tdestinationRules: make(map[string]*model.Config),\n\t\t},\n\t}\n}", "func CreateController(router *gin.RouterGroup, context *appcontext.Context, routeName string, controller ControllerInterface) {\n\tcontroller.SetContext(context)\n\n\t// Definisikan route\n\trouter = router.Group(routeName)\n\tcontroller.SetRoute(router)\n}", "func NewController(\n\texperiment core.ExperimentStore,\n\tevent core.EventStore,\n\tttlc *TTLconfig,\n) *Controller {\n\treturn &Controller{\n\t\texperiment: experiment,\n\t\tevent: event,\n\t\tttlconfig: ttlc,\n\t}\n}", "func NewController(\n\tcontrollerLogger *log.Logger,\n\trenderer *render.Render,\n\tauthPublisher *Publisher,\n\tuserRedis *user.RedisManager,\n) *Controller {\n\treturn &Controller{\n\t\tlogger: controllerLogger,\n\t\trender: renderer,\n\t\tauthPublisher: authPublisher,\n\t\tuserRedis: userRedis,\n\t}\n}", "func NewController(s Service) *ProjectController {\n\treturn &ProjectController{\n\t\tservice: s,\n\t}\n}", "func NewController(ctx context.Context, options *Options, resourceBaseURL string, objectType types.ObjectType, objectBlueprint func() types.Object, supportsCascadeDelete bool) *BaseController {\n\tpoolSize := options.OperationSettings.DefaultPoolSize\n\tfor _, pool := range options.OperationSettings.Pools {\n\t\tif pool.Resource == objectType.String() {\n\t\t\tpoolSize = pool.Size\n\t\t\tbreak\n\t\t}\n\t}\n\tcontroller := &BaseController{\n\t\trepository: options.Repository,\n\t\tresourceBaseURL: resourceBaseURL,\n\t\tobjectBlueprint: objectBlueprint,\n\t\tobjectType: objectType,\n\t\tDefaultPageSize: options.APISettings.DefaultPageSize,\n\t\tMaxPageSize: options.APISettings.MaxPageSize,\n\t\tscheduler: operations.NewScheduler(ctx, options.Repository, options.OperationSettings, poolSize, options.WaitGroup),\n\t\tsupportsCascadeDelete: supportsCascadeDelete,\n\t}\n\n\treturn controller\n}", "func NewController(context *clusterd.Context, containerImage string) *Controller {\n\treturn &Controller{\n\t\tcontext: context,\n\t\tcontainerImage: containerImage,\n\t}\n}", "func New(db *sql.DB) *Controller {\n\treturn &Controller{\n\t\tdb: db,\n\t}\n}", "func New(provider keystore.Provider) *Controller {\n\top := operation.New(provider)\n\thandlers := op.GetRESTHandlers()\n\n\treturn &Controller{handlers: handlers}\n}", "func NewController(betValidator BetValidator, betService BetService) *Controller {\n\treturn &Controller{\n\t\tbetValidator: betValidator,\n\t\tbetService: betService,\n\t}\n}", "func NewController(betValidator BetValidator, betService BetService) *Controller {\n\treturn &Controller{\n\t\tbetValidator: betValidator,\n\t\tbetService: betService,\n\t}\n}", "func New() *Controller {\n\tvar allHandlers []operation.Handler\n\n\trpService := operation.New()\n\n\thandlers := rpService.GetRESTHandlers()\n\n\tallHandlers = append(allHandlers, handlers...)\n\n\treturn &Controller{handlers: allHandlers}\n}", "func NewController(customer customer.Service) *Controller {\n\treturn &Controller{\n\t\tcustomer: customer,\n\t}\n}", "func newController(clusterCfg clusterConfig) (Controller, error) {\n\tcfg := &rest.Config{\n\t\tHost: clusterCfg.Host,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: false,\n\t\t\tCAData: []byte(clusterCfg.CACert),\n\t\t\tCertData: []byte(clusterCfg.ClientCert),\n\t\t\tKeyData: []byte(clusterCfg.ClientKey),\n\t\t},\n\t}\n\n\t// Init the knative serving client\n\tknsClientSet, err := knservingclientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Init the k8s clientset\n\tk8sClientset, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tistioClientSet, err := networkingv1alpha3.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsparkClient, err := sparkclient.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &controller{\n\t\tknServingClient: knsClientSet.ServingV1(),\n\t\tk8sCoreClient: k8sClientset.CoreV1(),\n\t\tk8sAppsClient: k8sClientset.AppsV1(),\n\t\tk8sBatchClient: k8sClientset.BatchV1(),\n\t\tk8sRBACClient: k8sClientset.RbacV1(),\n\t\tk8sSparkOperator: sparkClient.SparkoperatorV1beta2(),\n\t\tistioClient: istioClientSet,\n\t}, nil\n}", "func NewController(cxn *connection.Connection, dryRun bool) *Controller {\n\tctl := &Controller{\n\t\tcxn: cxn,\n\t\tprogress: progressbars.New(),\n\t\tdryRun: dryRun,\n\t}\n\tctl.progress.RefreshRate = 3 * time.Second\n\treturn ctl\n}", "func NewController(namespace string) (*Controller, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(*ClusterURL, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := typedv1.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ns *v1.Namespace\n\tif namespace != \"\" {\n\t\tns, err = clientset.Namespaces().Get(namespace, metav1.GetOptions{})\n\t} else {\n\t\tns, err = createNamespace(clientset)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Controller{\n\t\tclient: clientset,\n\t\tnamespace: ns,\n\t\trestConfig: config,\n\t\tfixedNs: namespace != \"\",\n\t}, nil\n}", "func New(apiEndpoint *url.URL, user, password string, customHTTPClient *http.Client) (c *Controller, err error) {\n\t// handle url\n\tif apiEndpoint == nil {\n\t\terr = errors.New(\"apiEndpoint can't be nil\")\n\t\treturn\n\t}\n\tcopiedURL, err := url.Parse(apiEndpoint.String())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"apiEndpoint can't be (re)parsed as URL: %v\", err) // weird\n\t\treturn\n\t}\n\t// handle http client\n\tif customHTTPClient == nil {\n\t\tcustomHTTPClient = cleanhttp.DefaultPooledClient()\n\t}\n\t// create the cookie jar if needed\n\tif customHTTPClient.Jar == nil {\n\t\tcustomHTTPClient.Jar, err = cookiejar.New(&cookiejar.Options{\n\t\t\tPublicSuffixList: publicsuffix.List,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// spawn the controller\n\tc = &Controller{\n\t\tuser: user,\n\t\tpassword: password,\n\t\turl: copiedURL,\n\t\tclient: customHTTPClient,\n\t}\n\treturn\n}", "func MakeController(datastore datastore.DataStore) (*Controller, error) {\n\n // Check that we can retrieve an inventory from the datastore\n _, error := datastore.GetInventory()\n if error != nil {\n return nil, error\n }\n\n controller := Controller{\n datastore: datastore,\n register: MakeRegister(),\n }\n return &controller, nil\n}", "func NewController(d *CSIDriver) csi.ControllerServer {\n\treturn &controller{\n\t\tdriver: d,\n\t\tcapabilities: newControllerCapabilities(),\n\t}\n}", "func NewController(addr, name string) *Controller {\n\tchatroom := NewRoom()\n\tcontroller := &Controller{\n\t\t&ownPeer{addr, name},\n\t\tNewConnHandler(addr, name, chatroom),\n\t\tchatroom,\n\t\tnewChatWindow(),\n\t\tmake([]rune, 0),\n\t\tmake(chan bool),\n\t}\n\treturn controller\n}", "func (c *Config) NewController(e *env.Env) *Controller {\n\tctl := NewController(e)\n\tctl.DeviceIndex = c.DeviceIndex\n\tctl.Verbose = c.Verbose\n\treturn ctl\n}", "func NewController(\n\tcontrollerLogger *log.Logger,\n\trenderer *render.Render,\n\tuserRedisManager *user.RedisManager,\n\tcategoryRedisManager *RedisManager,\n\tcategoryPublisher *Publisher,\n) *Controller {\n\treturn &Controller{\n\t\tlogger: controllerLogger,\n\t\trender: renderer,\n\t\tuserRedis: userRedisManager,\n\t\tcategoryRedis: categoryRedisManager,\n\t\tcategoryPublisher: categoryPublisher,\n\t}\n}", "func (app *Application) NewController(resource *Resource) *Controller {\n\tc := &Controller{\n\t\tresource: resource,\n\t\tcustomHandlers: make(map[route]handlerChain),\n\t}\n\n\tapp.controllers[c.resource] = c\n\treturn c\n}", "func NewController(commandBus command.Bus) Controller {\n\treturn &controllerImplement{commandBus}\n}", "func (app *Application) NewCRUDController(resource *Resource) *Controller {\n\tc := app.NewController(resource)\n\tc.SetIndexHandler(NewIndexAction())\n\tc.SetShowHandler(NewShowAction())\n\tc.SetCreateHandler(NewCreateAction())\n\tc.SetUpdateHandler(NewUpdateAction())\n\tc.SetDeleteHandler(NewDeleteAction())\n\treturn c\n}", "func NewController() *Controller {\n\treturn &Controller{\n\t\tstats: tabletenv.NewStats(servenv.NewExporter(\"MockController\", \"Tablet\")),\n\t\tqueryServiceEnabled: false,\n\t\tBroadcastData: make(chan *BroadcastData, 10),\n\t\tStateChanges: make(chan *StateChange, 10),\n\t\tqueryRulesMap: make(map[string]*rules.Rules),\n\t}\n}", "func NewController(\n\topt controller.Options,\n\tnotifications chan struct{},\n\tserviceInformer servinginformers.ServiceInformer,\n) *Controller {\n\tlogger, _ := zap.NewProduction()\n\topt.Logger = logger.Sugar()\n\tc := &Controller{\n\t\tBase: controller.NewBase(opt, controllerAgentName, \"Services\"),\n\t}\n\n\tc.Logger.Info(\"Setting up event handlers\")\n\tserviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.Enqueue,\n\t\tUpdateFunc: controller.PassNew(c.Enqueue),\n\t\tDeleteFunc: c.Enqueue,\n\t})\n\n\treturn c\n}", "func NewController(region string, networkManager *NetworkManager, playerManager *PlayerManager, firebase *triebwerk.Firebase, masterServer MasterServerClient) *Controller {\n\treturn &Controller{\n\t\tnetworkManager: networkManager,\n\t\tplayerManager: playerManager,\n\t\tstate: model.NewGameState(region),\n\t\tfirebase: firebase,\n\t\tmasterServer: masterServer,\n\t}\n}", "func NewController(le *logrus.Entry, bus bus.Bus, conf *Config) (*Controller, error) {\n\tdir := path.Clean(conf.GetDir())\n\tif _, err := os.Stat(dir); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"stat %s\", dir)\n\t}\n\treturn &Controller{\n\t\tle: le,\n\t\tbus: bus,\n\t\tdir: dir,\n\n\t\twatch: conf.GetWatch(),\n\t}, nil\n}", "func NewController(ctx context.Context, clientMap clientmap.ClientMap) (*Controller, error) {\n\tgardenClient, err := clientMap.GetClient(ctx, keys.ForGarden())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbackupBucketInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.BackupBucket{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get BackupBucket Informer: %w\", err)\n\t}\n\tbackupEntryInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.BackupEntry{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get BackupEntry Informer: %w\", err)\n\t}\n\tcontrollerDeploymentInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.ControllerDeployment{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get ControllerDeployment Informer: %w\", err)\n\t}\n\tcontrollerInstallationInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.ControllerInstallation{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get ControllerInstallation Informer: %w\", err)\n\t}\n\tcontrollerRegistrationInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.ControllerRegistration{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get ControllerRegistration Informer: %w\", err)\n\t}\n\tseedInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.Seed{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get Seed Informer: %w\", err)\n\t}\n\tshootInformer, err := gardenClient.Cache().GetInformer(ctx, &gardencorev1beta1.Shoot{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get Shoot Informer: %w\", err)\n\t}\n\n\tcontroller := &Controller{\n\t\tgardenClient: gardenClient.Client(),\n\n\t\tcontrollerRegistrationReconciler: NewControllerRegistrationReconciler(logger.Logger, gardenClient.Client()),\n\t\tcontrollerRegistrationSeedReconciler: NewControllerRegistrationSeedReconciler(logger.Logger, gardenClient),\n\t\tseedReconciler: NewSeedReconciler(logger.Logger, gardenClient.Client()),\n\n\t\tcontrollerRegistrationQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"controllerregistration\"),\n\t\tcontrollerRegistrationSeedQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"controllerregistration-seed\"),\n\t\tseedQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"seed\"),\n\t\tworkerCh: make(chan int),\n\t}\n\n\tbackupBucketInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.backupBucketAdd,\n\t\tUpdateFunc: controller.backupBucketUpdate,\n\t\tDeleteFunc: controller.backupBucketDelete,\n\t})\n\n\tbackupEntryInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.backupEntryAdd,\n\t\tUpdateFunc: controller.backupEntryUpdate,\n\t\tDeleteFunc: controller.backupEntryDelete,\n\t})\n\n\tcontrollerRegistrationInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) { controller.controllerRegistrationAdd(ctx, obj) },\n\t\tUpdateFunc: func(oldObj, newObj interface{}) { controller.controllerRegistrationUpdate(ctx, oldObj, newObj) },\n\t\tDeleteFunc: controller.controllerRegistrationDelete,\n\t})\n\n\tcontrollerDeploymentInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) { controller.controllerDeploymentAdd(ctx, obj) },\n\t\tUpdateFunc: func(oldObj, newObj interface{}) { controller.controllerDeploymentUpdate(ctx, oldObj, newObj) },\n\t})\n\n\tcontrollerInstallationInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.controllerInstallationAdd,\n\t\tUpdateFunc: controller.controllerInstallationUpdate,\n\t})\n\n\tseedInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) { controller.seedAdd(obj, true) },\n\t\tUpdateFunc: controller.seedUpdate,\n\t\tDeleteFunc: controller.seedDelete,\n\t})\n\n\tshootInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.shootAdd,\n\t\tUpdateFunc: controller.shootUpdate,\n\t\tDeleteFunc: controller.shootDelete,\n\t})\n\n\tcontroller.hasSyncedFuncs = append(controller.hasSyncedFuncs,\n\t\tbackupBucketInformer.HasSynced,\n\t\tbackupEntryInformer.HasSynced,\n\t\tcontrollerRegistrationInformer.HasSynced,\n\t\tcontrollerDeploymentInformer.HasSynced,\n\t\tcontrollerInstallationInformer.HasSynced,\n\t\tseedInformer.HasSynced,\n\t\tshootInformer.HasSynced,\n\t)\n\n\treturn controller, nil\n}", "func NewController(\n\tchopClient chopClientSet.Interface,\n\textClient apiExtensions.Interface,\n\tkubeClient kube.Interface,\n\tchopInformerFactory chopInformers.SharedInformerFactory,\n\tkubeInformerFactory kubeInformers.SharedInformerFactory,\n) *Controller {\n\n\t// Initializations\n\t_ = chopClientSetScheme.AddToScheme(scheme.Scheme)\n\n\t// Setup events\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(log.Info)\n\teventBroadcaster.StartRecordingToSink(\n\t\t&typedCoreV1.EventSinkImpl{\n\t\t\tInterface: kubeClient.CoreV1().Events(\"\"),\n\t\t},\n\t)\n\trecorder := eventBroadcaster.NewRecorder(\n\t\tscheme.Scheme,\n\t\tcoreV1.EventSource{\n\t\t\tComponent: componentName,\n\t\t},\n\t)\n\n\t// Create Controller instance\n\tcontroller := &Controller{\n\t\tkubeClient: kubeClient,\n\t\textClient: extClient,\n\t\tchopClient: chopClient,\n\t\tchiLister: chopInformerFactory.Clickhouse().V1().ClickHouseInstallations().Lister(),\n\t\tchiListerSynced: chopInformerFactory.Clickhouse().V1().ClickHouseInstallations().Informer().HasSynced,\n\t\tchitLister: chopInformerFactory.Clickhouse().V1().ClickHouseInstallationTemplates().Lister(),\n\t\tchitListerSynced: chopInformerFactory.Clickhouse().V1().ClickHouseInstallationTemplates().Informer().HasSynced,\n\t\tserviceLister: kubeInformerFactory.Core().V1().Services().Lister(),\n\t\tserviceListerSynced: kubeInformerFactory.Core().V1().Services().Informer().HasSynced,\n\t\tendpointsLister: kubeInformerFactory.Core().V1().Endpoints().Lister(),\n\t\tendpointsListerSynced: kubeInformerFactory.Core().V1().Endpoints().Informer().HasSynced,\n\t\tconfigMapLister: kubeInformerFactory.Core().V1().ConfigMaps().Lister(),\n\t\tconfigMapListerSynced: kubeInformerFactory.Core().V1().ConfigMaps().Informer().HasSynced,\n\t\tstatefulSetLister: kubeInformerFactory.Apps().V1().StatefulSets().Lister(),\n\t\tstatefulSetListerSynced: kubeInformerFactory.Apps().V1().StatefulSets().Informer().HasSynced,\n\t\tpodLister: kubeInformerFactory.Core().V1().Pods().Lister(),\n\t\tpodListerSynced: kubeInformerFactory.Core().V1().Pods().Informer().HasSynced,\n\t\trecorder: recorder,\n\t}\n\tcontroller.initQueues()\n\tcontroller.addEventHandlers(chopInformerFactory, kubeInformerFactory)\n\n\treturn controller\n}", "func NewController(cfg configuration.Controller, extractor interfaces.JetDropsExtractor, storage interfaces.Storage, pv int) (*Controller, error) {\n\tc := &Controller{\n\t\tcfg: cfg,\n\t\textractor: extractor,\n\t\tstorage: storage,\n\t\tjetDropRegister: make(map[types.Pulse]map[string]struct{}),\n\t\tmissedDataManager: NewMissedDataManager(time.Second*time.Duration(cfg.ReloadPeriod), time.Second*time.Duration(cfg.ReloadCleanPeriod)),\n\t\tplatformVersion: pv,\n\t}\n\treturn c, nil\n}", "func (t tApp) New(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\tc := &contr.App{}\n\tc.Controllers = Controllers.New(w, r, ctr, act)\n\treturn c\n}", "func NewController(ctx context.Context, router *Router) *controller.Impl {\n\tlogger := logging.FromContext(ctx)\n\n\tr := &Reconciler{\n\t\tkubeClientSet: kubeclient.Get(ctx),\n\t\trouter: router,\n\t}\n\n\timpl := githubsourcereconciler.NewImpl(ctx, r)\n\n\tlogger.Info(\"Setting up event handlers\")\n\n\t// Watch for githubsource objects\n\tgithubsourceInformer := githubsourceinformer.Get(ctx)\n\tgithubsourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))\n\n\treturn impl\n}", "func NewController(informer cache.SharedIndexInformer, conf *config.Config, defaultClient client.ValiClient,\n\tlogger log.Logger) (Controller, error) {\n\tcontroller := &controller{\n\t\tclients: make(map[string]ControllerClient, expectedActiveClusters),\n\t\tconf: conf,\n\t\tdefaultClient: defaultClient,\n\t\tlogger: logger,\n\t}\n\n\tinformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.addFunc,\n\t\tDeleteFunc: controller.delFunc,\n\t\tUpdateFunc: controller.updateFunc,\n\t})\n\n\tstopChan := make(chan struct{})\n\ttime.AfterFunc(conf.ControllerConfig.CtlSyncTimeout, func() {\n\t\tclose(stopChan)\n\t})\n\n\tif !cache.WaitForCacheSync(stopChan, informer.HasSynced) {\n\t\treturn nil, fmt.Errorf(\"failed to wait for caches to sync\")\n\t}\n\n\treturn controller, nil\n}", "func New(\n\troute *gin.Engine,\n\tcommandBus *command.Bus,\n\tqueryBus *query.Bus,\n\tutil *util.Util,\n\tapi api.Interface,\n) *Controller {\n\tcontroller := &Controller{\n\t\troute: route,\n\t\tcommandBus: commandBus,\n\t\tqueryBus: queryBus,\n\t\tutil: util,\n\t\tapi: api,\n\t}\n\tcontroller.SetupRoutes()\n\treturn controller\n}", "func NewController(stop chan struct{}) *Controller {\n\tk8sClient := util.Clientset()\n\tk8sFactory := informers.NewSharedInformerFactory(k8sClient, time.Minute*informerSyncMinute)\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(glog.Infof)\n\teventBroadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: k8sClient.CoreV1().Events(\"\")})\n\n\tcontroller := &Controller{\n\t\tstopCh: make(chan struct{}),\n\t\tStop: stop,\n\t\tk8sFactory: k8sFactory,\n\t\tpodLister: k8sFactory.Core().V1().Pods().Lister(),\n\t\teventAddedCh: make(chan *core.Event),\n\t\teventUpdatedCh: make(chan *eventUpdateGroup),\n\t\trecorder: eventBroadcaster.NewRecorder(scheme.Scheme, core.EventSource{Component: \"oom-event-generator\"}),\n\t\tstartTime: time.Now(),\n\t}\n\n\teventsInformer := informers.SharedInformerFactory(k8sFactory).Core().V1().Events().Informer()\n\teventsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tcontroller.eventAddedCh <- obj.(*core.Event)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tcontroller.eventUpdatedCh <- &eventUpdateGroup{\n\t\t\t\toldEvent: oldObj.(*core.Event),\n\t\t\t\tnewEvent: newObj.(*core.Event),\n\t\t\t}\n\t\t},\n\t})\n\n\treturn controller\n}", "func NewController(clientset kubernetes.Interface, namespaceInformer coreinformers.NamespaceInformer) *Controller {\n\tsystemNamespaces := []string{metav1.NamespaceSystem, metav1.NamespacePublic, v1.NamespaceNodeLease, metav1.NamespaceDefault}\n\tinterval := 1 * time.Minute\n\n\treturn &Controller{\n\t\tclient: clientset,\n\t\tnamespaceLister: namespaceInformer.Lister(),\n\t\tnamespaceSynced: namespaceInformer.Informer().HasSynced,\n\t\tsystemNamespaces: systemNamespaces,\n\t\tinterval: interval,\n\t}\n}", "func newHelloController(helloService HelloService) *helloController {\n\treturn &helloController{\n\t\thelloService: helloService,\n\t}\n}", "func NewController(client *k8s.KubeClient, nodeID string, serviceClient api.DriveServiceClient, eventRecorder *events.Recorder, log *logrus.Logger) *Controller {\n\treturn &Controller{\n\t\tclient: client,\n\t\tcrHelper: k8s.NewCRHelper(client, log),\n\t\tnodeID: nodeID,\n\t\tdriveMgrClient: serviceClient,\n\t\teventRecorder: eventRecorder,\n\t\tlog: log.WithField(\"component\", \"Controller\"),\n\t}\n}", "func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl {\n\tsubscriptionInformer := subscriptioninformersv1alpha1.Get(ctx)\n\teventActivationInformer := eventactivationinformersv1alpha1.Get(ctx)\n\tknativeLib, err := util.NewKnativeLib()\n\tif err != nil {\n\t\tpanic(\"Failed to initialize knative lib\")\n\t}\n\tStatsReporter, err := NewStatsReporter()\n\tif err != nil {\n\t\tpanic(\"Failed to Kyma Subscription Controller stats reporter\")\n\t}\n\n\tr := &Reconciler{\n\t\tBase: reconciler.NewBase(ctx, controllerAgentName, cmw),\n\t\tsubscriptionLister: subscriptionInformer.Lister(),\n\t\teventActivationLister: eventActivationInformer.Lister(),\n\t\tkymaEventingClient: eventbusclient.Get(ctx).EventingV1alpha1(),\n\t\tknativeLib: knativeLib,\n\t\topts: opts.DefaultOptions(),\n\t\ttime: util.NewDefaultCurrentTime(),\n\t\tStatsReporter: StatsReporter,\n\t}\n\timpl := controller.NewImpl(r, r.Logger, reconcilerName)\n\n\tsubscriptionInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))\n\n\tregisterMetrics()\n\n\treturn impl\n}", "func NewController(factory k8s.ClientFactory) *Controller {\n\tpipelineRunInformer := factory.StewardInformerFactory().Steward().V1alpha1().PipelineRuns()\n\tpipelineRunLister := pipelineRunInformer.Lister()\n\tpipelineRunFetcher := k8s.NewListerBasedPipelineRunFetcher(pipelineRunInformer.Lister())\n\ttektonTaskRunInformer := factory.TektonInformerFactory().Tekton().V1beta1().TaskRuns()\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.V(3).Infof)\n\teventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: factory.CoreV1().Events(\"\")})\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"runController\"})\n\n\tcontroller := &Controller{\n\t\tfactory: factory,\n\t\tpipelineRunFetcher: pipelineRunFetcher,\n\t\tpipelineRunLister: pipelineRunLister,\n\t\tpipelineRunSynced: pipelineRunInformer.Informer().HasSynced,\n\n\t\ttektonTaskRunsSynced: tektonTaskRunInformer.Informer().HasSynced,\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), metrics.WorkqueueName),\n\t\trecorder: recorder,\n\t\tpipelineRunStore: pipelineRunInformer.Informer().GetStore(),\n\t}\n\tpipelineRunInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.addPipelineRun,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tcontroller.addPipelineRun(new)\n\t\t},\n\t})\n\ttektonTaskRunInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.handleTektonTaskRun,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tcontroller.handleTektonTaskRun(new)\n\t\t},\n\t})\n\n\treturn controller\n}", "func New(\n\troute *gin.Engine,\n\tcommandBus *command.Bus,\n\tqueryBus *query.Bus,\n\tutil *util.Util,\n\tconfig config.Interface,\n\tapi api.Interface,\n) *Controller {\n\tcontroller := &Controller{\n\t\troute: route,\n\t\tcommandBus: commandBus,\n\t\tqueryBus: queryBus,\n\t\tutil: util,\n\t\tconfig: config,\n\t\tapi: api,\n\t}\n\tcontroller.SetupRoutes()\n\treturn controller\n}", "func NewController(\n\tcontrollerName string,\n\tinstallStrategy InstallStrategy,\n\tplaybooks []string,\n\tclusterInformer capiinformers.ClusterInformer,\n\tmachineSetInformer capiinformers.MachineSetInformer,\n\tjobInformer batchinformers.JobInformer,\n\tkubeClient kubeclientset.Interface,\n\tclustopClient clustopclientset.Interface,\n\tcapiClient capiclientset.Interface,\n) *Controller {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(glog.Infof)\n\t// TODO: remove the wrapper when every clients have moved to use the clientset.\n\teventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(kubeClient.CoreV1().RESTClient()).Events(\"\")})\n\n\tif kubeClient != nil && kubeClient.CoreV1().RESTClient().GetRateLimiter() != nil {\n\t\tmetrics.RegisterMetricAndTrackRateLimiterUsage(\n\t\t\tfmt.Sprintf(\"clusteroperator_%s_controller\", controllerName),\n\t\t\tkubeClient.CoreV1().RESTClient().GetRateLimiter(),\n\t\t)\n\t}\n\n\tlogger := log.WithField(\"controller\", controllerName)\n\n\tc := &Controller{\n\t\tcontrollerName: controllerName,\n\t\tinstallStrategy: installStrategy,\n\t\tplaybooks: playbooks,\n\t\tclustopClient: clustopClient,\n\t\tcapiClient: capiClient,\n\t\tkubeClient: kubeClient,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), controllerName),\n\t\tLogger: logger,\n\t\tclusterLister: clusterInformer.Lister(),\n\t\tmachineSetLister: machineSetInformer.Lister(),\n\t\tclustersSynced: clusterInformer.Informer().HasSynced,\n\t\tmachineSetsSynced: machineSetInformer.Informer().HasSynced,\n\t}\n\n\tclusterInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCluster,\n\t\tUpdateFunc: c.updateCluster,\n\t\tDeleteFunc: c.deleteCluster,\n\t})\n\tmachineSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addMachineSet,\n\t\tUpdateFunc: c.updateMachineSet,\n\t\tDeleteFunc: c.deleteMachineSet,\n\t})\n\n\tjobOwnerControl := &jobOwnerControl{controller: c}\n\tc.jobControl = controller.NewJobControl(controllerName, clusterKind, kubeClient, jobInformer.Lister(), jobOwnerControl, logger)\n\tjobInformer.Informer().AddEventHandler(c.jobControl)\n\tc.jobsSynced = jobInformer.Informer().HasSynced\n\n\tsyncStrategy := (controller.JobSyncStrategy)(&jobSyncStrategy{controller: c})\n\tif _, shouldReprocessJobs := installStrategy.(controller.JobSyncReprocessStrategy); shouldReprocessJobs {\n\t\tsyncStrategy = &jobSyncWithReprocessStrategy{&jobSyncStrategy{controller: c}}\n\t}\n\tc.jobSync = controller.NewJobSync(c.jobControl, syncStrategy, false, logger)\n\n\tc.syncHandler = c.jobSync.Sync\n\tc.enqueueCluster = c.enqueue\n\tc.ansibleGenerator = ansible.NewJobGenerator()\n\n\treturn c\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tblobMgr: blob.Mgr,\n\t\tblobSizeExpiration: time.Hour * 24, // keep the size of blob in redis with 24 hours\n\t}\n}" ]
[ "0.8268421", "0.76750875", "0.76736444", "0.75587475", "0.7557911", "0.75288594", "0.7517306", "0.75066286", "0.74756855", "0.74221504", "0.7381676", "0.7372851", "0.7335539", "0.7329626", "0.7297026", "0.72962", "0.72910386", "0.728513", "0.72847664", "0.72808325", "0.7277432", "0.72721666", "0.72687143", "0.7256995", "0.7225203", "0.7225074", "0.72192377", "0.721466", "0.721466", "0.72137755", "0.71738935", "0.7173381", "0.7137028", "0.7098262", "0.7073387", "0.706922", "0.70575446", "0.70562774", "0.7045889", "0.70378536", "0.70293176", "0.70242715", "0.6997071", "0.6983235", "0.69826734", "0.69628614", "0.6959585", "0.6938013", "0.69339436", "0.6929018", "0.69206905", "0.6907861", "0.6893985", "0.6886228", "0.6884144", "0.6880875", "0.68687546", "0.6858262", "0.6843852", "0.68306774", "0.6822728", "0.68174464", "0.6813205", "0.6812394", "0.68059576", "0.68059576", "0.67921156", "0.67671555", "0.67446953", "0.67364347", "0.67335206", "0.67305106", "0.6729946", "0.67266524", "0.67087656", "0.67037475", "0.66988134", "0.66912746", "0.66725314", "0.66527927", "0.6652524", "0.6638631", "0.66375995", "0.662633", "0.66225505", "0.6595032", "0.65948945", "0.6590515", "0.6579064", "0.6573264", "0.6566433", "0.656639", "0.65641195", "0.65251833", "0.6513039", "0.6511022", "0.65021795", "0.6495963", "0.64800036", "0.64756006" ]
0.67023987
76
Run will list and watch the resources and then process them.
func (c *SimpleController) Run(stopper <-chan struct{}) error { defer runtime.HandleCrash() defer c.queue.ShutDown() fmt.Println(c.cfg.Name, " Starts...") go c.informer.Run(stopper) if !cache.WaitForCacheSync(stopper, c.informer.HasSynced) { runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync")) return nil } for i := 0; i < c.cfg.ConcurrentWorkers; i++ { go wait.Until(c.runWorker, time.Second, stopper) } <-stopper fmt.Printf("Stopping controller") return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *client) Run() {\n\tstream, err := c.client.ListAndWatch(context.Background(), &api.Empty{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListAndWatch ended unexpectedly for device plugin\", \"resource\", c.resource)\n\t\treturn\n\t}\n\n\tfor {\n\t\tresponse, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"ListAndWatch ended unexpectedly for device plugin\", \"resource\", c.resource)\n\t\t\treturn\n\t\t}\n\t\tklog.V(2).InfoS(\"State pushed for device plugin\", \"resource\", c.resource, \"resourceCapacity\", len(response.Devices))\n\t\tc.handler.PluginListAndWatchReceiver(c.resource, response)\n\t}\n}", "func (s *Service) Run(ctx context.Context) {\n\tdefer close(s.toAdd)\n\tdefer close(s.toRemove)\n\n\trunning.WithBackOff(\n\t\tctx,\n\t\ts.log,\n\t\t\"asset-watcher\",\n\t\ts.processAllAssetsOnce,\n\t\t20*time.Second,\n\t\t30*time.Second,\n\t\t5*time.Minute,\n\t)\n}", "func (mgr *WatcherManager) Run(stopCh <-chan struct{}) {\n\t// run normal resource watchers.\n\tfor resourceName, watcher := range mgr.watchers {\n\t\tglog.Infof(\"watcher manager, start list-watcher[%+v]\", resourceName)\n\t\tgo watcher.Run(stopCh)\n\t}\n\n\tif !mgr.watchResource.DisableNetservice {\n\t\t// run netservice watcher.\n\t\tgo mgr.netserviceWatcher.Run(stopCh)\n\t}\n\n\t// synchronizer run once\n\tvar count = 0\n\tfor {\n\t\tif count >= 5 {\n\t\t\tpanic(\"synchronizer run failed\")\n\t\t}\n\t\tif err := mgr.synchronizer.RunOnce(); err != nil {\n\t\t\tglog.Errorf(\"synchronizer sync failed: %v\", err)\n\t\t\ttime.Sleep(5 * time.Minute)\n\t\t} else {\n\t\t\tglog.Infof(\"synchronizer sync done.\")\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t}\n}", "func (c *Controller) Run(stop <-chan struct{}) {\n\t// Catch crash and log an error.\n\tdefer runtime.HandleCrash()\n\t// Shutdown after all goroutines have finished handling\n\t// existing items.\n\tdefer c.queue.ShutDown()\n\n\t// Start listing and watching resource changes.\n\tgo c.informer.Run(stop)\n\n\t// Do a cache sync.\n\tif !cache.WaitForCacheSync(stop, c.HasSynced) {\n\t\truntime.HandleError(fmt.Errorf(\"error syncing cached\"))\n\t\treturn\n\t}\n\n\twait.Until(c.runWorker, time.Second, stop)\n}", "func Run(done chan error, mgr manager.Manager, watchesPath string) {\n\twatches, err := runner.NewFromWatches(watchesPath)\n\tif err != nil {\n\t\tlogrus.Error(\"Failed to get watches\")\n\t\tdone <- err\n\t\treturn\n\t}\n\trand.Seed(time.Now().Unix())\n\tc := signals.SetupSignalHandler()\n\n\tfor gvk, runner := range watches {\n\t\tcontroller.Add(mgr, controller.Options{\n\t\t\tGVK: gvk,\n\t\t\tRunner: runner,\n\t\t})\n\t}\n\tdone <- mgr.Start(c)\n}", "func Run(ctx context.Context, namespace string, clientset *kubernetes.Clientset) error {\n\n\tadded, removed, err := Watch(ctx, clientset.CoreV1().Pods(namespace), regexp.MustCompile(\".*\"), regexp.MustCompile(\".*\"), RUNNING, labels.Everything())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set up watch: %v\", err)\n\t}\n\n\ttails := make(map[string]*Tail)\n\n\tgo func() {\n\t\tfor p := range added {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttail := NewTail(p.Namespace, p.Pod, p.Container)\n\t\t\ttails[id] = tail\n\n\t\t\ttail.Start(ctx, clientset.CoreV1().Pods(p.Namespace))\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor p := range removed {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttails[id].Close()\n\t\t\tdelete(tails, id)\n\t\t}\n\t}()\n\n\t<-ctx.Done()\n\n\treturn nil\n}", "func (q *Queue) Run(w http.ResponseWriter, req *http.Request) {\n\tfor _, f := range q.list {\n\t\tif w, req = f(w, req); req == nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *Reflector) Run() {\n\tgo wait.Until(func() { r.ListAndWatch(wait.NeverStop) }, r.period, wait.NeverStop)\n}", "func (c *AnalyticsController) runWatches() {\n\tlastResourceVersion := big.NewInt(0)\n\tcurrentResourceVersion := big.NewInt(0)\n\twatchListItems := WatchFuncList(c.kclient, c.client)\n\tfor name := range watchListItems {\n\n\t\t// assign local variable (not in range operator above) so that each\n\t\t// goroutine gets the correct watch function required\n\t\twfnc := watchListItems[name]\n\t\tn := name\n\t\tbackoff := 1 * time.Second\n\n\t\tgo wait.Until(func() {\n\t\t\t// any return from this func only exits that invocation of the func.\n\t\t\t// wait.Until will call it again after its sync period.\n\t\t\twatchLog := log.WithFields(log.Fields{\n\t\t\t\t\"watch\": n,\n\t\t\t})\n\t\t\twatchLog.Infof(\"starting watch\")\n\t\t\tw, err := wfnc.watchFunc(metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\twatchLog.Errorf(\"error creating watch: %v\", err)\n\t\t\t}\n\n\t\t\twatchLog.Debugf(\"backing off watch for %v seconds\", backoff)\n\t\t\ttime.Sleep(backoff)\n\t\t\tbackoff = backoff * 2\n\t\t\tif backoff > 60*time.Second {\n\t\t\t\tbackoff = 60 * time.Second\n\t\t\t}\n\n\t\t\tif w == nil {\n\t\t\t\twatchLog.Errorln(\"watch function nil, watch not created, returning\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase event, ok := <-w.ResultChan():\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\twatchLog.Warnln(\"watch channel closed unexpectedly, attempting to re-establish\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tif event.Type == watch.Error {\n\t\t\t\t\t\twatchLog.Errorf(\"watch channel returned error: %s\", spew.Sdump(event))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// success means the watch is working.\n\t\t\t\t\t// reset the backoff back to 1s for this watch\n\t\t\t\t\tbackoff = 1 * time.Second\n\n\t\t\t\t\tif event.Type == watch.Added || event.Type == watch.Deleted {\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\twatchLog.Errorf(\"Unable to create object meta for %v: %v\", event.Object, err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tm, err := meta.Accessor(event.Object)\n\t\t\t\t\t\t// if both resource versions can be converted to numbers\n\t\t\t\t\t\t// and if the current resource version is lower than the\n\t\t\t\t\t\t// last recorded resource version for this resource type\n\t\t\t\t\t\t// then skip the event\n\t\t\t\t\t\tc.mutex.RLock()\n\t\t\t\t\t\tif _, ok := lastResourceVersion.SetString(c.watchResourceVersions[n], 10); ok {\n\t\t\t\t\t\t\tif _, ok = currentResourceVersion.SetString(m.GetResourceVersion(), 10); ok {\n\t\t\t\t\t\t\t\tif lastResourceVersion.Cmp(currentResourceVersion) == 1 {\n\t\t\t\t\t\t\t\t\twatchLog.Debugf(\"ResourceVersion %v is to old (%v)\",\n\t\t\t\t\t\t\t\t\t\tcurrentResourceVersion, c.watchResourceVersions[n])\n\t\t\t\t\t\t\t\t\tc.mutex.RUnlock()\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc.mutex.RUnlock()\n\n\t\t\t\t\t\t// each watch is a separate go routine\n\t\t\t\t\t\tc.mutex.Lock()\n\t\t\t\t\t\tc.watchResourceVersions[n] = m.GetResourceVersion()\n\t\t\t\t\t\tc.mutex.Unlock()\n\n\t\t\t\t\t\tanalytic, err := newEvent(c.typer, event.Object, event.Type)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\twatchLog.Errorf(\"unexpected error creating analytic from watch event %#v\", event.Object)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// additional info will be set to the analytic and\n\t\t\t\t\t\t\t// an instance queued for all destinations\n\t\t\t\t\t\t\terr := c.AddEvent(analytic)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\twatchLog.Errorf(\"error adding event: %v - %v\", err, analytic)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1*time.Millisecond, c.stopChannel)\n\t}\n}", "func Run(log *util.Logger, httpd webServer, outChan chan<- util.Param) {\n\tu := &watch{\n\t\tlog: log,\n\t\toutChan: outChan,\n\t\trepo: NewRepo(log, owner, repository),\n\t}\n\n\tc := make(chan *github.RepositoryRelease, 1)\n\tgo u.watchReleases(server.Version, c) // endless\n\n\tfor rel := range c {\n\t\tu.Send(\"availableVersion\", *rel.TagName)\n\t}\n}", "func main() {\n\t// read a bunch of urls from the file \"urls.txt\" from the current directory\n\t// create a data slice of []strings\n\turls := []string{}\n file, err := os.Open(\"urls.txt\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close()\n\n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n line := scanner.Text()\n urls = append(urls, line)\n }\n\t// Create our input and output channels, with *Resoruces. Pending is for Poll to check status, while complete, as the name suggest is you're done with the Resource\n\t// The channels provide the means of communication between the main, Poller, and StateMonitor goroutines.\n\tpending, complete := make(chan *Resource), make(chan *Resource)\n\t// Launch the StateMonitor, with its goroutine, and its return value of status channel is saved and used in the Poller\n\t// the argument to StateMonitor is the constant time interval defined above.\n\tstatus := StateMonitor(statusInterval)\n\t// Launch some Poller goroutines. Ths is the where the Pollers do their job. It passes the necessary channels it\n\t// needs for sharing *Resouce. Note again, share memory by communicaitng. \n\tfor i := 0; i < numPollers; i++ {\n\t\tgo Poller(pending, complete, status)\n\t}\n\n\t// Send some Resources to the pending queue.\n\tgo func() {\n\t\tfor _, url := range urls {\n\t\t\tpending <- &Resource{url: url}\n\t\t}\n\t}()\n\n\tfor r := range complete {\n\t\tgo r.Sleep(pending)\n\t}\n}", "func (s *SubscriptionWatcher) Run(ctx context.Context) error {\n\tvar wg sync.WaitGroup\n\tdone := make(chan struct{})\n\tout := make(chan ResourceAudits)\n\n\t// setup worker pool\n\t// workers receive jobs and send results to output channel\n\tworkers := make(map[schema.ContentType]chan ResourceSubscription)\n\tcontentTypes := schema.GetContentTypes()\n\n\twg.Add(len(contentTypes))\n\tfor _, ct := range contentTypes {\n\t\ts.logger.WithField(\"content-type\", ct.String()).Info(\"starting worker\")\n\t\tch := make(chan ResourceSubscription, 1)\n\t\tworkers[ct] = ch\n\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor res := range ch {\n\t\t\t\tcontentCh := s.fetchContent(ctx, done, res)\n\t\t\t\tauditCh := s.fetchAudits(ctx, done, contentCh)\n\n\t\t\t\tfor a := range auditCh {\n\t\t\t\t\tout <- a\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// this goroutine is responsible for closing output channel\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\n\t// setup ticker that will periodically fetch subscriptions\n\t// and create jobs for workers.\n\t// this goroutine is responsible for closing worker channels\n\tgo func() {\n\t\ttickerDur := time.Duration(s.config.TickerIntervalSeconds) * time.Second\n\t\tticker := time.NewTicker(tickerDur)\n\t\tdefer ticker.Stop()\n\n\t\ts.logger.Infoln(\"start main\")\n\t\ts.logger.Infof(\"using config: %+v\", s.config)\n\n\t\tfetch := func(t time.Time) {\n\t\t\tsubCh := s.fetchSubscriptions(ctx, done, t)\n\t\t\tfor sub := range subCh {\n\t\t\t\tctLogger := s.logger.WithField(\"content-type\", sub.ContentType.String())\n\t\t\t\tworkerCh, ok := workers[*sub.ContentType]\n\t\t\t\tif !ok {\n\t\t\t\t\tctLogger.Error(\"no worker registered for content-type\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tdefault:\n\t\t\t\t\tctLogger.Warn(\"worker is busy, skipping\")\n\t\t\t\tcase workerCh <- sub:\n\t\t\t\t\tctLogger.Debugln(\"sent work\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfetch(time.Now())\n\tLoop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\tfor ct, workerCh := range workers {\n\t\t\t\t\ts.logger.WithField(\"content-type\", ct.String()).Info(\"closing worker\")\n\t\t\t\t\tclose(workerCh)\n\t\t\t\t}\n\t\t\t\tbreak Loop\n\t\t\tcase t := <-ticker.C:\n\t\t\t\tfetch(t)\n\t\t\t}\n\t\t}\n\t\ts.logger.Infoln(\"end main\")\n\t}()\n\n\t// this goroutine is responsible for notifying\n\t// everyone that we want to exit\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tclose(done)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn s.Handler.Handle(out)\n}", "func (r *ResourcesController) Run(stopCh <-chan struct{}) {\n\tif r.resources.clusterID == \"\" {\n\t\tklog.Info(\"No cluster ID configured -- skipping cluster dependent syncers.\")\n\t\treturn\n\t}\n\tgo r.syncer.Sync(\"tags syncer\", controllerSyncTagsPeriod, stopCh, r.syncTags)\n}", "func Run(devfile *Devfile) error {\n\t// Validate watch path\n\tvalidPath, err := validatePath(devfile.Watch)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdevfile.Watch = validPath\n\n\t// If no tasks were given, then we're done.\n\t// Otherwise, run them atleast once.\n\tif len(devfile.Tasks) <= 0 {\n\t\treturn nil\n\t} else {\n\t\tif err := runTasks(devfile.Tasks); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If no watcher is needed, then we're done.\n\tif devfile.Watch == \"\" {\n\t\treturn nil\n\t}\n\n\t// Otherwise, watch for changes.\n\tchanged := make(chan struct{}, 1)\n\terrored := make(chan error, 1)\n\tclosed := make(chan struct{}, 1)\n\tgo watch(devfile.Watch, changed, errored, closed)\n\tfor {\n\t\tselect {\n\t\tcase <-changed:\n\t\t\tclearScreen(os.Stdout)\n\t\t\trunTasks(devfile.Tasks)\n\t\tcase err := <-errored:\n\t\t\tlog.Print(err)\n\t\tcase <-closed:\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}", "func Run(ctx context.Context, config *Config) error {\n\tclientConfig, err := rest.InClusterConfig()\n\tclientset, err := kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar namespace string\n\t// A specific namespace is ignored if all-namespaces is provided\n\tif config.AllNamespaces {\n\t\tnamespace = \"\"\n\t} else {\n\t\tnamespace = config.Namespace\n\t\tif namespace == \"\" {\n\t\t\treturn errors.Wrap(err, \"unable to get default namespace\")\n\t\t}\n\t}\n\tfmt.Println(\"Hello 1 :\")\n\tadded, removed, err := Watch(ctx, clientset.CoreV1().Pods(namespace), config.PodQuery, config.ContainerQuery, config.ExcludeContainerQuery, config.ContainerState, config.LabelSelector)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to set up watch\")\n\t}\n\n\ttails := make(map[string]*Tail)\n\n\tgo func() {\n\t\tfor p := range added {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttail := NewTail(p.Namespace, p.Pod, p.Container, config.Template, &TailOptions{\n\t\t\t\tTimestamps: config.Timestamps,\n\t\t\t\tSinceSeconds: int64(config.Since.Seconds()),\n\t\t\t\tExclude: config.Exclude,\n\t\t\t\tNamespace: config.AllNamespaces,\n\t\t\t\tTailLines: config.TailLines,\n\t\t\t})\n\t\t\ttails[id] = tail\n\n\t\t\ttail.Start(ctx, clientset.CoreV1().Pods(p.Namespace))\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor p := range removed {\n\t\t\tid := p.GetID()\n\t\t\tif tails[id] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttails[id].Close()\n\t\t\tdelete(tails, id)\n\t\t}\n\t}()\n\n\t<-ctx.Done()\n\n\treturn nil\n}", "func (s *Service) Watch(ctx context.Context, chConfig *config.CheckerConfig) {\n\tsourcesFile, err := os.Open(chConfig.Source())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer sourcesFile.Close()\n\n\tfor i := 0; i < cap(s.workerPool); i++ {\n\t\tworker := NewWorker(s.store, s.workerPool)\n\t\tworker.Start(ctx)\n\t}\n\n\tvar parallelRun int\n\tscanner := bufio.NewScanner(sourcesFile)\n\tfor scanner.Scan() && parallelRun < parallelRunMaxQty {\n\t\ts.spawnCheck(ctx, scanner.Text(), chConfig.Interval())\n\t\tparallelRun++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tfmt.Println(\"Service shutdown.\")\n\t\treturn\n\t}\n}", "func (urm *UnifiedResourceManager) Run(stopCh <-chan struct{}) {\n\tctx := context.Background()\n\n\t// Create UnifiedResource CR if not exist\n\turm.CreateUnifiedResourceCRD(ctx)\n\n\t// Maintain VolumeGroup if set in configMap\n\tgo urm.BuildUnifiedResource()\n\n\t// UpdateUnifiedStorage\n\t// go wait.Until(urm.RecordUnifiedResources, time.Duration(urm.UpdateInterval)*time.Second, stopCh)\n\n\tlog.Infof(\"Starting to update node storage on %s...\", urm.NodeID)\n\t<-stopCh\n\tlog.Infof(\"Stop to update node storage...\")\n}", "func (o *ListOptions) Run(ctx context.Context) (err error) {\n\to.printDevfileList(o.devfileList.Items)\n\treturn nil\n}", "func Run() {\n\trscs := ParseAll(context.Background(), resourceFiles, pkg)\n\tb, err := proto.Marshal(rscs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err = ioutil.WriteFile(rPbOutput, b, 0644); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (c *Controller) Run(workers int, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.workqueue.ShutDown()\n\n\tklog.Info(\"starting manifest controller...\")\n\tdefer klog.Info(\"shutting down manifest controller\")\n\n\t// Wait for the caches to be synced before starting workers\n\tif !cache.WaitForNamedCacheSync(\"manifest-controller\", stopCh, c.manifestSynced) {\n\t\treturn\n\t}\n\n\tklog.V(5).Infof(\"starting %d worker threads\", workers)\n\t// Launch workers to process Manifest resources\n\tfor i := 0; i < workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t<-stopCh\n}", "func (g *Gossiper) Run(ctx context.Context) {\n\tsths := make(chan sthInfo, g.bufferSize)\n\n\tvar wg sync.WaitGroup\n\twg.Add(1 + len(g.srcs))\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tglog.Info(\"starting Submitter\")\n\t\tg.Submitter(ctx, sths)\n\t\tglog.Info(\"finished Submitter\")\n\t}()\n\tfor _, src := range g.srcs {\n\t\tgo func(src *sourceLog) {\n\t\t\tdefer wg.Done()\n\t\t\tglog.Infof(\"starting Retriever(%s)\", src.Name)\n\t\t\tsrc.Retriever(ctx, g, sths)\n\t\t\tglog.Infof(\"finished Retriever(%s)\", src.Name)\n\t\t}(src)\n\t}\n\twg.Wait()\n}", "func Run(config *Settings) {\n\tfileNames, err := config.reader.ReadExecutables()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar resMutex = &sync.Mutex{}\n\tres := make([]*google.TestResult, 0)\n\n\tvar tasksWg sync.WaitGroup\n\ttasksWg.Add(len(fileNames))\n\tworkerQueueLimit := make(chan bool, config.workersCount) \n\n\tfor _, line := range fileNames {\n\t\tworkerQueueLimit <- true // try get access to work\n\t\tgo func(file string) {\n\t\t\tdefer tasksWg.Done()\n\t\t\tdefer func() { <-workerQueueLimit }() // decrease working queue\n\n\t\t\tconfig.formatter.ShowSuiteStart(file)\n\n\t\t\tgr, output, err := runGoogleTest(file, config.workingDir)\n\t\t\tif err != nil {\n\t\t\t\tconfig.formatter.ShowSuiteFailure(file, output, err)\n\t\t\t} else {\n\t\t\t\tresMutex.Lock()\n\t\t\t\tdefer resMutex.Unlock()\n\t\t\t\tres = append(res, gr)\n\t\t\t\tconfig.formatter.ShowTests(gr, output)\n\t\t\t}\n\t\t}(line)\n\t}\n\n\ttasksWg.Wait()\n\n\tconfig.formatter.ShowStatistics(res)\n}", "func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error {\n\tdefer runtime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\t// Start the informer factories to begin populating the informer caches\n\tglog.Info(\"Starting add ebs tags controller\")\n\n\t// Wait for the caches to be synced before starting workers\n\tglog.Info(\"Waiting for informer caches to sync\")\n\tif ok := cache.WaitForCacheSync(stopCh, c.claimListerSynced); !ok {\n\t\treturn fmt.Errorf(\"failed to wait for caches to sync\")\n\t}\n\n\tglog.Info(\"Starting workers\")\n\t// Launch two workers to process the resources\n\tfor i := 0; i < threadiness; i++ {\n\t\tgo wait.Until(c.runWorker, 30*time.Second, stopCh)\n\t}\n\n\tglog.Info(\"Started workers\")\n\t<-stopCh\n\tglog.Info(\"Shutting down workers\")\n\n\treturn nil\n}", "func (w *Watcher) run() {\n watcher, err := w.dial()\n\n if err != nil {\n w.log <- err\n return\n }\n defer watcher.Close()\n\n go func() {\n for event := range watcher.Event {\n w.handleEvent(event)\n }\n }()\n\n go func() {\n for err := range watcher.Error {\n w.handleError(err)\n }\n }()\n\n <-w.done\n}", "func (a *asyncProvidersFinder) Run(ctx context.Context, numWorkers int) {\n\ta.ctx = ctx\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase req := <-a.workQueue:\n\t\t\t\t\ta.handleRequest(ctx, req)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\t// periodic metric publishing\n\tgo func() {\n\t\tfor {\n\t\t\tdefer a.metricsTicker.Stop()\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-a.metricsTicker.C:\n\t\t\t\ta.pendingMut.RLock()\n\t\t\t\tpending := len(a.pending)\n\t\t\t\ta.pendingMut.RUnlock()\n\n\t\t\t\tstats.Record(ctx, metrics.PrefetchesPending.M(int64(pending)))\n\t\t\t\tstats.Record(ctx, metrics.PrefetchNegativeCacheSize.M(int64(a.negativeCache.Len())))\n\t\t\t\tstats.Record(ctx, metrics.PrefetchNegativeCacheTTLSeconds.M(int64(a.negativeCacheTTL.Seconds())))\n\t\t\t\tstats.Record(ctx, metrics.PrefetchesPendingLimit.M(int64(a.workQueueSize)))\n\n\t\t\t\ta.onMetricsPublished()\n\t\t\t}\n\t\t}\n\t}()\n}", "func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlevel.Error(d.logger).Log(\"msg\", \"Error adding file watcher\", \"err\", err)\n\t\tfileWatcherErrorsCount.Inc()\n\t\treturn\n\t}\n\td.watcher = watcher\n\tdefer d.stop()\n\n\td.refresh(ctx, ch)\n\n\tticker := time.NewTicker(d.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\n\t\tcase event := <-d.watcher.Events:\n\t\t\t// fsnotify sometimes sends a bunch of events without name or operation.\n\t\t\t// It's unclear what they are and why they are sent - filter them out.\n\t\t\tif len(event.Name) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Everything but a chmod requires rereading.\n\t\t\tif event.Op^fsnotify.Chmod == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Changes to a file can spawn various sequences of events with\n\t\t\t// different combinations of operations. For all practical purposes\n\t\t\t// this is inaccurate.\n\t\t\t// The most reliable solution is to reload everything if anything happens.\n\t\t\td.refresh(ctx, ch)\n\n\t\tcase <-ticker.C:\n\t\t\t// Setting a new watch after an update might fail. Make sure we don't lose\n\t\t\t// those files forever.\n\t\t\td.refresh(ctx, ch)\n\n\t\tcase err := <-d.watcher.Errors:\n\t\t\tif err != nil {\n\t\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error watching file\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func(c *kubeResourceServiceController)Run(ctx context.Context)error{\n\t// define a listwatch\n\tlw := cache.ListWatch{\n\t\tListFunc: func(options v1.ListOptions) (object runtime.Object, err error) {\n\t\t\treturn c.clientSet.CoreV1().Services(corev1.NamespaceAll).List(v1.ListOptions{\n\t\t\t\tLabelSelector:LABEL_SELECTOR_KUBE_BRIDGE_MODULE,\n\t\t\t})\n\t\t},\n\t\tWatchFunc: func(options v1.ListOptions) (w watch.Interface, err error) {\n\t\t\treturn c.clientSet.CoreV1().Services(corev1.NamespaceAll).Watch(v1.ListOptions{\n\t\t\t\tLabelSelector:LABEL_SELECTOR_KUBE_BRIDGE_MODULE,\n\t\t\t})\n\t\t},\n\t\tDisableChunking: false,\n\t}\n\tsvcInformer := cache.NewSharedIndexInformer(&lw, &corev1.Service{},0,cache.Indexers{})\n\tsvcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onAdd\t,\n\t\tUpdateFunc: c.onUpdate,\n\t\tDeleteFunc: c.onDelete,\n\t})\n\tsvcInformer.Run(ctx.Done())\n\t<- ctx.Done()\n\treturn ctx.Err()\n}", "func (p *Poller) Run() {\n\tgo util.Forever(func() {\n\t\te, err := p.getFunc()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"failed to list: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tp.sync(e)\n\t}, p.period)\n}", "func (c *Controller) Run(workers int, stopCh chan struct{}) {\n\tdefer runtime.HandleCrash()\n\n\t// Let the workers stop when we are done\n\tdefer c.queue.ShutDown()\n\tklog.V(2).Infof(\"[%s] Starting controller\", c.resource)\n\n\tgo c.informer.Run(stopCh)\n\n\t// Wait for all involved caches to be synced, before processing items from the queue is started\n\tif !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {\n\t\truntime.HandleError(fmt.Errorf(\"[%s] : Timed out waiting for caches to sync\", c.resource))\n\t\treturn\n\t}\n\n\tfor i := 0; i < workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\tgo wait.Until(c.patchUpdateNotifyList, time.Second, stopCh)\n\n\t<-stopCh\n\tklog.V(2).Infof(\"[%s] Stopping controller\", c.resource)\n}", "func (w *Watcher) Run() {\n\tfor {\n\t\tif w.closed {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Millisecond * time.Duration(w.Interval))\n\t\tl := len(w.Inputs)\n\t\tw.LogFunc(\"Checking %d items...\\n\", l)\n\t\tw.DoRemoval()\n\t\tw.DoUpdate()\n\t\ttime.Sleep(time.Millisecond * time.Duration(w.Interval))\n\t}\n}", "func (d *Deployer) runWorker() {\n\tlog.Debug(\"Deployer: starting\")\n\n\t// invoke processNextItem to fetch and consume the next change\n\t// to a watched or listed resource\n\tfor d.processNextItem() {\n\t\tlog.Debug(\"Deployer.runWorker: processing next item\")\n\t}\n\n\tlog.Debug(\"Deployer.runWorker: completed\")\n}", "func (r *Reflector) Run(stopCh <-chan struct{}) {\n\tklog.V(3).Infof(\"Starting reflector %s (%s) from %s\", r.typeDescription, r.resyncPeriod, r.name)\n\twait.BackoffUntil(func() {\n\t\tif err := r.ListAndWatch(stopCh); err != nil {\n\t\t\tr.watchErrorHandler(r, err)\n\t\t}\n\t}, r.backoffManager, true, stopCh)\n\tklog.V(3).Infof(\"Stopping reflector %s (%s) from %s\", r.typeDescription, r.resyncPeriod, r.name)\n}", "func (e *DockerRegistryServiceController) Run(workers int, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer e.registryLocationQueue.ShutDown()\n\n\tglog.Infof(\"Starting DockerRegistryServiceController controller\")\n\tdefer glog.Infof(\"Shutting down DockerRegistryServiceController controller\")\n\n\t// Wait for the store to sync before starting any work in this controller.\n\tready := make(chan struct{})\n\tgo e.waitForDockerURLs(ready, stopCh)\n\tselect {\n\tcase <-ready:\n\tcase <-stopCh:\n\t\treturn\n\t}\n\tglog.V(1).Infof(\"caches synced\")\n\n\tgo wait.Until(e.watchForDockerURLChanges, time.Second, stopCh)\n\tfor i := 0; i < workers; i++ {\n\t\tgo wait.Until(e.watchForDockercfgSecretUpdates, time.Second, stopCh)\n\t}\n\t<-stopCh\n}", "func (sm *StatsManager) Run() {\n\tfor _, stat := range sm.statsConfigs {\n\t\tgo sm.periodicallyDisplayStats(stat)\n\t}\n}", "func (list *APTAuditList) Run() (int, error) {\n\tlistAttempts := 0\n\tlistErrCount := 0\n\tvar err error\n\tlist.initClients()\n\tfor {\n\t\tlistAttempts += 1\n\t\tlist.listClient.GetList(list.keyPrefix)\n\t\tif list.listClient.ErrorMessage != \"\" {\n\t\t\tfmt.Fprintln(os.Stderr, list.listClient.ErrorMessage)\n\t\t\tlist.flagError()\n\t\t\tlistErrCount += 1\n\t\t\tif listAttempts == 3 && listErrCount == 3 {\n\t\t\t\tbreak // Config error.\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Fetch the records is batches, using concurrent goroutines.\n\t\t// The number of goroutines is specified by list.concurrency.\n\t\tstart := 0\n\t\tfor {\n\t\t\tstart = list.fetchBatch(list.listClient.Response.Contents, start)\n\t\t\tif start >= len(list.listClient.Response.Contents) || list.getCount() >= list.limit {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Print the batch of results we just fetched. This will be <=100 records.\n\t\t// Clear the results list, so we're never holding more than 100 items at\n\t\t// once in memory.\n\t\tlist.printAll()\n\t\tlist.clearResults()\n\n\t\t// If the S3 response is not truncated, there are no more records to fetch.\n\t\t// In that case, or if we've already fetched the limit, we're done.\n\t\tif *list.listClient.Response.IsTruncated == false || list.getCount() >= list.limit {\n\t\t\tbreak // no more items to fetch\n\t\t}\n\t}\n\treturn list.getCount(), err\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 (c *cacheSelector) run() {\n\tdefer c.wg.Done()\n\n\t// 除非收到quit信号,否则一直卡在watch上,watch内部也是一个loop\n\tfor {\n\t\t// exit early if already dead\n\t\tif c.quit() {\n\t\t\tlog.Warn(\"(cacheSelector)run() quit now\")\n\t\t\treturn\n\t\t}\n\n\t\t// create new watcher\n\t\t// 创建新watch,走到这一步要么第第一次for循环进来,要么是watch函数出错。watch出错说明registry.watch的zk client与zk连接出现了问题\n\t\tw, err := c.so.Registry.Watch()\n\t\tlog.Debug(\"cache.Registry.Watch() = watch{%#v}, error{%#v}\", w, jerrors.ErrorStack(err))\n\t\tif err != nil {\n\t\t\tif c.quit() {\n\t\t\t\tlog.Warn(\"(cacheSelector)run() quit now\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Warn(\"cacheSelector.Registry.Watch() = error{%v}\", jerrors.ErrorStack(err))\n\t\t\ttime.Sleep(common.TimeSecondDuration(registry.REGISTRY_CONN_DELAY))\n\t\t\tcontinue\n\t\t}\n\n\t\t// watch for events\n\t\t// 除非watch遇到错误,否则watch函数内部的for循环一直运行下午,run函数的for循环也会一直卡在watch函数上\n\t\t// watch一旦退出,就会执行registry.Watch().Stop, 相应的client就会无效\n\t\terr = c.watch(w)\n\t\tlog.Debug(\"cache.watch(w) = err{%#+v}\", jerrors.ErrorStack(err))\n\t\tif err != nil {\n\t\t\tlog.Warn(\"cacheSelector.watch() = error{%v}\", jerrors.ErrorStack(err))\n\t\t\ttime.Sleep(common.TimeSecondDuration(registry.REGISTRY_CONN_DELAY))\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (r Reflector) Run(ctx context.Context) error {\n\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\n\t// Grab all goroutines error into err\n\tvar err error\n\terrLock := sync.Mutex{}\n\twg := &sync.WaitGroup{}\n\n\t// Goroutine fetch events from API server and schedule them\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif gErr := r.runFetcher(ctx); gErr != nil {\n\t\t\terrLock.Lock()\n\t\t\terr = multierr.Append(err, gErr)\n\t\t\terrLock.Unlock()\n\t\t\tr.log.Errorw(\"Error during fetching events. Send signal to stop\", zap.Error(err))\n\t\t\tcancel()\n\t\t} else {\n\t\t\tr.log.Info(\"Event fetcher was stopped\")\n\t\t}\n\t}()\n\n\n\t// Handler. Can re-schedule event if temporary error happens\n\tfor i := 0; i < r.workersCount; i++ {\n\t\twg.Add(1)\n\t\tlog := r.log.With(\"WorkerID\", i)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tr.runProcessor(log)\n\t\t\tlog.Info(\"Worker was stopped\")\n\t\t}()\n\t}\n\tr.log.Infof(\"Start %d workers\", r.workersCount)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tr.log.Debug(\"Get cancel signal. Shutdown queue\")\n\t\tr.queue.ShutDown()\n\t}()\n\n\twg.Wait()\n\n\treturn err\n}", "func Run() {\n\tflag.Parse()\n\n\t// Open or create file at ~/applications.json\n\tfile := openFile()\n\n\t// If file is empty write initial JSON to it\n\tfi, _ := file.Stat()\n\tif fi.Size() == 0 {\n\t\t_, err := file.WriteString(\"{}\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t// Reopen it to get updates\n\t\tfile = openFile()\n\t}\n\n\t// Read file and parse into applications struct\n\topts := readFile(file)\n\tapps := make(applications)\n\terr := json.Unmarshal(opts, &apps)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Handle reading and setting configuration if -s flag passed\n\tif *set {\n\t\tsetConfig(opts, apps)\n\t\treturn\n\t}\n\n\t// Loop through applications and either open or close them\n\tfor _, app := range apps[*group] {\n\t\twg.Add(1)\n\t\tgo func(app string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif *close {\n\t\t\t\terr = closeApp(app)\n\t\t\t} else {\n\t\t\t\terr = openApp(app, apps)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}(app)\n\t}\n\n\twg.Wait()\n}", "func (c *Client) Run() {\n\tlog.Infof(\"Checking permission for: %s\", c.config.outputDir)\n\tif !c.checkWritable() {\n\t\tlog.Panicf(\"No write permission on directory: %s\", c.config.outputDir)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Info(\"Starting collecting URLs..\")\n\tc.collectUrlsFromIndex()\n\tlog.Infof(\"Total files found: %d, Total directories found: %d\", len(c.files), len(c.directories))\n\tlog.Info(\"Creating the same directory structure..\")\n\tc.createDirectories()\n\tlog.Info(\"Preparing for downloads..\")\n\tc.start()\n\tlog.Info(\"Done.\")\n}", "func Run(rc types.ResourceConfig) int {\n\t// Read files.\n\tf, err := readFiles()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed reading files: %v\\n\", err)\n\n\t\treturn ExitError\n\t}\n\n\tc, err := prepare(f, rc)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed preparing object: %v\\n\", err)\n\n\t\treturn ExitError\n\t}\n\n\t// Calculate and print diff.\n\tfmt.Printf(\"Calculating diff...\\n\\n\")\n\n\td := cmp.Diff(c.Containers().ToExported().PreviousState, c.Containers().DesiredState())\n\n\tif d == \"\" {\n\t\tfmt.Println(\"No changes required\")\n\n\t\treturn ExitOK\n\t}\n\n\tfmt.Printf(\"Following changes required:\\n\\n%s\\n\\n\", d)\n\n\treturn deploy(c)\n}", "func (m *cloudResourceSyncManager) Run(stopCh <-chan struct{}) {\n\twait.Until(m.syncNodeAddresses, m.syncPeriod, stopCh)\n}", "func (w *WorkerManager) Run(ctx context.Context, filename string) {\n\tstats.StartTimer()\n\n\tdefer w.close()\n\n\tvar r io.ReadCloser\n\tvar err error\n\n\tif filename == \"-\" {\n\t\tr = os.Stdin\n\t} else {\n\t\tr, err = os.Open(filename)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer r.Close()\n\t}\n\n\tw.produceWithScanner(ctx, r)\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 (c *cleaner) Run(isRunning *atomic.Bool) {\n\tlog.Info(\"Cleaning reserved resources and volumes\")\n\tc.cleanUnusedVolumes()\n\tlog.Info(\"Cleaning reserved resources and volumes returned\")\n}", "func (r *Rclone) Run() error {\n\tfor _, v := range r.config.Copy {\n\t\terr := r.callJob(&v)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, v := range r.config.Sync {\n\t\terr := r.callJob(&v)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Run() {\n\tloading.Prefix = loadingMsgProcess\n\tloading.Start()\n\n\tvar review []*Review\n\n\tlineCh := make(chan string, 100)\n\n\tgo readFile(inputFile, lineCh)\n\n\tfor line := range lineCh {\n\t\tindex := getIndexPosition(line, delimiter)\n\t\tif index != -1 {\n\t\t\tr, err := unmarshal(line[index:])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"%s => %s\", errorMsgUnmarshal, err)\n\t\t\t}\n\t\t\treview = append(review, r)\n\t\t}\n\t}\n\tloading.Stop()\n\tloading.Prefix = loadingMsgWrite\n\tloading.FinalMSG = loadingMsgComplete\n\tloading.Start()\n\n\tif err := writeOut(review, outputFile); err != nil {\n\t\tlog.Fatalf(\"%s => %s\", errorMsgWriteOut, err)\n\t}\n\tloading.Stop()\n}", "func (m *Manager) Run() error {\n\tfor range m.ctx.Done() {\n\t\tm.cancelDiscoverers()\n\t\treturn m.ctx.Err()\n\t}\n\treturn nil\n}", "func (t *Task) Run() error {\n\tfor _, v := range t.Paths { //Loop through all our paths\n\t\terr := t.FSWatcher.Add(v) //Add path to watcher\n\t\tif err != nil {\n\t\t\treturn err // Pass fail back to caller, we can't continue from this.\n\t\t}\n\t}\n\tdefer t.FSWatcher.Close()\n\n\tticker := time.NewTicker(time.Millisecond * 500) //Run every 0.5 secs\n\tdefer ticker.Stop()\n\n\tvar evts []fsnotify.Event //Create a slice to temp store all events\n\tvar mux sync.Mutex //Create a mux for our append lock\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif len(evts) == 0 { //Not events added on this tick\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil //Events found, stop blocking and return to program flow\n\t\tcase event := <-t.FSWatcher.Events:\n\t\t\tmux.Lock()\n\t\t\tevts = append(evts, event) //Append the events to the event slice, this isn't thread-safe so we need a mux\n\t\t\tmux.Unlock()\n\t\t}\n\t}\n}", "func (i *Initializer) Run() (chan struct{}, error) {\n\n\tif err := i.declare(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar err error\n\ti.client, err = rest.RESTClientFor(i.kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquit := make(chan struct{})\n\n\tsource := cache.NewListWatchFromClient(\n\t\ti.client,\n\t\ti.ns.Resource,\n\t\tapi.NamespaceAll,\n\t\tfields.Everything())\n\n\tsourcePreInitialization := &cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.IncludeUninitialized = true\n\t\t\treturn source.List(options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.IncludeUninitialized = true\n\t\t\treturn source.Watch(options)\n\t\t},\n\t}\n\n\t_, controller := cache.NewInformer(\n\t\tsourcePreInitialization,\n\t\t&unstructured.Unstructured{},\n\t\ttime.Second*60,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tu := obj.(*unstructured.Unstructured)\n\t\t\t\tif err := i.initializeResource(u); err != nil {\n\t\t\t\t\tlogrus.Errorf(\"Failed to initialize %v object %v/%v: %v\", i.ns.Resource, u.GetNamespace(), u.GetName(), err)\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\n\tgo controller.Run(quit)\n\n\treturn quit, nil\n}", "func (g *Gossiper) Run(ctx context.Context) {\n\tsths := make(chan sthInfo, g.bufferSize)\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(g.srcs))\n\tfor _, src := range g.srcs {\n\t\tgo func(src *sourceLog) {\n\t\t\tdefer wg.Done()\n\t\t\tglog.Infof(\"starting Retriever(%s)\", src.Name)\n\t\t\tsrc.Retriever(ctx, g, sths)\n\t\t\tglog.Infof(\"finished Retriever(%s)\", src.Name)\n\t\t}(src)\n\t}\n\tglog.Info(\"starting Submitter\")\n\tg.Submitter(ctx, sths)\n\tglog.Info(\"finished Submitter\")\n\n\t// Drain the sthInfo channel during shutdown so the Retrievers don't block on it.\n\tgo func() {\n\t\tfor info := range sths {\n\t\t\tglog.V(1).Infof(\"discard STH from %s\", info.name)\n\t\t}\n\t}()\n\n\twg.Wait()\n\tclose(sths)\n}", "func (m *Manager) Run(ctx context.Context, wg *sync.WaitGroup) error {\n\tif m.machine == nil {\n\t\treturn fmt.Errorf(\"manager requires a machine to manage\")\n\t}\n\n\terr := m.configureWatchers()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, watcher := range m.watchers {\n\t\twg.Add(1)\n\t\tgo watcher.Run(ctx, wg)\n\n\t\tif watcher.AnnounceInterval() > 0 {\n\t\t\twg.Add(1)\n\t\t\tgo m.announceWatcherState(ctx, wg, watcher)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *HabitatController) Run(ctx context.Context) error {\n\tfmt.Printf(\"Watching Service Group objects\\n\")\n\n\t_, err := c.watchServiceGroups(ctx)\n\tif err != nil {\n\t\tfmt.Printf(\"error: Failed to register watch for ServiceGroup resource: %v\\n\", err)\n\t\treturn err\n\t}\n\n\t<-ctx.Done()\n\treturn ctx.Err()\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 (p *listProcessor) run(ctx context.Context, gvr schema.GroupVersionResource) error {\n\tlistPager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) {\n\t\tfor {\n\t\t\tallResource, err := p.dynamicClient.Resource(gvr).List(ctx, opts)\n\t\t\tif err != nil {\n\t\t\t\tklog.Warningf(\"List of %v failed: %v\", gvr, err)\n\t\t\t\tif errors.IsResourceExpired(err) {\n\t\t\t\t\ttoken, err := inconsistentContinueToken(err)\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\topts.Continue = token\n\t\t\t\t\tklog.V(2).Infof(\"Relisting %v after handling expired token\", gvr)\n\t\t\t\t\tcontinue\n\t\t\t\t} else if retryable := canRetry(err); retryable == nil || *retryable == false {\n\t\t\t\t\treturn nil, err // not retryable or we don't know. Return error and controller will restart migration.\n\t\t\t\t} else {\n\t\t\t\t\tif seconds, delay := errors.SuggestsClientDelay(err); delay {\n\t\t\t\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\t\t\t\t\t}\n\t\t\t\t\tklog.V(2).Infof(\"Relisting %v after retryable error: %v\", gvr, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmigrationStarted := time.Now()\n\t\t\tklog.V(2).Infof(\"Migrating %d objects of %v\", len(allResource.Items), gvr)\n\t\t\tif err = p.processList(allResource, gvr); err != nil {\n\t\t\t\tklog.Warningf(\"Migration of %v failed after %v: %v\", gvr, time.Now().Sub(migrationStarted), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tklog.V(2).Infof(\"Migration of %d objects of %v finished in %v\", len(allResource.Items), gvr, time.Now().Sub(migrationStarted))\n\n\t\t\tallResource.Items = nil // do not accumulate items, this fakes the visitor pattern\n\t\t\treturn allResource, nil // leave the rest of the list intact to preserve continue token\n\t\t}\n\t}))\n\tlistPager.FullListIfExpired = false // prevent memory explosion from full list\n\n\tmigrationStarted := time.Now()\n\tif _, _, err := listPager.List(p.ctx, metav1.ListOptions{}); err != nil {\n\t\tmetrics.ObserveFailedMigration(gvr.String())\n\t\treturn err\n\t}\n\tmigrationDuration := time.Now().Sub(migrationStarted)\n\tklog.V(2).Infof(\"Migration for %v finished in %v\", gvr, migrationDuration)\n\tmetrics.ObserveSucceededMigration(gvr.String())\n\tmetrics.ObserveSucceededMigrationDuration(migrationDuration.Seconds(), gvr.String())\n\treturn nil\n}", "func WatchCommand(args Args, done chan bool) {\n\tfor _, client := range args.ThemeClients {\n\t\tconfig := client.GetConfiguration()\n\t\tclient.Message(\"Spawning %d workers for %s\", config.Concurrency, args.Domain)\n\t\tassetEvents := client.NewFileWatcher(args.Directory, args.NotifyFile)\n\t\tfor i := 0; i < config.Concurrency; i++ {\n\t\t\tgo spawnWorker(assetEvents, client)\n\t\t\tclient.Message(\"%s Worker #%d ready to upload local changes\", config.Domain, i)\n\t\t}\n\t}\n}", "func (wire *Wire) Run() {\n\tgo wire.blackList.clear()\n\n\tfor r := range wire.requests {\n\t\twire.workerTokens <- struct{}{}\n\n\t\tgo func(r Request) {\n\t\t\tdefer func() {\n\t\t\t\t<-wire.workerTokens\n\t\t\t}()\n\n\t\t\tkey := strings.Join([]string{\n\t\t\t\tstring(r.InfoHash), genAddress(r.IP, r.Port),\n\t\t\t}, \":\")\n\n\t\t\tif len(r.InfoHash) != 20 || wire.blackList.in(r.IP, r.Port) ||\n\t\t\t\twire.queue.Has(key) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twire.fetchMetadata(r)\n\t\t}(r)\n\t}\n}", "func (c *QueueController) loop() {\n\tvar watchCh chan runner.RunStatus\n\tvar updateDoneCh chan interface{}\n\tupdateRequested := false\n\n\tvar idleLatency = c.inv.stat.Latency(stats.WorkerIdleLatency_ms)\n\tidleLatency.Time()\n\n\ttryUpdate := func() {\n\t\tif watchCh == nil && updateDoneCh == nil {\n\t\t\tupdateRequested = false\n\t\t\tupdateDoneCh = make(chan interface{})\n\t\t\tgo func() {\n\t\t\t\t// Record filers by RunType that have requested updates\n\t\t\t\tc.updateLock.Lock()\n\t\t\t\ttypesToUpdate := []runner.RunType{}\n\t\t\t\tfor t, u := range c.updateReq {\n\t\t\t\t\tif u {\n\t\t\t\t\t\ttypesToUpdate = append(typesToUpdate, t)\n\t\t\t\t\t\tc.updateReq[t] = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.updateLock.Unlock()\n\n\t\t\t\t// Run all requested filer updates serially\n\t\t\t\tfor _, t := range typesToUpdate {\n\t\t\t\t\tlog.Infof(\"Running filer update for type %v\", t)\n\t\t\t\t\tif err := c.filerMap[t].Filer.Update(); err != nil {\n\t\t\t\t\t\tfields := log.Fields{\"err\": err}\n\t\t\t\t\t\tif c.runningCmd != nil {\n\t\t\t\t\t\t\tfields[\"runType\"] = t\n\t\t\t\t\t\t\tfields[\"tag\"] = c.runningCmd.Tag\n\t\t\t\t\t\t\tfields[\"jobID\"] = c.runningCmd.JobID\n\t\t\t\t\t\t\tfields[\"taskID\"] = c.runningCmd.TaskID\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.WithFields(fields).Error(\"Error running Filer Update\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tupdateDoneCh <- nil\n\t\t\t}()\n\t\t} else {\n\t\t\tupdateRequested = true\n\t\t}\n\t}\n\n\ttryRun := func() {\n\t\tif watchCh == nil && updateDoneCh == nil && len(c.queue) > 0 && (c.statusManager.svcStatus.IsHealthy) {\n\t\t\tcmdID := c.queue[0]\n\t\t\twatchCh = c.runAndWatch(cmdID)\n\t\t\tidleLatency.Stop()\n\t\t}\n\t}\n\n\tfor c.reqCh != nil {\n\t\t// Prefer to run an update first if we have one scheduled. If not updating, try running.\n\t\tif updateRequested {\n\t\t\ttryUpdate()\n\t\t} else {\n\t\t\tselect {\n\t\t\tcase <-c.updateCh:\n\t\t\t\ttryUpdate()\n\t\t\tdefault:\n\t\t\t\ttryRun()\n\t\t\t}\n\t\t}\n\n\t\t// Wait on update, updateDone, run start, or run abort.\n\t\tselect {\n\t\tcase <-c.updateCh:\n\t\t\ttryUpdate()\n\n\t\tcase <-updateDoneCh:\n\t\t\t// Give run() a chance right after we've finished updating.\n\t\t\tupdateDoneCh = nil\n\t\t\ttryRun()\n\n\t\tcase req, ok := <-c.reqCh:\n\t\t\t// Handle run and abort requests.\n\t\t\tif !ok {\n\t\t\t\tc.reqCh = nil\n\t\t\t\tclose(c.cancelTimerCh)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch r := req.(type) {\n\t\t\tcase runReq:\n\t\t\t\tst, err := c.enqueue(r.cmd)\n\t\t\t\tr.resultCh <- result{st, err}\n\t\t\tcase abortReq:\n\t\t\t\tst, err := c.abort(r.runID)\n\t\t\t\tr.resultCh <- result{st, err}\n\t\t\t}\n\n\t\tcase <-watchCh:\n\t\t\t// Handle finished run by resetting state.\n\t\t\twatchCh = nil\n\t\t\tc.runningID = \"\"\n\t\t\tc.runningCmd = nil\n\t\t\tc.runningAbort = nil\n\t\t\tc.queue = c.queue[1:]\n\t\t\tidleLatency.Time()\n\t\t}\n\t}\n}", "func (l *HandlerList) Run(r *Request) {\n\tfor _, f := range l.list {\n\t\tf.Fn(r)\n\t}\n}", "func (r *ProcessingStatsRefresher) Run(ctx context.Context) error {\n\tif r.refreshRate == 0 {\n\t\treturn nil\n\t}\n\treturn wait.RepeatUntil(ctx, r.refreshRate, r.collectStats)\n}", "func (c *Reader) Run() {\n\t// Log service settings\n\tc.logSettings()\n\n\t// Run immediately\n\tc.poll()\n\n\t// Schedule additional runs\n\tsched := cron.New()\n\tsched.AddFunc(fmt.Sprintf(\"@every %s\", c.opts.LookupInterval), c.poll)\n\tsched.Start()\n}", "func (p *Processor) Process(read chan resource.Resource, readDone chan bool, swg *sizedwaitgroup.SizedWaitGroup) {\n\tdefer swg.Done()\n\n\timages, err := p.reader.ListAllImages()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"error\": err}).Fatal(\"error list images\")\n\t}\n\n\tfor _, v := range images {\n\t\tread <- v\n\t}\n}", "func Run(workerCount int, refreshInterval time.Duration) {\n\tfor w := 0; w < workerCount; w++ {\n\t\tgo worker(clients)\n\t}\n\tfor {\n\t\tcfg := config.GetConfig()\n\t\tfor i, _ := range cfg.PlatformManagements {\n\t\t\tswitch pm := cfg.PlatformManagements[i].Type; pm {\n\t\t\tcase \"IDRAC\":\n\t\t\t\tfallthrough\n\t\t\tcase \"IDRAC9\":\n\t\t\t\tfallthrough\n\t\t\tcase \"IDRAC8\":\n\t\t\t\tclient := api.NewRedfishAPI(cfg.PlatformManagements[i].Host)\n\t\t\t\tclient.SetUser(cfg.PlatformManagements[i].Username, cfg.PlatformManagements[i].Password)\n\t\t\t\tclients <- client\n\t\t\tcase \"ILO5\":\n\t\t\t\tclient := api.NewHpeApi(cfg.PlatformManagements[i].Host)\n\t\t\t\tclient.SetUser(cfg.PlatformManagements[i].Username, cfg.PlatformManagements[i].Password)\n\t\t\t\tclients <- client\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"Error fetching inventory for %v - type unknown (%v)\\n\", cfg.PlatformManagements[i].Host, cfg.PlatformManagements[i].Type)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(refreshInterval)\n\t}\n}", "func (tester *Tester) Run(v *viper.Viper) {\n\ttester.bindInput(v)\n\n\tpaths, err := filedir.ReadDir(tester.withWatchDir)\n\tif err != nil {\n\t\ttester.logger.Fatalf(err.Error())\n\t}\n\tpaths = append(paths, tester.withWatchDir)\n\n\tabsDir, err := filepath.Abs(tester.withWatchDir)\n\tif err != nil {\n\t\ttester.logger.Fatalf(err.Error())\n\t}\n\n\ttester.logger.Infof(\"Watching : %s\", absDir)\n\n\ttester.watcher.watch(paths, tester.receiver)\n}", "func (p *PCache) Run(ctx context.Context, wg *sync.WaitGroup) {\n\tticker := time.NewTicker(p.retryInterval)\n\tinProgress := false\n\tdefer wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tif !inProgress {\n\t\t\t\tinProgress = true\n\n\t\t\t\tp.RLock()\n\t\t\t\tfor kind, m := range p.kinds {\n\t\t\t\t\tkindInfo := p.kindOptsMap[kind]\n\t\t\t\t\tm.Lock()\n\t\t\t\t\tfor _, in := range m.entries {\n\t\t\t\t\t\terr := p.validateAndPush(m, in, kindInfo)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tp.Log.Errorf(\"Validate and Push of object failed. Err : %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tm.Unlock()\n\t\t\t\t}\n\t\t\t\tp.RUnlock()\n\n\t\t\t\tinProgress = false\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Controller) Run(workers int, stopCh <-chan struct{}) error {\n\t// Start the informer factories to begin populating the informer caches\n\tlog.Info(\"Starting collector controller\")\n\tdefer log.Info(\"Shutting down collector controller\")\n\n\tif len(c.remoteClient.InfluxDB) > 0 {\n\t\t// Check if database for project existed, if not, just create\n\t\tquery := influxapi.Query{\n\t\t\tCommand: \"create database \" + monitorutil.ProjectDatabaseName,\n\t\t\tDatabase: monitorutil.ProjectDatabaseName,\n\t\t}\n\t\t// Wait unitl influxdb is OK\n\t\t_ = wait.PollImmediateInfinite(10*time.Second, func() (bool, error) {\n\t\t\tfor _, client := range c.remoteClient.InfluxDB {\n\t\t\t\tlog.Debugf(\"Query sql: %s\", query.Command)\n\t\t\t\tresp, err := client.Client.Query(query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Create database %s for %s failed: %v\", monitorutil.ProjectDatabaseName, client.Address, err)\n\t\t\t\t\treturn false, nil\n\t\t\t\t} else if resp.Error() != nil {\n\t\t\t\t\tlog.Errorf(\"Create database %s for %s failed: %v\", monitorutil.ProjectDatabaseName, client.Address, resp.Error())\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Info(\"Created database projects in influxdb\")\n\t\t\treturn true, nil\n\t\t})\n\t}\n\n\tdefer runtime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tif ok := cache.WaitForCacheSync(stopCh, c.listerSynced); !ok {\n\t\treturn fmt.Errorf(\"failed to wait for cluster caches to sync\")\n\t}\n\n\tc.stopCh = stopCh\n\n\tfor i := 0; i < workers; i++ {\n\t\tgo wait.Until(c.worker, time.Second, stopCh)\n\t}\n\n\t<-stopCh\n\treturn nil\n}", "func (c *BundleController) Run(ctx context.Context) {\n\tdefer c.wg.Wait()\n\tdefer c.queue.ShutDown()\n\n\tlog.Print(\"Starting Bundle controller\")\n\tdefer log.Print(\"Shutting down Bundle controller\")\n\n\tc.crdInf.AddEventHandler(&crdEventHandler{\n\t\tctx: ctx,\n\t\tBundleController: c,\n\t\twatchers: make(map[string]watchState),\n\t})\n\n\tif !cache.WaitForCacheSync(ctx.Done(), c.bundleInf.HasSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i < c.workers; i++ {\n\t\tc.wg.StartWithContext(ctx, c.worker)\n\t}\n\n\t<-ctx.Done()\n}", "func (c *PsCmd) Run(cli *CLI, logWriters *LogWriters) (err error) {\n\tvar aids []int\n\tif c.AccountID == 0 {\n\t\ts := NewSpinner(\"Looking up accounts\", logWriters)\n\t\ts.Start()\n\n\t\tas, err := api.Accounts()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to look up accounts: %w\", err)\n\t\t}\n\t\tfor _, a := range as {\n\t\t\taids = append(aids, a.ID)\n\t\t}\n\n\t\ts.Stop()\n\t} else {\n\t\taids = append(aids, c.AccountID)\n\t}\n\n\tvar targets [][]int\n\tfor _, id := range aids {\n\t\tif c.AppID == 0 {\n\t\t\ts := NewSpinner(\"Looking up applications\", logWriters)\n\t\t\ts.Start()\n\n\t\t\tas, err := api.Applications(id)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to look up applications: %w\", err)\n\t\t\t}\n\t\t\tfor _, a := range as {\n\t\t\t\ttargets = append(targets, []int{id, a.ID})\n\t\t\t}\n\n\t\t\ts.Stop()\n\t\t} else {\n\t\t\ttargets = append(targets, []int{id, c.AppID})\n\t\t}\n\t}\n\n\tif c.Watch {\n\t\tticker := time.NewTicker(c.Interval)\n\t\tfor ; true; <-ticker.C {\n\t\t\terr = pollAndOutput(cli, targets, c.AppPath,logWriters)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = pollAndOutput(cli, targets, c.AppPath,logWriters)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (w *ImageWorker) Run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase img := <-w.in:\n\t\t\tif err := w.limit.Wait(ctx); err != nil {\n\t\t\t\tif !errors.Is(err, context.Canceled) {\n\t\t\t\t\tlog.Err(err).Send()\n\t\t\t\t}\n\t\t\t}\n\t\t\terr := w.imageDownload(img)\n\t\t\tif err != nil {\n\t\t\t\tlog.Err(err).Send()\n\t\t\t}\n\t\t\tw.done <- struct{}{}\n\t\t}\n\t}\n}", "func (p *GaugeCollectionProcess) Run() {\n\tdefer close(p.stopped)\n\n\t// Wait a random amount of time\n\tstopReceived := p.delayStart()\n\tif stopReceived {\n\t\treturn\n\t}\n\n\t// Create a ticker to start each cycle\n\tp.resetTicker()\n\n\t// Loop until we get a signal to stop\n\tfor {\n\t\tselect {\n\t\tcase <-p.ticker.C:\n\t\t\tp.collectAndFilterGauges()\n\t\tcase <-p.stop:\n\t\t\t// Can't use defer because this might\n\t\t\t// not be the original ticker.\n\t\t\tp.ticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *FileRead) Run() {\n\tfor f := range r.File {\n\t\tif t, err := ioutil.ReadFile(f); err != nil {\n\t\t\tr.Error <- \"Error: file \" + f + \" not found.\"\n\t\t} else {\n\t\t\tr.Text <- string(t)\n\t\t}\n\t}\n}", "func (s *Storage) Run() {\n\tfor _, q := range s.queues {\n\t\tgo q.Run()\n\t}\n}", "func (mc *PodWatcher) StartWatcher(quitCh chan struct{}, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tfor {\n\t\twatcher := cache.NewListWatchFromClient(mc.clientset.CoreV1().RESTClient(), mc.resourceStr, v1.NamespaceAll, fields.Everything())\n\t\tretryWatcher, err := watchClient.NewRetryWatcher(mc.lastRV, watcher)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Could not start watcher for k8s resource: \" + mc.resourceStr)\n\t\t}\n\n\t\tresCh := retryWatcher.ResultChan()\n\t\trunWatcher := true\n\t\tfor runWatcher {\n\t\t\tselect {\n\t\t\tcase <-quitCh:\n\t\t\t\treturn\n\t\t\tcase c := <-resCh:\n\t\t\t\ts, ok := c.Object.(*metav1.Status)\n\t\t\t\tif ok && s.Status == metav1.StatusFailure {\n\t\t\t\t\tif s.Reason == metav1.StatusReasonGone {\n\t\t\t\t\t\tlog.WithField(\"resource\", mc.resourceStr).Info(\"Requested resource version too old, no longer stored in K8S API\")\n\t\t\t\t\t\trunWatcher = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\t// Ignore and let the retry watcher retry.\n\t\t\t\t\tlog.WithField(\"resource\", mc.resourceStr).WithField(\"object\", c.Object).Info(\"Failed to read from k8s watcher\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Update the lastRV, so that if the watcher restarts, it starts at the correct resource version.\n\t\t\t\to, ok := c.Object.(*v1.Pod)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tmc.lastRV = o.ObjectMeta.ResourceVersion\n\n\t\t\t\tpb, err := protoutils.PodToProto(o)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr := &storepb.K8SResource{\n\t\t\t\t\tResource: &storepb.K8SResource_Pod{\n\t\t\t\t\t\tPod: pb,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tmsg := &K8sResourceMessage{\n\t\t\t\t\tObject: r,\n\t\t\t\t\tObjectType: mc.resourceStr,\n\t\t\t\t\tEventType: c.Type,\n\t\t\t\t}\n\t\t\t\tmc.updateCh <- msg\n\t\t\t}\n\t\t}\n\n\t\tlog.WithField(\"resource\", mc.resourceStr).Info(\"K8s watcher channel closed. Retrying\")\n\n\t\t// Wait 5 minutes before retrying, however if stop is called, just return.\n\t\tselect {\n\t\tcase <-quitCh:\n\t\t\treturn\n\t\tcase <-time.After(5 * time.Minute):\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (o *listOptions) Run() error {\n\n\tids, err := backend.List(o.accessToken, o.pipelinesFolderPath, o.getAppServiceNames(), o.isCICD)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to a get list of webhook IDs: %v\", err)\n\t}\n\n\tif ids != nil {\n\t\tif log.IsJSON() {\n\t\t\tmachineoutput.OutputSuccess(ids)\n\t\t} else {\n\t\t\tw := tabwriter.NewWriter(os.Stdout, 5, 2, 3, ' ', tabwriter.TabIndent)\n\t\t\tfmt.Fprintln(w, \"ID\")\n\t\t\tfmt.Fprintln(w, \"==\")\n\t\t\tfor _, id := range ids {\n\t\t\t\tfmt.Fprintln(w, id)\n\t\t\t}\n\t\t\tw.Flush()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w *watcher) Run() {\n\t_, controller := cache.NewInformer(w.watchList, w.eventHandler.GetResourceObject(), time.Second*0, w.eventHandler)\n\tcontroller.Run(w.stopChan)\n\tclose(w.stopChan)\n}", "func (s *Scavenger) run() {\n\tdefer func() {\n\t\ts.emitStats()\n\t\tgo s.Stop()\n\t\ts.stopWG.Done()\n\t}()\n\n\t// Start a task to delete orphaned tasks from the tasks table, if enabled\n\tif s.cleanOrphans() {\n\t\ts.executor.Submit(&orphanExecutorTask{scvg: s})\n\t}\n\n\tvar pageToken []byte\n\tfor {\n\t\tresp, err := s.listTaskList(taskListBatchSize, pageToken)\n\t\tif err != nil {\n\t\t\ts.logger.Error(\"listTaskList error\", tag.Error(err))\n\t\t\treturn\n\t\t}\n\n\t\tfor _, item := range resp.Items {\n\t\t\tatomic.AddInt64(&s.stats.tasklist.nProcessed, 1)\n\t\t\tif !s.executor.Submit(s.newTask(&item)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tpageToken = resp.NextPageToken\n\t\tif pageToken == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\ts.awaitExecutor()\n}", "func (p *Processor) Process(read chan resource.Resource, readDone chan bool, swg *sizedwaitgroup.SizedWaitGroup) {\n\tdefer swg.Done()\n\tpageOffset := 1\n\nprocessing:\n\tfor {\n\t\tswg.Add()\n\t\tgo p.list(read, readDone, swg, pageOffset)\n\t\tselect {\n\t\tcase <-readDone:\n\t\t\tbreak processing\n\t\tdefault:\n\t\t}\n\n\t\tpageOffset++\n\t}\n}", "func (c Client) Run(ctx context.Context) (bool, error) {\n\tif err := c.init(); err != nil {\n\t\treturn false, fmt.Errorf(\"fail during init: %w\", err)\n\t}\n\n\ts := scan.Scan{IgnoreFile: c.Ignore.File, IgnoreLink: c.Ignore.Link, Parser: c.parser}\n\tif err := s.Init(); err != nil {\n\t\treturn false, fmt.Errorf(\"fail to initialize the scan service: %w\", err)\n\t}\n\tentries, err := s.Process(c.Path)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"fail to scan the files: %w\", err)\n\t}\n\n\tw := worker.Worker{Providers: c.providers}\n\tentries, err = w.Process(ctx, entries)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"fail to process the link: %w\", err)\n\t}\n\n\treturn c.output(entries), nil\n}", "func (m *manager) Run() {\n\t// Check if there are any plugins that didn't get cleanly shutdown before\n\t// and if there are shut them down.\n\tm.cleanupStalePlugins()\n\n\t// Get device plugins\n\tdevices := m.loader.Catalog()[base.PluginTypeDevice]\n\tif len(devices) == 0 {\n\t\tm.logger.Debug(\"exiting since there are no device plugins\")\n\t\tm.cancel()\n\t\treturn\n\t}\n\n\tfor _, d := range devices {\n\t\tid := loader.PluginInfoID(d)\n\t\tstoreFn := func(c *plugin.ReattachConfig) error {\n\t\t\tid := id\n\t\t\treturn m.storePluginReattachConfig(id, c)\n\t\t}\n\t\tm.instances[id] = newInstanceManager(&instanceManagerConfig{\n\t\t\tLogger: m.logger,\n\t\t\tCtx: m.ctx,\n\t\t\tLoader: m.loader,\n\t\t\tStoreReattach: storeFn,\n\t\t\tPluginConfig: m.pluginConfig,\n\t\t\tId: &id,\n\t\t\tFingerprintOutCh: m.fingerprintResCh,\n\t\t\tStatsInterval: m.statsInterval,\n\t\t})\n\t}\n\n\t// Now start the fingerprint handler\n\tgo m.fingerprint()\n}", "func (d *Downloads) Run() {\n\tfor {\n\t\tselect {\n\t\tcase performer := <-d.performers:\n\t\t\tgo d.start(performer)\n\t\tcase <-d.quit:\n\t\t\td.close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Scheduler) Run(client *clientv3.Client) error {\n\ts.client = client\n\ts.queue = recipe.NewPriorityQueue(client, common.QueuePrefix)\n\n\ts.logger.Infof(\"starting main scheduler\")\n\n\tgo s.watchDone()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.ready:\n\t\t\ts.process()\n\t\tcase <-s.ctx.Done():\n\t\t\treturn s.ctx.Err()\n\t\tcase <-s.done:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (rm *ReplicationManager) Run(period time.Duration) {\n\trm.syncTime = time.Tick(period)\n\tresourceVersion := \"\"\n\tgo util.Forever(func() { rm.watchControllers(&resourceVersion) }, period)\n}", "func (w *Watcher) doWatch(d time.Duration) {\n\tticker := time.NewTicker(d)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-w.closed:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tcurrFileList := w.listForAll()\n\t\t\tw.pollEvents(currFileList)\n\n\t\t\t// update file list\n\t\t\tw.mu.Lock()\n\t\t\tw.files = currFileList\n\t\t\tw.mu.Unlock()\n\t\t}\n\t}\n}", "func (s *Sync) Run(namespaces []string) (chan struct{}, error) {\n\tclient, err := rest.RESTClientFor(s.kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.clientset, err = kubernetes.NewForConfig(s.kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tquit := make(chan struct{})\n\n \tlogrus.Infof(\"Policy/data ConfigMap processor connected to K8s: namespaces=%v\", namespaces)\n\tfor _, namespace := range namespaces {\n\t\tif namespace == \"*\" {\n\t\t\tnamespace = v1.NamespaceAll\n\t\t}\n\t\tsource := cache.NewListWatchFromClient(\n\t\t\tclient,\n\t\t\t\"configmaps\",\n\t\t\tnamespace,\n\t\t\tfields.Everything())\n\t\t_, controller := cache.NewInformer(\n\t\t\tsource,\n\t\t\t&v1.ConfigMap{},\n\t\t\t0,\n\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: s.add,\n\t\t\t\tUpdateFunc: s.update,\n\t\t\t\tDeleteFunc: s.delete,\n\t\t\t})\n\t\tgo controller.Run(quit)\n\t}\n\treturn quit, nil\n}", "func (c *listCommand) Run(ctx context.Context, _ *commoncli.Env, serverClient util.ServerClient) error {\n\tfilter := &agentv1.ListAgentsRequest_Filter{}\n\tif len(c.selectors) > 0 {\n\t\tmatchBehavior, err := parseToSelectorMatch(c.matchSelectorsOn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tselectors := make([]*types.Selector, len(c.selectors))\n\t\tfor i, sel := range c.selectors {\n\t\t\tselector, err := util.ParseSelector(sel)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error parsing selector %q: %w\", sel, err)\n\t\t\t}\n\t\t\tselectors[i] = selector\n\t\t}\n\t\tfilter.BySelectorMatch = &types.SelectorMatch{\n\t\t\tSelectors: selectors,\n\t\t\tMatch: matchBehavior,\n\t\t}\n\t}\n\n\tagentClient := serverClient.NewAgentClient()\n\n\tpageToken := \"\"\n\tresponse := new(agentv1.ListAgentsResponse)\n\tfor {\n\t\tlistResponse, err := agentClient.ListAgents(ctx, &agentv1.ListAgentsRequest{\n\t\t\tPageSize: 1000, // comfortably under the (4 MB/theoretical maximum size of 1 agent in MB)\n\t\t\tPageToken: pageToken,\n\t\t\tFilter: filter,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresponse.Agents = append(response.Agents, listResponse.Agents...)\n\t\tif pageToken = listResponse.NextPageToken; pageToken == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn c.printer.PrintProto(response)\n}", "func (c *Controller) runWorker() {\n\tlog.Info(\"Starting worker\")\n\n\t// invoke processNextItem to fetch and consume the next change\n\t// to a watched resource\n\tfor c.processNextItem() {\n\t\tlog.Info(\"Processing next item from the queue\")\n\t}\n\n\tlog.Info(\"Worker completed processing items\")\n}", "func (b *Boomer) Run() {\n\tb.results = make(chan *result, b.N)\n\n\ttotalRequests = 0\n\trequestCountChan = make(chan int)\n\tquit = make(chan bool)\n\n\tstart := time.Now()\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\n\tgo func() {\n\t\t<-c\n\t\tfmt.Print(\"quit\\n\")\n\t\t// TODO(jbd): Progress bar should not be finalized.\n\t\tnewReport(b.N, b.results, b.Output, time.Now().Sub(start)).finalize()\n\n\t\tclose(requestCountChan)\n\t\tos.Exit(1)\n\t}()\n\tgo showProgress(b.C) // sunny\n\n\tif b.EnableEngineIo {\n\t\tgo b.readConsole()\n\t\tb.clients = make([]*engineioclient2.Client, b.C)\n\t\tb.startTimes = make([]time.Time, b.C)\n\t\tb.durations = make([]time.Duration, b.C)\n\t}\n\tb.runWorkers()\n\n\tfmt.Printf(\"Finished %d requests\\n\\n\", totalRequests)\n\tclose(requestCountChan)\n\n\tnewReport(b.N, b.results, b.Output, time.Now().Sub(start)).finalize()\n\tclose(b.results)\n\t//<-quit\n}", "func (r *InstanceRead) Run() {\n\tvar err error\n\n\tfor statement, prepStmt := range map[string]**sql.Stmt{\n\t\tstmt.InstanceScopedList: &r.stmtList,\n\t\tstmt.InstanceShow: &r.stmtShow,\n\t\tstmt.InstanceVersions: &r.stmtVersions,\n\t} {\n\t\tif *prepStmt, err = r.conn.Prepare(statement); err != nil {\n\t\t\tr.errLog.Fatal(`instance`, err, stmt.Name(statement))\n\t\t}\n\t\tdefer (*prepStmt).Close()\n\t}\n\nrunloop:\n\tfor {\n\t\tselect {\n\t\tcase <-r.Shutdown:\n\t\t\tbreak runloop\n\t\tcase req := <-r.Input:\n\t\t\tgo func() {\n\t\t\t\tr.process(&req)\n\t\t\t}()\n\t\t}\n\t}\n}", "func (e *EndpointsManager) Run() {\n\tticker := time.NewTicker(time.Second * 10)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\te.watchAliveEndpoint()\n\t\tcase <-e.exit:\n\t\t\tclose(e.closed)\n\t\t\tcommon.Logger.Info(\"service done!!!\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func runMonitor(requests []Request, env Environment, testname string, verbose bool, filename string, delay int) {\n\tfor {\n\t\ttotalRequests, failCount := runRequests(requests, env, testname, verbose, true)\n\n\t\tlog.Println(\"Total requests:\", totalRequests)\n\n\t\tif failCount > 0 {\n\t\t\tlog.Printf(\"FAIL %s (%v requests, %v failed)\", filename, totalRequests, failCount)\n\t\t} else {\n\t\t\tlog.Printf(\"PASSED %s (%v requests)\", filename, totalRequests)\n\t\t}\n\n\t\ttime.Sleep(time.Duration(delay) * time.Second)\n\t}\n}", "func (w *CrawlerWorker) Run() {\n\tfor _, j := range w.jobs {\n\t\tgo w.crawler.ProcessJob(*j)\n\t}\n\tw.ClearJobs()\n}", "func (s *Consumer) Run() error {\n\t// check queue status\n\tselect {\n\tcase <-s.stop:\n\t\treturn ErrQueueShutdown\n\tdefault:\n\t}\n\n\tfor task := range s.taskQueue {\n\t\tvar data Job\n\t\t_ = json.Unmarshal(task.Bytes(), &data)\n\t\tif v, ok := task.(Job); ok {\n\t\t\tif v.Task != nil {\n\t\t\t\tdata.Task = v.Task\n\t\t\t}\n\t\t}\n\t\tif err := s.handle(data); err != nil {\n\t\t\ts.logger.Error(err.Error())\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error {\n\tvar resourceVersion string\n\tresyncCh, cleanup := r.resyncChan()\n\tdefer cleanup()\n\n\t// list, err := r.listerWatcher.List()\n\t// if err != nil {\n\t// \tglog.Errorf(\"Failed to list %v: %v\", r.expectedType, err)\n\t// \treturn fmt.Errorf(\"%s: Failed to list %v: %v\", r.name, r.expectedType, err)\n\t// }\n\t// glog.V(4).Infof(\"The list from listerWatcher is %v\", list)\n\t// meta, err := meta.Accessor(list)\n\t// if err != nil {\n\t// \tglog.Errorf(\"%s: Unable to understand list result %#v\", r.name, list)\n\t// \treturn fmt.Errorf(\"%s: Unable to understand list result %#v\", r.name, list)\n\t// }\n\t// glog.Infof(\"meta is %v\", meta)\n\t// resourceVersion = meta.ResourceVersion()\n\t// items, err := ExtractList(list)\n\t// // items := list.([]interface{})\n\n\t// if err != nil {\n\t// \tglog.Errorf(\"%s: Unable to understand list result %#v (%v)\", r.name, list, err)\n\t// \treturn fmt.Errorf(\"%s: Unable to understand list result %#v (%v)\", r.name, list, err)\n\t// }\n\t// if err := r.syncWith(items, resourceVersion); err != nil {\n\t// \tglog.Errorf(\"%s: Unable to sync list result: %v\", r.name, err)\n\t// \treturn fmt.Errorf(\"%s: Unable to sync list result: %v\", r.name, err)\n\t// }\n\t// r.setLastSyncResourceVersion(resourceVersion)\n\n\tresourceVersion = \"0\"\n\n\tfor {\n\t\tw, err := r.listerWatcher.Watch(resourceVersion)\n\n\t\tif err != nil {\n\t\t\tif etcdError, ok := err.(*etcderr.Error); ok && etcdError != nil && etcdError.ErrorCode == etcderr.EcodeKeyNotFound {\n\t\t\t\t// glog.Errorf(\"Key not found Error: %v\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch err {\n\t\t\tcase io.EOF:\n\t\t\t\t// watch closed normally\n\t\t\tcase io.ErrUnexpectedEOF:\n\t\t\t\tglog.V(1).Infof(\"%s: Watch for %v closed with unexpected EOF: %v\", r.name, r.expectedType, err)\n\t\t\tdefault:\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Failed to watch %v: %v\", r.name, r.expectedType, err))\n\t\t\t}\n\t\t\t// If this is \"connection refused\" error, it means that most likely apiserver is not responsive.\n\t\t\t// It doesn't make sense to re-list all objects because most likely we will be able to restart\n\t\t\t// watch where we ended.\n\t\t\t// If that's the case wait and resend watch request.\n\t\t\tif urlError, ok := err.(*url.Error); ok {\n\t\t\t\tif opError, ok := urlError.Err.(*net.OpError); ok {\n\t\t\t\t\tif errno, ok := opError.Err.(syscall.Errno); ok && errno == syscall.ECONNREFUSED {\n\t\t\t\t\t\tglog.Warningf(\"Sleep, Zzzzzzzzzzzzzz\")\n\t\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tglog.Errorf(\"Error during calling watch: %v\", err)\n\t\t\treturn nil\n\t\t}\n\t\tglog.V(5).Infof(\"watch from listerWather is %v\", w)\n\n\t\tif err := r.watchHandler(w, &resourceVersion, resyncCh, stopCh); err != nil {\n\t\t\tif err != errorResyncRequested && err != errorStopRequested {\n\t\t\t\tglog.Warningf(\"%s: watch of %v ended with: %v\", r.name, r.expectedType, err)\n\t\t\t}\n\t\t\tglog.Error(\"Error calling watchHandler: %s. Return from for loop in ListAndWatch.\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *AutoScaler) Run() {\n\tticker := s.clock.NewTicker(s.pollPeriod)\n\ts.readyCh <- struct{}{} // For testing.\n\n\t// Don't wait for ticker and execute pollAPIServer() for the first time.\n\ts.pollAPIServer()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C():\n\t\t\ts.pollAPIServer()\n\t\tcase <-s.stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (mc *ServiceWatcher) StartWatcher(quitCh chan struct{}, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tfor {\n\t\twatcher := cache.NewListWatchFromClient(mc.clientset.CoreV1().RESTClient(), mc.resourceStr, v1.NamespaceAll, fields.Everything())\n\t\tretryWatcher, err := watchClient.NewRetryWatcher(mc.lastRV, watcher)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Could not start watcher for k8s resource: \" + mc.resourceStr)\n\t\t}\n\n\t\tresCh := retryWatcher.ResultChan()\n\t\trunWatcher := true\n\t\tfor runWatcher {\n\t\t\tselect {\n\t\t\tcase <-quitCh:\n\t\t\t\treturn\n\t\t\tcase c := <-resCh:\n\t\t\t\ts, ok := c.Object.(*metav1.Status)\n\t\t\t\tif ok && s.Status == metav1.StatusFailure {\n\t\t\t\t\tif s.Reason == metav1.StatusReasonGone {\n\t\t\t\t\t\tlog.WithField(\"resource\", mc.resourceStr).Info(\"Requested resource version too old, no longer stored in K8S API\")\n\t\t\t\t\t\trunWatcher = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\t// Ignore and let the retry watcher retry.\n\t\t\t\t\tlog.WithField(\"resource\", mc.resourceStr).WithField(\"object\", c.Object).Info(\"Failed to read from k8s watcher\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Update the lastRV, so that if the watcher restarts, it starts at the correct resource version.\n\t\t\t\to, ok := c.Object.(*v1.Service)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tmc.lastRV = o.ObjectMeta.ResourceVersion\n\n\t\t\t\tpb, err := protoutils.ServiceToProto(o)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr := &storepb.K8SResource{\n\t\t\t\t\tResource: &storepb.K8SResource_Service{\n\t\t\t\t\t\tService: pb,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tmsg := &K8sResourceMessage{\n\t\t\t\t\tObject: r,\n\t\t\t\t\tObjectType: mc.resourceStr,\n\t\t\t\t\tEventType: c.Type,\n\t\t\t\t}\n\t\t\t\tmc.updateCh <- msg\n\t\t\t}\n\t\t}\n\n\t\tlog.WithField(\"resource\", mc.resourceStr).Info(\"K8s watcher channel closed. Retrying\")\n\n\t\t// Wait 5 minutes before retrying, however if stop is called, just return.\n\t\tselect {\n\t\tcase <-quitCh:\n\t\t\treturn\n\t\tcase <-time.After(5 * time.Minute):\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func main() {\n\t// Load configuration.\n\t// @I Support providing configuration file for Cron component via cli options\n\t// @I Validate Cron component configuration when loading from JSON file\n\tvar cronConfig config.Config\n\terr := util.ReadJSONFile(CronConfigFile, &cronConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Load Schedules provided in the config, if we run on ephemeral storage mode.\n\tloadEphemeralSchedules(&cronConfig)\n\n\t// Channel that receives IDs of the Watches that are ready to be triggered.\n\ttriggers := make(chan int)\n\n\t// Channel that receives Schedules that are candidate for triggering.\n\tschedules := make(chan schedule.Schedule)\n\n\t// Search for candidate Schedules; it could be from a variety of sources.\n\tgo search(schedules, &cronConfig)\n\n\t// Listen to candidate Schedules and send them for execution as they come. We\n\t// do this in a goroutine so that we don't block the program yet.\n\tgo func() {\n\t\tfor schedule := range schedules {\n\t\t\tgo run(schedule, triggers, &cronConfig)\n\t\t}\n\t}()\n\n\t// Configuration required by the Watch API SDK.\n\t// @I Load Watch API SDK configuration from file or command line\n\tsdkConfig := sdk.Config{\n\t\tcronConfig.WatchAPI.BaseURL,\n\t\tcronConfig.WatchAPI.Version,\n\t}\n\n\t// Listen for IDs of Watches that are ready for triggering, and trigger them\n\t// as they come. We keep the channel open and the program stays on perpetual.\n\tfor watchID := range triggers {\n\t\tfmt.Printf(\"triggering Watch with ID \\\"%d\\\"\\n\", watchID)\n\t\terr := sdk.TriggerByID(watchID, sdkConfig)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}", "func (d *discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {\n\tfor c := time.Tick(time.Duration(d.refreshInterval) * time.Second); ; {\n\t\tvar srvs map[string][]string\n\t\tresp, err := http.Get(fmt.Sprintf(\"http://%s/v1/catalog/services\", d.address))\n\t\tif err != nil {\n\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error getting services list\", \"err\", err)\n\t\t\ttime.Sleep(time.Duration(d.refreshInterval) * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tb, err := io.ReadAll(resp.Body)\n\t\tio.Copy(io.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t\tif err != nil {\n\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error reading services list\", \"err\", err)\n\t\t\ttime.Sleep(time.Duration(d.refreshInterval) * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = json.Unmarshal(b, &srvs)\n\t\tresp.Body.Close()\n\t\tif err != nil {\n\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error parsing services list\", \"err\", err)\n\t\t\ttime.Sleep(time.Duration(d.refreshInterval) * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tgs []*targetgroup.Group\n\t\t// Note that we treat errors when querying specific consul services as fatal for this\n\t\t// iteration of the time.Tick loop. It's better to have some stale targets than an incomplete\n\t\t// list of targets simply because there may have been a timeout. If the service is actually\n\t\t// gone as far as consul is concerned, that will be picked up during the next iteration of\n\t\t// the outer loop.\n\n\t\tnewSourceList := make(map[string]bool)\n\t\tfor name := range srvs {\n\t\t\tif name == \"consul\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresp, err := http.Get(fmt.Sprintf(\"http://%s/v1/catalog/service/%s\", d.address, name))\n\t\t\tif err != nil {\n\t\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error getting services nodes\", \"service\", name, \"err\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttg, err := d.parseServiceNodes(resp, name)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error parsing services nodes\", \"service\", name, \"err\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttgs = append(tgs, tg)\n\t\t\tnewSourceList[tg.Source] = true\n\t\t}\n\t\t// When targetGroup disappear, send an update with empty targetList.\n\t\tfor key := range d.oldSourceList {\n\t\t\tif !newSourceList[key] {\n\t\t\t\ttgs = append(tgs, &targetgroup.Group{\n\t\t\t\t\tSource: key,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\td.oldSourceList = newSourceList\n\t\tif err == nil {\n\t\t\t// We're returning all Consul services as a single targetgroup.\n\t\t\tch <- tgs\n\t\t}\n\t\t// Wait for ticker or exit when ctx is closed.\n\t\tselect {\n\t\tcase <-c:\n\t\t\tcontinue\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *SchedulerController) Run(ctx context.Context) {\n\tvar waitGroup sync.WaitGroup\n\n\tif !cache.WaitForCacheSync(ctx.Done(), c.hasSyncedFuncs...) {\n\t\tlogger.Logger.Error(\"Timed out waiting for caches to sync\")\n\t\treturn\n\t}\n\n\t// Count number of running workers.\n\tgo func() {\n\t\tfor res := range c.workerCh {\n\t\t\tc.numberOfRunningWorkers += res\n\t\t\tlogger.Logger.Debugf(\"Current number of running Scheduler workers is %d\", c.numberOfRunningWorkers)\n\t\t}\n\t}()\n\n\tfor i := 0; i < c.config.Schedulers.Shoot.ConcurrentSyncs; i++ {\n\t\tcontrollerutils.CreateWorker(ctx, c.shootQueue, \"Shoot\", c.reconciler, &waitGroup, c.workerCh)\n\t}\n\n\tlogger.Logger.Infof(\"Shoot Scheduler controller initialized with %d workers (with Strategy: %s)\", c.config.Schedulers.Shoot.ConcurrentSyncs, c.config.Schedulers.Shoot.Strategy)\n\n\t<-ctx.Done()\n\tc.shootQueue.ShutDown()\n\n\tfor {\n\t\tif c.shootQueue.Len() == 0 && c.numberOfRunningWorkers == 0 {\n\t\t\tlogger.Logger.Debug(\"No running Scheduler worker and no items left in the queues. Terminated Scheduler controller...\")\n\t\t\tbreak\n\t\t}\n\t\tlogger.Logger.Debugf(\"Waiting for %d Scheduler worker(s) to finish (%d item(s) left in the queues)...\", c.numberOfRunningWorkers, c.shootQueue.Len())\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\twaitGroup.Wait()\n}", "func (c *Collector) Run(ctx context.Context) error {\n\tdefer close(c.doneChan)\n\n\twatcher, cancel, err := store.ViewAndWatch(c.store, func(readTx store.ReadTx) error {\n\t\tnodes, err := store.FindNodes(readTx, store.All)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, node := range nodes {\n\t\t\tc.updateNodeState(nil, node)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cancel()\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-watcher:\n\t\t\tswitch v := event.(type) {\n\t\t\tcase api.EventCreateNode:\n\t\t\t\tc.updateNodeState(nil, v.Node)\n\t\t\tcase api.EventUpdateNode:\n\t\t\t\tc.updateNodeState(v.OldNode, v.Node)\n\t\t\tcase api.EventDeleteNode:\n\t\t\t\tc.updateNodeState(v.Node, nil)\n\t\t\t}\n\t\tcase <-c.stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (w *Watcher) Run() {\n\terr := w.Verify()\n\tif err != nil {\n\t\tw.ScheduleRun(120 * time.Second)\n\t}\n\tw.Watch()\n}", "func (s *Scraper) Run() {\n\tlog.Println(\"Collection cycle starting\")\n\t// Make sure we don't leave DB connections hanging open\n\tdefer s.writer.Close()\n\tvar wg sync.WaitGroup\n\t// For each collector\n\tfor _, collector := range s.collectors {\n\t\twg.Add(1)\n\t\tgo func(c Client) {\n\t\t\tdefer wg.Done()\n\t\t\terr := s.run(c)\n\t\t\tHandleMinorError(err)\n\t\t}(collector)\n\t}\n\twg.Wait()\n\tlog.Println(\"Collection cycle complete\")\n}" ]
[ "0.6950651", "0.67211396", "0.66870356", "0.66390353", "0.651078", "0.6471139", "0.64108497", "0.62734497", "0.62452585", "0.6224909", "0.6221336", "0.6209296", "0.6180416", "0.6116038", "0.6105096", "0.60590774", "0.60429734", "0.6036074", "0.6018043", "0.59669805", "0.5961872", "0.5943753", "0.593657", "0.59270775", "0.59257096", "0.59247494", "0.5922659", "0.5917093", "0.5886138", "0.58754003", "0.58599436", "0.58477163", "0.58401096", "0.5839118", "0.58257127", "0.58215773", "0.5814796", "0.5806874", "0.5805596", "0.5797708", "0.5793247", "0.578724", "0.57802236", "0.5778651", "0.5778595", "0.57732284", "0.57715714", "0.57698536", "0.57583207", "0.57537365", "0.5748809", "0.57469165", "0.5742449", "0.5736648", "0.5721029", "0.5707197", "0.5701249", "0.5692261", "0.56849957", "0.56836367", "0.5682675", "0.56776416", "0.5672115", "0.56695557", "0.5668726", "0.56617856", "0.5655844", "0.5649693", "0.56483346", "0.56435925", "0.5641966", "0.5641256", "0.56398904", "0.56381255", "0.56347257", "0.5627415", "0.5626134", "0.5619146", "0.5619113", "0.56160843", "0.56123275", "0.5604213", "0.5603931", "0.56000197", "0.559374", "0.5586343", "0.5581937", "0.55747944", "0.55738074", "0.5565356", "0.5555579", "0.55485934", "0.55482644", "0.55398923", "0.5538193", "0.5535691", "0.5533529", "0.55332893", "0.5532168", "0.552609", "0.55250204" ]
0.0
-1
GetUserList returns a list of Users
func GetUserList(w http.ResponseWriter, r *http.Request) { users, err := user.GetUserList(r) if err != nil { httpext.AbortAPI(w, err.Error(), http.StatusInternalServerError) return } httpext.SuccessDataAPI(w, "Ok", users) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *UsersClient) List(ctx context.Context, filter string) (*[]models.User, int, error) {\n\tparams := url.Values{}\n\tif filter != \"\" {\n\t\tparams.Add(\"$filter\", filter)\n\t}\n\tresp, status, _, err := c.BaseClient.Get(ctx, base.GetHttpRequestInput{\n\t\tValidStatusCodes: []int{http.StatusOK},\n\t\tUri: base.Uri{\n\t\t\tEntity: \"/users\",\n\t\t\tParams: params,\n\t\t\tHasTenantId: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tvar data struct {\n\t\tUsers []models.User `json:\"value\"`\n\t}\n\tif err := json.Unmarshal(respBody, &data); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &data.Users, status, 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 (retUser) List(ctx context.Context, db *sqlx.DB) ([]User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.user.list\")\n\tdefer span.End()\n\n\tusers := []User{}\n\tconst q = `SELECT * FROM users`\n\n\tif err := db.SelectContext(ctx, &users, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting users\")\n\t}\n\n\treturn users, nil\n}", "func (u *UserServiceHandler) List(ctx context.Context) ([]User, error) {\n\n\turi := \"/v1/user/list\"\n\n\treq, err := u.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar users []User\n\terr = u.client.DoWithContext(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn users, nil\n}", "func (u *UserService) List(ctx context.Context) ([]*User, *http.Response, error) {\n\treq, err := u.client.newRequest(\"GET\", \"user.list\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar users []*User\n\tresp, err := u.client.do(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn users, resp, nil\n}", "func (up *userProvider) List(ctx context.Context) ([]models.User, error) {\n\tusers, err := up.userStore.List(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (s *Service) List(c context.Context, req *user.ListReq) (*user.ListResp, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := s.auth.GetUser(c)\n\n\tlimit, offset := query.Paginate(req.Limit, req.Page)\n\n\tusers, err := s.udb.List(\n\t\ts.dbcl.WithContext(c),\n\t\tquery.ForTenant(u, req.TenantId),\n\t\tlimit,\n\t\toffset,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pu []*user.Resp\n\tfor _, v := range users {\n\t\tpu = append(pu, v.Proto())\n\t}\n\n\treturn &user.ListResp{Users: pu}, nil\n}", "func (us UserService) List(dto dto.GeneralListDto) ([]model.User, int64) {\n\treturn userDao.List(dto)\n}", "func (UserService) List(ctx context.Context, gdto dto.GeneralListDto) ([]model.User, int64) {\n\tcols := \"*\"\n\tgdto.Q, cols = dataPermService.DataPermFilter(ctx, \"users\", gdto)\n\treturn userDao.List(gdto, cols)\n}", "func (m *userManager) UserList() []string {\n\tuserList := make([]string, 0)\n\tm.db.View(func(tx *bolt.Tx) error {\n\t\tusers := tx.Bucket(m.usersBucket)\n\t\treturn users.ForEach(func(username, v []byte) error {\n\t\t\tuserList = append(userList, string(username))\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn userList\n}", "func (r repository) List(ctx context.Context, list *ListUsersRequest) ([]model.User, error) {\n\tusers := make([]model.User, 0)\n\toffset := (list.Page - 1) * list.Limit\n\terr := r.db.Select(&users, ListUsersSQL, offset, list.Limit)\n\tif err != nil {\n\t\tr.logger.Errorf(\"Failed to select users %s\", err)\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (us *UserService) List(p *Pagination) ([]User, error) {\n\treturn us.Datasource.List(p)\n}", "func (u *User) List() ([]*UserListRes, error) {\n\tvar users []db.Users\n\tif err := u.Sess.Asc(\"id\").Find(&users); err != nil {\n\t\treturn nil, err\n\t}\n\tres := make([]*UserListRes, len(users))\n\tfor i := 0; i < len(users); i++ {\n\t\tuser := users[i]\n\t\tres[i] = &UserListRes{ID: user.Id, Name: user.Name}\n\t}\n\treturn res, nil\n}", "func (cli *OpsGenieUserV2Client) List(req userv2.ListUsersRequest) (*userv2.ListUsersResponse, error) {\n\tvar response userv2.ListUsersResponse\n\terr := cli.sendGetRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (cs *UserService) List() ([]UsersResponse, error) {\n\n\treq, err := cs.client.NewRequest(\"GET\", \"/users\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := cs.client.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := validateResponse(resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBytes, _ := ioutil.ReadAll(resp.Body)\n\tbodyString := string(bodyBytes)\n\n\tu := &listUsersJSONResponse{}\n\terr = json.Unmarshal([]byte(bodyString), &u)\n\n\treturn u.Users, err\n}", "func (s *UsersService) List(opt *UsersOptions) ([]User, *http.Response, error) {\n\turi, err := addOptions(\"users\", opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tusers := new(Users)\n\tres, err := s.client.Get(uri, users)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\treturn users.Users, res, err\n}", "func (rep *UserRepo) List(ctx context.Context) ([]*User, error) {\n\tu := []*User{}\n\terr := rep.db.Query(\n\t\tctx,\n\t\trep.db.Select(\"*\").From(rep.table()),\n\t).Decode(&u)\n\treturn u, err\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn c.Render(200, r.JSON(users))\n}", "func (h *User) List(w http.ResponseWriter, r *http.Request) {\n\tlimit, offset := utils.GetPaginationParams(r.URL.Query())\n\tresp, err := h.Storage.GetUserList(limit, offset)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tif len(resp) < 1 {\n\t\tR.JSON404(w)\n\t\treturn\n\t}\n\n\tR.JSON200(w, resp)\n}", "func (s *UserServiceImpl) ListUser(c *gin.Context) ([]*models.User, error) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\tusers := []*models.User{}\n\terr := db.Find(&users).Error\n\treturn users, err\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 List(ctx context.Context, dbConn *db.DB) ([]User, error) {\n\tu := []User{}\n\n\tf := func(collection *mgo.Collection) error {\n\t\treturn collection.Find(nil).All(&u)\n\t}\n\tif err := dbConn.MGOExecute(ctx, usersCollection, f); err != nil {\n\t\treturn nil, errors.Wrap(err, \"db.users.find()\")\n\t}\n\n\treturn u, nil\n}", "func (us *UserService) List(ctx context.Context) ([]*resources.User, error) {\n\tdoc, err := us.list(ctx, \"one.userpool.info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\telements := doc.FindElements(\"USER_POOL/USER\")\n\n\tusers := make([]*resources.User, len(elements))\n\tfor i, e := range elements {\n\t\tusers[i] = resources.CreateUserFromXML(e)\n\t}\n\n\treturn users, nil\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 (m *Mgr) List(ctx context.Context) ([]*User, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tusers, err := m.list(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// hide passwords\n\tfor _, u := range users {\n\t\tu.Password = \"\"\n\t}\n\treturn users, nil\n}", "func (u *User) List(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.User.List\")\n\tdefer span.End()\n\n\tusers, err := user.List(ctx, u.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn web.Respond(ctx, w, users, http.StatusOK)\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn fmt.Errorf(\"no transaction found\")\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn err\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(http.StatusOK, r.Auto(c, users))\n}", "func List(ctx echo.Context) error {\n\tvar res []*userResponse\n\terr := db.Model(&User{}).Where(\"type = ?\", ctx.QueryParams().Get(\"type\")).Scan(&res).Error\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusBadRequest, &response{Code: 1})\n\t}\n\treturn ctx.JSON(http.StatusOK, &response{\n\t\tCode: 0,\n\t\tData: res,\n\t})\n}", "func GetUsers() {\n\tvar users []User\n\t_, err := orm.NewOrm().QueryTable(\"t_user\").Filter(\"name__contains\", \"awd\").All(&users)\n\tif err == nil {\n\t\tfor _, user := range users {\n\t\t\tfmt.Println(user.ToString())\n\t\t}\n\t}\n}", "func GetUsers(req *http.Request, render render.Render, account services.Account) {\n qs := req.URL.Query()\n userIDs := qs[\"userId\"]\n var users []models.User\n for _, userID := range userIDs {\n if user, err := account.GetUser(userID); err != nil {\n render.JSON(err.HttpCode, err)\n return\n } else {\n users = append(users, *user)\n }\n }\n render.JSON(http.StatusOK, users)\n}", "func (h *ServiceUsersHandler) List(ctx context.Context, project, serviceName string) ([]*ServiceUser, error) {\n\t// Aiven API does not provide list operation for service users, need to get them via service info instead\n\tservice, err := h.client.Services.Get(ctx, project, serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service.Users, nil\n}", "func getUserList() string {\n\tvar userlist string\n\tfmt.Println(len(Users))\n\tfor key, value := range Users {\n\t\tfmt.Println(\"key\", key, \"value\", value)\n\t\tuserlist = userlist + key + \"|\"\n\n\t}\n\treturn strings.TrimRight(userlist, \"|\")\n}", "func GetUsers(c *gin.Context) {\n\tvar users []models.User\n\tlog.Println(\"GetUsers from db\")\n\tdb := db.GetDB()\n\tdb.Find(&users)\n\tc.JSON(http.StatusOK, users)\n}", "func ListUser(email, password string) []User {\n\tvar u []User\n\tDb.Find(&u)\n\treturn u\n}", "func (h UserHTTP) List(w http.ResponseWriter, r *http.Request) {\n\tlistRequest := listRequestDecoder(r)\n\tusers, err := h.svc.ListUsers(r.Context(), listRequest)\n\tif err != nil {\n\t\th.logger.With(r.Context()).Errorf(\"list users error : %s\", err)\n\t\trender.Render(w, r, e.BadRequest(err, \"bad request\"))\n\t\treturn\n\t}\n\trender.Respond(w, r, users)\n}", "func (r mysqlRepo) GetUserList(ctx context.Context, page, perpage int) (data []User, total int, err error) {\n\tusers := make([]User, 0)\n\toffset := (page - 1) * perpage\n\tquery := \"SELECT id, username, email, created_at, updated_at FROM users limit ?,?\"\n\n\terr = r.db.Select(&users, query, offset, perpage)\n\tif err != nil {\n\t\tr.logger.Errorf(\"failed to get list of users %s\", err)\n\t\treturn\n\t}\n\n\treturn users, len(users), nil\n}", "func ListUser(ctx context.Context, tx *sql.Tx, request *models.ListUserRequest) (response *models.ListUserResponse, err error) {\n\tvar rows *sql.Rows\n\tqb := &common.ListQueryBuilder{}\n\tqb.Auth = common.GetAuthCTX(ctx)\n\tspec := request.Spec\n\tqb.Spec = spec\n\tqb.Table = \"user\"\n\tqb.Fields = UserFields\n\tqb.RefFields = UserRefFields\n\tqb.BackRefFields = UserBackRefFields\n\tresult := []*models.User{}\n\n\tif spec.ParentFQName != nil {\n\t\tparentMetaData, err := common.GetMetaData(tx, \"\", spec.ParentFQName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't find parents\")\n\t\t}\n\t\tspec.Filters = common.AppendFilter(spec.Filters, \"parent_uuid\", parentMetaData.UUID)\n\t}\n\n\tquery := qb.BuildQuery()\n\tcolumns := qb.Columns\n\tvalues := qb.Values\n\tlog.WithFields(log.Fields{\n\t\t\"listSpec\": spec,\n\t\t\"query\": query,\n\t}).Debug(\"select query\")\n\trows, err = tx.QueryContext(ctx, query, values...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"select query failed\")\n\t}\n\tdefer rows.Close()\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"row error\")\n\t}\n\n\tfor rows.Next() {\n\t\tvaluesMap := map[string]interface{}{}\n\t\tvalues := make([]interface{}, len(columns))\n\t\tvaluesPointers := make([]interface{}, len(columns))\n\t\tfor _, index := range columns {\n\t\t\tvaluesPointers[index] = &values[index]\n\t\t}\n\t\tif err := rows.Scan(valuesPointers...); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan failed\")\n\t\t}\n\t\tfor column, index := range columns {\n\t\t\tval := valuesPointers[index].(*interface{})\n\t\t\tvaluesMap[column] = *val\n\t\t}\n\t\tm, err := scanUser(valuesMap)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan row failed\")\n\t\t}\n\t\tresult = append(result, m)\n\t}\n\tresponse = &models.ListUserResponse{\n\t\tUsers: result,\n\t}\n\treturn response, nil\n}", "func (db *Database) GetUsersList() ([]*User, error) {\n\trows, err := db.db.Query(`\n\t\tSELECT id, username, owner FROM melodious.accounts WHERE banned=false;\n\t`)\n\tif err != nil {\n\t\treturn []*User{}, err\n\t}\n\tusers := []*User{}\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\terr := rows.Scan(&(user.ID), &(user.Username), &(user.Owner))\n\t\tif err != nil {\n\t\t\treturn []*User{}, err\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\treturn users, nil\n}", "func (m *manager) List(ctx context.Context, query *q.Query) (models.Users, error) {\n\tquery = q.MustClone(query)\n\tif query.Sorting == \"\" {\n\t\tquery.Sorting = \"username\"\n\t}\n\n\texcludeAdmin := true\n\tfor key := range query.Keywords {\n\t\tstr := strings.ToLower(key)\n\t\tif str == \"user_id__in\" {\n\t\t\texcludeAdmin = false\n\t\t\tbreak\n\t\t} else if str == \"user_id\" {\n\t\t\texcludeAdmin = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif excludeAdmin {\n\t\t// Exclude admin account when not filter by UserIDs, see https://github.com/goharbor/harbor/issues/2527\n\t\tquery.Keywords[\"user_id__gt\"] = 1\n\t}\n\n\treturn m.dao.List(ctx, query)\n}", "func (m *Mgr) list(ctx context.Context) (users []*User, err error) {\n\trows, err := m.db.QueryContext(ctx, `SELECT username, password FROM users`)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar u User\n\t\tif err = rows.Scan(&u.Username, &u.Password); err != nil {\n\t\t\treturn\n\t\t}\n\t\tusers = append(users, &u)\n\t}\n\treturn users, rows.Err()\n}", "func (c *DefaultIdentityProvider) ListUsers(ctx context.Context, options *metainternal.ListOptions) (*auth.UserList, error) {\n\tkeyword := \"\"\n\tlimit := 50\n\tif options.FieldSelector != nil {\n\t\tkeyword, _ = options.FieldSelector.RequiresExactMatch(auth.KeywordQueryTag)\n\t\tlimitStr, _ := options.FieldSelector.RequiresExactMatch(auth.QueryLimitTag)\n\t\tif li, err := strconv.Atoi(limitStr); err == nil && li > 0 {\n\t\t\tlimit = li\n\t\t}\n\t}\n\n\t_, tenantID := authentication.GetUsernameAndTenantID(ctx)\n\tif tenantID != \"\" && tenantID != c.tenantID {\n\t\treturn nil, apierrors.NewBadRequest(\"must in the same tenant\")\n\t}\n\n\tallList, err := c.localIdentityLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localIdentityList []*authv1.LocalIdentity\n\tfor i, item := range allList {\n\t\tif item.Spec.TenantID == c.tenantID {\n\t\t\tlocalIdentityList = append(localIdentityList, allList[i])\n\t\t}\n\t}\n\n\tif keyword != \"\" {\n\t\tvar newList []*authv1.LocalIdentity\n\t\tfor i, val := range localIdentityList {\n\t\t\tif strings.Contains(val.Name, keyword) || strings.Contains(val.Spec.Username, keyword) || strings.Contains(val.Spec.DisplayName, keyword) {\n\t\t\t\tnewList = append(newList, localIdentityList[i])\n\t\t\t}\n\t\t}\n\t\tlocalIdentityList = newList\n\t}\n\n\titems := localIdentityList[0:min(len(localIdentityList), limit)]\n\n\tuserList := auth.UserList{}\n\tfor _, item := range items {\n\t\tuser := convertToUser(item)\n\t\tuserList.Items = append(userList.Items, user)\n\t}\n\n\treturn &userList, nil\n}", "func (s *UserServer) List(ctx context.Context, in *pb.UserQuery) (*pb.UsersInfo, error) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tutils.GetLog().Error(\"rpc.user.List error: %+v\", err)\n\t\t}\n\t}()\n\n\tconfig := &users.Config{\n\t\tPageNum: int(in.Num),\n\t\tPageSize: int(in.Size),\n\t\tSearch: in.Search,\n\t\tIDs: in.IDs,\n\t}\n\n\tusers := users.NewUsers(config)\n\tif err = users.Do(); err != nil {\n\t\treturn nil, errors.New(users.ErrorCode().String())\n\t}\n\n\tsrvUsers := users.Users()\n\tcount := users.Count()\n\n\tvar pbUsers []*pb.UserInfo\n\tfor _, srvUser := range srvUsers {\n\t\tpbUser := srvUserToPbUser(srvUser)\n\t\tpbUsers = append(pbUsers, pbUser)\n\t}\n\n\treturn &pb.UsersInfo{Users: pbUsers, TotalNum: count}, nil\n}", "func ListUser(url, token string) {\n\tres, err := handleReadRequest(url, http.MethodGet, token)\n\tif err != nil {\n\t\tfmt.Println(\"Error\\n\")\n\t}\n\n\tvar apiResponse ListUsers\n\terr = json.Unmarshal(res, &apiResponse)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Print(\"List of users:\\n\")\n\tfor i:=0; i < len(apiResponse.Users); i++ {\n\t\tfmt.Print(apiResponse.Users[i],\"\\n\")\n\t}\n}", "func (e Endpoints) ListUsers(ctx context.Context, token string, args map[string]string) (users []registry.User, err error) {\n\trequest := ListUsersRequest{\n\t\tArgs: args,\n\t\tToken: token,\n\t}\n\tresponse, err := e.ListUsersEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListUsersResponse).Users, response.(ListUsersResponse).Err\n}", "func (c *Client) ListUsers() (*http.Response, error) {\n\treturn c.get(\"/user/listusers\", nil)\n}", "func ListUsers(w http.ResponseWriter, r *http.Request) {\n\tusers, err := dal.GetUsers(\"\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcommon.WriteResponse(w, users)\n}", "func (s *Service) List() *ListOp {\n\treturn &ListOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"users\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func (c *UsersController) List(ctx *app.ListUsersContext) error {\n\t// UsersController_List: start_implement\n\n\t// Put your logic here\n\tusers, err := models.UserList(c.db, ctx.Offset, ctx.Limit)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn ctx.InternalServerError(goa.ErrInternal(ErrInternalServerError))\n\t}\n\n\tres := app.UserCollection{}\n\n\tfor _, user := range users {\n\t\tuserMedia := &app.User{\n\t\t\tID: user.ID,\n\t\t\tScreenName: user.ScreenName,\n\t\t\tCreatedAt: user.CreatedAt.Unix(),\n\t\t\tUpdatedAt: user.UpdatedAt.Unix(),\n\t\t}\n\t\tres = append(res, userMedia)\n\t}\n\n\treturn ctx.OK(res)\n\t// UsersController_List: end_implement\n}", "func (s repoUserService) List(path string) ([]*api.User, error) {\n\trepoPath, err := api.NewRepoPath(path)\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\tusers, err := s.client.httpClient.ListRepoUsers(repoPath.GetNamespaceAndRepoName())\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\treturn users, nil\n}", "func (db *MySQLDB) ListUser(ctx context.Context, request *helper.PageRequest) ([]*User, *helper.Page, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"ListUser\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\tcount, err := db.Count(ctx)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.Count got %s\", err.Error())\n\t\treturn nil, nil, err\n\t}\n\tpage := helper.NewPage(request, uint(count))\n\tuserList := make([]*User, 0)\n\n\tvar OrderBy string\n\tswitch strings.ToUpper(request.OrderBy) {\n\tcase \"EMAIL\":\n\t\tOrderBy = \"EMAIL\"\n\tcase \"ENABLED\":\n\t\tOrderBy = \"ENABLED\"\n\tcase \"SUSPENDED\":\n\t\tOrderBy = \"SUSPENDED\"\n\tcase \"LAST_SEEN\":\n\t\tOrderBy = \"LAST_SEEN\"\n\tcase \"LAST_LOGIN\":\n\t\tOrderBy = \"LAST_LOGIN\"\n\tdefault:\n\t\tOrderBy = \"EMAIL\"\n\t}\n\n\tq := fmt.Sprintf(\"SELECT REC_ID, EMAIL,HASHED_PASSPHRASE,ENABLED, SUSPENDED,LAST_SEEN,LAST_LOGIN,FAIL_COUNT,ACTIVATION_CODE,ACTIVATION_DATE,TOTP_KEY,ENABLE_2FE,TOKEN_2FE,RECOVERY_CODE FROM HANSIP_USER ORDER BY %s %s LIMIT %d, %d\", OrderBy, request.Sort, page.OffsetStart, page.OffsetEnd-page.OffsetStart)\n\trows, err := db.instance.QueryContext(ctx, q)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.QueryContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn nil, nil, &ErrDBQueryError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error ListUser\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\tvar enabled, suspended, enable2fa int\n\t\terr := rows.Scan(&user.RecID, &user.Email, &user.HashedPassphrase, &enabled, &suspended, &user.LastSeen, &user.LastLogin, &user.FailCount, &user.ActivationCode,\n\t\t\t&user.ActivationDate, &user.UserTotpSecretKey, &enable2fa, &user.Token2FA, &user.RecoveryCode)\n\t\tif err != nil {\n\t\t\tfLog.Warnf(\"rows.Scan got %s\", err.Error())\n\t\t\treturn nil, nil, &ErrDBScanError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error ListUser\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t} else {\n\t\t\tif enabled == 1 {\n\t\t\t\tuser.Enabled = true\n\t\t\t}\n\t\t\tif suspended == 1 {\n\t\t\t\tuser.Suspended = true\n\t\t\t}\n\t\t\tif enable2fa == 1 {\n\t\t\t\tuser.Enable2FactorAuth = true\n\t\t\t}\n\t\t\tuserList = append(userList, user)\n\t\t}\n\t}\n\treturn userList, page, nil\n}", "func (endpoint *Endpoint) ListUsers(ctx context.Context, fields string, filter string, sort string, min, max int) (*UsersPaginatedResponse, error) {\n\t// Options\n\toptions := []Option{}\n\toptions = append(options, WithParam(\"current_user\", \"false\"))\n\tif fields != \"\" {\n\t\toptions = append(options, WithParam(\"fields\", fields))\n\t}\n\tif filter != \"\" {\n\t\toptions = append(options, WithParam(\"filter\", filter))\n\t}\n\tif sort != \"\" {\n\t\toptions = append(options, WithParam(\"sort\", sort))\n\t}\n\toptions = append(options, WithHeader(\"Range\", fmt.Sprintf(\"items=%d-%d\", min, max)))\n\n\t// Do the request\n\tresp, err := endpoint.client.do(ctx, http.MethodGet, \"/config/access/users\", options...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while calling the endpoint: %s\", err)\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"error with the status code: %d\", resp.StatusCode)\n\t}\n\n\t// Process the Content-Range\n\tmin, max, total, err := parseContentRange(resp.Header.Get(\"Content-Range\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while parsing the content-range: %s\", err)\n\t}\n\n\t// Prepare the response\n\tresponse := &UsersPaginatedResponse{\n\t\tTotal: total,\n\t\tMin: min,\n\t\tMax: max,\n\t}\n\n\t// Decode the response\n\terr = json.NewDecoder(resp.Body).Decode(&response.User)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while decoding the response: %s\", err)\n\t}\n\n\treturn response, nil\n}", "func (m *UserResource) ListUsers(ctx context.Context, qp *query.Params) ([]*User, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users\")\n\tif qp != nil {\n\t\turl = url + qp.String()\n\t}\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 user []*User\n\n\tresp, err := rq.Do(ctx, req, &user)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn user, resp, nil\n}", "func (c client) UserList() ([]*User, error) {\n\tdata := url.Values{}\n\tdata.Set(\"token\", c.conf.Token)\n\tres, err := http.PostForm(\"https://slack.com/api/users.list\", data)\n\tif err != nil {\n\t\treturn []*User{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar list userlist\n\tif err = json.NewDecoder(res.Body).Decode(&list); err != nil {\n\t\treturn []*User{}, err\n\t}\n\treturn list.Members, nil\n}", "func ListUsers(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\trepo := users.NewUserRepository(db)\n\tutils.JsonResponse(w, repo.GetAllUsers([]users.User{}), http.StatusOK)\n}", "func GetUsers(c *gin.Context) {\n\tdb := dbConn()\n\tselDB, err := db.Query(\"CALL read_users()\")\n\tif err != nil {\n\t\tpanic(err.Error)\n\t}\n\n\tuser := User{}\n\tusers := []User{}\n\tfor selDB.Next() {\n\t\tvar id, username, useremail, fname, lname, password, passwordchange, passwordexpired, lastlogon, accountlocked string\n\t\terr = selDB.Scan(&id, &username, &useremail, &fname, &lname, &password, &passwordchange, &passwordexpired, &lastlogon, &accountlocked)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\tuser.ID = id\n\t\tuser.UserName = username\n\t\tuser.UserEmail = useremail\n\t\tuser.FName = fname\n\t\tuser.LName = lname\n\t\tuser.Password = password\n\t\tuser.PasswordChange = passwordchange\n\t\tuser.PasswordExpired = passwordexpired\n\t\tuser.LastLogon = lastlogon\n\t\tuser.AccountLocked = accountlocked\n\t\tiid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\tselDB02, err := db.Query(\"CALL read_access_userid(?)\", iid)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\taccess := Access{}\n\t\taccessList := []Access{}\n\t\tfor selDB02.Next() {\n\t\t\tvar accessid, userid, courtid, caseaccess, personaccess, accountingaccess, juryaccess, attorneyaccess, configaccess, securitylevel, sealedcase string\n\t\t\terr := selDB02.Scan(&accessid, &userid, &courtid, &caseaccess, &personaccess, &accountingaccess, &juryaccess, &attorneyaccess, &configaccess, &securitylevel, &sealedcase)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t})\n\t\t\t}\n\t\t\taccess.AccessID = accessid\n\t\t\taccess.IDUser = userid\n\t\t\taccess.IDCourt = courtid\n\t\t\taccess.CaseAccess = caseaccess\n\t\t\taccess.PersonAccess = personaccess\n\t\t\taccess.AccountingAccess = accountingaccess\n\t\t\taccess.JuryAccess = juryaccess\n\t\t\taccess.AttorneyAccess = attorneyaccess\n\t\t\taccess.ConfigAccess = configaccess\n\t\t\taccess.SecurityLevel = securitylevel\n\t\t\taccess.SealedCase = sealedcase\n\t\t\taccessList = append(accessList, access)\n\t\t}\n\t\tuser.AccessList = accessList\n\t\tusers = append(users, user)\n\t}\n\n\tc.JSON(200, gin.H{\n\t\t\"result\": users,\n\t})\n\n\tdefer db.Close()\n}", "func (c Client) GetUsers(query url.Values) ([]UserItem, error) {\r\n\r\n\tvar res struct {\r\n\t\tRecords []UserItem\r\n\t}\r\n\terr := c.GetRecordsFor(TableUser, query, &res)\r\n\treturn res.Records, err\r\n}", "func GetUsers(w http.ResponseWriter, r *http.Request) {\n\tvar users []UsersData\n\terr := model.FindAll(nil, &users)\n\tif err != nil {\n\t\tfmt.Println(\"err\", err)\n\t\tw.Write([]byte(\"Something wen't wrong!!\"))\n\t} else {\n\t\trender.JSON(w, 200, &users)\n\t}\n}", "func (c *Client) ListUsers(ctx context.Context) ([]*models.User, error) {\n\tvar resp struct {\n\t\tUsers []*models.User `json:\"users\"`\n\t}\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery Users {\n\t\t\tusers {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, nil, &resp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Users, nil\n}", "func (c *UsersController) List(ctx *app.ListUsersContext) error {\n\t// UsersController_List: start_implement\n\n\t// Put your logic here\n\tcognitoUserID := ctx.Params.Get(\"cognitoAuthUserId\")\n\tuserID, err := c.db.GetUserIDByCognitoUserID(cognitoUserID)\n\tif err != nil {\n\t\tlog.Errorf(\"[controller/user] failed to get user id: %v\", err)\n\t\treturn ctx.InternalServerError(&app.StandardError{\n\t\t\tCode: 500,\n\t\t\tMessage: \"could not retrieve user data\",\n\t\t})\n\t}\n\n\tuser := &types.User{\n\t\tID: userID,\n\t\tCognitoAuthUserID: cognitoUserID,\n\t}\n\n\tif user == nil {\n\t\tlog.Errorf(\"[controller/user] user not found: %v\", userID)\n\t\treturn ctx.NotFound(&app.StandardError{\n\t\t\tCode: 400,\n\t\t\tMessage: \"user not found\",\n\t\t})\n\t}\n\n\tres := &app.User{\n\t\tID: user.ID,\n\t\tCognitoAuthUserID: &user.CognitoAuthUserID,\n\t}\n\treturn ctx.OK(res)\n\t// UsersController_List: end_implement\n}", "func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {\n\tcon, err := g.initLdap()\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"Failed to initialize ldap\")\n\t\terrorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// TODO make filter configurable\n\tresult, err := g.ldapSearch(con, \"(objectClass=posixAccount)\", g.config.Ldap.BaseDNUsers)\n\n\tif err != nil {\n\t\tg.logger.Error().Err(err).Msg(\"Failed search ldap with filter: '(objectClass=posixAccount)'\")\n\t\terrorcode.ServiceNotAvailable.Render(w, r, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tusers := make([]*msgraph.User, 0, len(result.Entries))\n\n\tfor _, user := range result.Entries {\n\t\tusers = append(\n\t\t\tusers,\n\t\t\tcreateUserModelFromLDAP(\n\t\t\t\tuser,\n\t\t\t),\n\t\t)\n\t}\n\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, &listResponse{Value: users})\n}", "func (u *UsersController) List(ctx *gin.Context) {\n\tcriteria := u.buildCriteria(ctx)\n\n\tvar listAsAdmin bool\n\tif isTatAdmin(ctx) {\n\t\tlistAsAdmin = true\n\t} else {\n\t\tuser, e := PreCheckUser(ctx)\n\t\tif e != nil {\n\t\t\tctx.AbortWithError(http.StatusInternalServerError, e)\n\t\t\treturn\n\t\t}\n\t\tlistAsAdmin = user.CanListUsersAsAdmin\n\t}\n\tcount, users, err := userDB.ListUsers(criteria, listAsAdmin)\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tout := &tat.UsersJSON{\n\t\tCount: count,\n\t\tUsers: users,\n\t}\n\tctx.JSON(http.StatusOK, out)\n}", "func (service *UserService) ListUsers() ([]models.User, error) {\n\tvar list []models.User\n\tfor _, v := range service.UserList {\n\t\tlist = append(list, v)\n\t}\n\treturn list, nil\n}", "func GetUsers(c *gin.Context) {\n\tvar users []models.User\n\tdb := db.GetDB()\n\tdb.Find(&users)\n\tc.JSON(200, users)\n}", "func (r *UsersService) List() *UsersListCall {\n\tc := &UsersListCall{s: r.s, opt_: make(map[string]interface{})}\n\treturn c\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Mohomaaf ...dsb\", nil, nil)\n\t\t}\n\t}()\n\n\tfLog := userMgmtLogger.WithField(\"func\", \"ListAllUsers\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Listing Users\")\n\tpageRequest, err := helper.NewPageRequestFromRequest(r)\n\tif err != nil {\n\t\tfLog.Errorf(\"helper.NewPageRequestFromRequest got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tusers, page, err := UserRepo.ListUser(r.Context(), pageRequest)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.ListUser got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tsusers := make([]*SimpleUser, len(users))\n\tfor i, v := range users {\n\t\tsusers[i] = &SimpleUser{\n\t\t\tRecID: v.RecID,\n\t\t\tEmail: v.Email,\n\t\t\tEnabled: v.Enabled,\n\t\t\tSuspended: v.Suspended,\n\t\t}\n\t}\n\tret := make(map[string]interface{})\n\tret[\"users\"] = susers\n\tret[\"page\"] = page\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"List of all user paginated\", nil, ret)\n}", "func (c *Client) ListUsers() ([]User, error) {\n\tusers := []User{}\n\t_, err := c.sling.Get(\"users\").ReceiveSuccess(&users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func GetUsers(w http.ResponseWriter, r *http.Request) {\n\tloginOrName := strings.ToLower(r.URL.Query().Get(\"user\"))\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tusers, err := repository.SearchByLoginOrName(loginOrName)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusOK, users)\n\n}", "func (client IdentityClient) listUsers(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/users\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListUsersResponse\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 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 (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {\n\tsanitizedPath := strings.TrimPrefix(r.URL.Path, \"/graph/v1.0/\")\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\tusers, err := g.identityBackend.GetUsers(r.Context(), r.URL.Query())\n\tif err != nil {\n\t\tvar errcode errorcode.Error\n\t\tif errors.As(err, &errcode) {\n\t\t\terrcode.Render(w, r)\n\t\t} else {\n\t\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tusers, err = sortUsers(odataReq, users)\n\tif err != nil {\n\t\tvar errcode errorcode.Error\n\t\tif errors.As(err, &errcode) {\n\t\t\terrcode.Render(w, r)\n\t\t} else {\n\t\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\t}\n\t\treturn\n\t}\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, &listResponse{Value: users})\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request){\n\n\trows, err:= db.Query(\"SELECT * FROM users LIMIT 20\")\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tlistUsers := Users{}\n\tfor rows.Next() {\n\t\tp := User{}\n\t\tif err := rows.Scan(&p.ID, &p.Name, &p.Score); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlistUsers = append(listUsers, p)\n\n\t}\n\tdefer rows.Close()\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tjson.NewEncoder(w).Encode(listUsers)\n}", "func (service Service) GetList(pagination entity.Pagination) (ug []entity.UserGroup, count int, err error) {\n\tusers, count, err := service.repository.GetList(pagination)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tug, err = service.mapUsersToUserGroups(users)\n\treturn\n}", "func (a Authorizer) ListUsers() (users []models.User, err error) {\n\tif users, err = a.userDao.Users(nil); err != nil {\n\t\tlogger.Get().Error(\"Unable get the list of users. error: %v\", err)\n\t\treturn users, err\n\t}\n\treturn users, nil\n}", "func GetUsers(c *fiber.Ctx) {\n\tvar users []User\n\tdatabase.DBConn.Find(&users)\n\tc.JSON(users)\n}", "func userList(w http.ResponseWriter, r *http.Request) {}", "func (a *Server) ListUsers(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"lists all users\")\n}", "func GetUsers(c *gin.Context) {\n\tvar user []Models.User\n\tvar u Models.User\n\terr := Models.GetAllUsers(&user)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tlog.Println(\"====== Bind By Query String ======\")\n\t\tlog.Println(u.Nombre)\n\t\t//var rubro []Models.RubroUsuario\n\t \n\t\tfmt.Println(c.Request.URL.Query())\n\t\t page, _ := strconv.Atoi(c.DefaultQuery(\"page\", \"1\"))\n\t\t limit, _ := strconv.Atoi(c.DefaultQuery(\"limit\", \"50\"))\n\t\n\t\t paginator := pagination.Paging(&pagination.Param{\n\t\t\tDB: Config.DB.Preload(\"Rubros\").Preload(\"Unidades\"),\n\t\t\tPage: page,\n\t\t\tLimit: limit,\n\t\t\tOrderBy: []string{\"id\"},\n\t\t\tShowSQL: true,\n\t\t}, &user)\n \n\t\tc.JSON(200, paginator)\n\n\t}\n}", "func (u *UserModel) List(limit int, offset int, order string) ([]*models.User, error) {\n\torderOpts := map[string]string{\n\t\t\"firstName\": \"first_name\",\n\t\t\"lastName\": \"last_name\",\n\t\t\"email\": \"email\",\n\t\t\"created\": \"created\",\n\t\t\"status\": \"s.name\",\n\t}\n\n\tif val, ok := orderOpts[order]; ok {\n\t\torder = val\n\t} else {\n\t\torder = \"created\"\n\t}\n\n\tstmt := fmt.Sprintf(`SELECT u.id, u.uuid, first_name, last_name, email, phone, s.slug, u.created\n\t\t\t FROM user AS u\n\t\t LEFT JOIN ref_user_status AS s ON u.status_id = s.id\n\t\t ORDER BY %s\n\t\t\t LIMIT ?,?`, order)\n\n\tif limit < 1 {\n\t\tlimit = DEFAULT_LIMIT\n\t}\n\n\trows, err := u.DB.Query(stmt, offset, limit)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tusers := []*models.User{}\n\n\tfor rows.Next() {\n\t\tu := &models.User{}\n\t\terr = rows.Scan(&u.ID, &u.UUID, &u.FirstName, &u.LastName, &u.Email, &u.Phone, &u.Status, &u.Created)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, u)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (s *UsersService) List() *UsersListCall {\n\tvar call UsersListCall\n\tcall.service = s\n\treturn &call\n}", "func GetUsers(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"getting all users\")\n\tvar users []entity.User\n\terr := model.GetAllUsers(&users, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tfor _, user := range users {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n}", "func GetAllUsers() []*User {\n\tUserListLock.Acquire(\"get all users\")\n\tdefer UserListLock.Release()\n\tlst := make([]*User, len(UserList))\n\ti := 0\n\tfor _, val := range UserList {\n\t\tlst[i] = val\n\t\ti += 1\n\t}\n\treturn lst\n}", "func ListUsers(db *pg.DB) ([]*models.User, error) {\n\tvar users []*models.User\n\n\t_, err := db.Query(&users, `SELECT * FROM Users`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Print names and PK\n\tfor i, n := range users {\n\t\tfmt.Println(i, n.UserName, n.Password, n.Email)\n\t}\n\treturn users, nil\n}", "func (h *Handler) GetUsers() ([]models.User, error) {\n\tquery := \"SELECT id, first_name, last_name, email, password FROM users;\"\n\trows, err := h.DB.Query(query)\n\tif err != nil {\n\t\tfmt.Printf(\"user_service-GetUsers-query: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tvar users []models.User\n\n\tfor rows.Next(){\n\t\tuser := models.User{}\n\t\t\n\t\terr := rows.Scan(\n\t\t\t&user.ID,\n\t\t\t&user.FirstName,\n\t\t\t&user.LastName,\n\t\t\t&user.Email,\n\t\t\t&user.Password,\n\t\t)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"user_service-GetUsers-Scan: %s \\n\",err)\n\t\t}\n\t\t\n\t\tusers = append(users, user)\n\t}\n\n\treturn users, nil\n}", "func UsersGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tlog.Println(\"starting retrieval\")\n\tstart := 0\n\tlimit := 10\n\n\tnext := start + limit\n\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\tw.Header().Set(\"Link\", \"<http://localhost:8080/api/users?start=\"+string(next)+\"; rel=\\\"next\\\"\")\n\n\trows, _ := database.Query(\"SELECT * FROM users LIMIT 10\")\n\n\tusers := Users{}\n\n\tfor rows.Next() {\n\t\tuser := User{}\n\t\trows.Scan(&user.ID, &user.Username, &user.First, &user.Last, &user.Email)\n\t\tusers.Users = append(users.Users, user)\n\t}\n\n\toutput, err := json.Marshal(users)\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Something went wrong while processing your request: \", err)\n\t}\n\n\tfmt.Fprintln(w, string(output))\n}", "func (store *Storage) ListUsers() ([]string, error) {\n\treturn store.Back.ListUsers()\n}", "func (s *Shell) ListUsers(_ *cli.Context) (err error) {\n\tresp, err := s.HTTP.Get(\"/v2/users/\", nil)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := resp.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(resp, &AdminUsersPresenters{})\n}", "func ListUsers() ([]*User, error) {\n\tvar users []*User\n\terr := meddler.QueryAll(db, &users, userStmt)\n\treturn users, err\n}", "func (s *initServer) GetUserListFilter(ctx context.Context, in *pb.UserListRequest) (*pb.UserListResponse, error) {\t\n\treturn userListTempl(ctx, in, \"userListFilter:user\", true)\n}", "func GetUsers(db *sql.DB) ([]models.UserResponse, error) {\n\n\trows, err := db.Query(\"SELECT id, username, email, createdAt FROM users\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpersons := make([]models.UserResponse, 0)\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar username string\n\t\tvar email string\n\t\tvar createdAt time.Time\n\t\terr = rows.Scan(&id, &username, &email, &createdAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpersons = append(persons, models.UserResponse{ID: id, Username: username, CreatedAt: createdAt})\n\t}\n\treturn persons, nil\n}", "func (c *Client) ListUser(ctx context.Context, path string) (*http.Response, error) {\n\tvar body io.Reader\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", 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\tc.SignerJWT.Sign(ctx, req)\n\treturn c.Client.Do(ctx, req)\n}", "func getUsers(types int) {\n\treq, _ := http.NewRequest(\"GET\", cfg.Main.Server+\"users\", nil)\n\treq.Header.Set(\"Content-Type\", \"application/xml\")\n\treq.Header.Set(\"Authorization\", cfg.Main.Key)\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tp(\"Couldn't connect to Openfire server: %s\", err.Error())\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tp(\"Error requesting userlist from the server.\")\n\t\treturn\n\t}\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tvar users XMLUsers\n\txml.Unmarshal(body, &users)\n\tfor _, e := range users.User {\n\t\tn := e.Username + \",\"\n\t\tif e.Name != \"\" {\n\t\t\tn = e.Username + \",\" + e.Name\n\t\t}\n\t\tswitch types {\n\t\tcase 0:\n\t\t\tm := \"<missing e-mail>\"\n\t\t\tif e.Email != \"\" {\n\t\t\t\tm = e.Email\n\t\t\t}\n\t\t\tp(\"%s,%s\", n, m)\n\t\tcase 1:\n\t\t\tif e.Email != \"\" {\n\t\t\t\tp(\"%s,%s\", n, e.Email)\n\t\t\t}\n\t\tcase 2:\n\t\t\tif e.Email == \"\" {\n\t\t\t\tp(\"%s\", n)\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *AdminAPI) ListUsers(ctx context.Context) ([]string, error) {\n\tvar users []string\n\treturn users, a.sendAny(ctx, http.MethodGet, usersEndpoint, nil, &users)\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 (r *UserRead) list(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tuserID, userName string\n\t\trows *sql.Rows\n\t\terr error\n\t)\n\n\tif rows, err = r.stmtList.Query(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(\n\t\t\t&userID,\n\t\t\t&userName,\n\t\t); err != nil {\n\t\t\trows.Close()\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\t\tmr.User = append(mr.User, proto.User{\n\t\t\tID: userID,\n\t\t\tUserName: userName,\n\t\t})\n\t}\n\tif err = rows.Err(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tmr.OK()\n}", "func GetUsers(c *gin.Context) {\n\tvar users []models.User\n\tpagination := models.GeneratePaginationFromRequest(c)\n\terr := repository.GetAllUsersPaged(&users, &pagination)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, users)\n\t}\n}", "func (c CvpRestAPI) GetAllUsers(start, end int) (*UserList, error) {\n\tvar users UserList\n\n\tquery := &url.Values{\n\t\t\"queryparam\": {\"\"},\n\t\t\"startIndex\": {strconv.Itoa(start)},\n\t\t\"endIndex\": {strconv.Itoa(end)},\n\t}\n\n\tresp, err := c.client.Get(\"/user/getUsers.do\", query)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"GetAllUsers: %s\", err)\n\t}\n\n\tif err = json.Unmarshal(resp, &users); err != nil {\n\t\treturn nil, errors.Errorf(\"GetAllUsers: %s Payload:\\n%s\", err, resp)\n\t}\n\n\tif err := users.Error(); err != nil {\n\t\t// Entity does not exist\n\t\tif users.ErrorCode == \"132801\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Errorf(\"GetAllUsers: %s\", err)\n\t}\n\treturn &users, nil\n}", "func GetUsers(c echo.Context) error {\n\tu := []*models.User{}\n\tfor _, v := range users {\n\t\tu = append(u, v)\n\t}\n\n\treturn c.JSON(http.StatusOK, u)\n}", "func GetUsers(c *gin.Context) {\n\trequestID := c.GetString(\"x-request-id\")\n\thelper.Logger(requestID, \"\").Infoln(\"RequestID= \", requestID)\n\t// cacheTest := helper.CacheExists(\"xxxxxxxxxx\")\n\t// helper.Logger(requestID, \"\").Infoln(\"cacheTest= \", cacheTest)\n\n\thttpCode, body, erro := helper.MakeHTTPRequest(\"GET\", \"https://api-101.glitch.me/customers\", \"\", nil, true)\n\thelper.Logger(requestID, \"\").Infoln(\"httpCode= \", httpCode)\n\thelper.Logger(requestID, \"\").Infoln(\"body= \", fmt.Sprintf(\"%s\", body))\n\thelper.Logger(requestID, \"\").Infoln(\"error= \", erro)\n\n\tvar user []models.User\n\terr := models.GetAllUsers(&user)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func (h *Handler) GetUsers(w http.ResponseWriter, r *http.Request) {\n\tvar users []User\n\tcur, err := h.Collection.Find(context.TODO(), bson.D{{}}, options.Find())\n\tif err != nil {\n\t\th.Logger.Errorf(\"err retrieving cursor item: %s\", err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\tfor cur.Next(context.TODO()) {\n\t\tuser := &User{}\n\t\terr := cur.Decode(&user)\n\t\tif err != nil {\n\t\t\th.Logger.Errorf(\"err decoding item: %s\", err)\n\t\t\thttp.Error(w, http.StatusText(500), 500)\n\t\t\treturn\n\t\t}\n\t\tuser.Password = \"\" // Never return password hashes\n\t\tusers = append(users, *user)\n\t}\n\trender.JSON(w, r, users) // A chi router helper for serializing and returning json\n}", "func (uc UserController) GetUsers(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\n\tvar ul []models.User\n\n\t// Fetch user\n\tif err := uc.session.DB(\"todos\").C(\"users\").Find(nil).All(&ul); err != nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Marshal provided interface into JSON structure\n\tuj, _ := json.Marshal(ul)\n\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}" ]
[ "0.8061143", "0.80199534", "0.7991874", "0.79858255", "0.7920047", "0.79061973", "0.77202743", "0.7713175", "0.7689258", "0.76788044", "0.7641432", "0.7624448", "0.7622708", "0.7591941", "0.7590967", "0.7556658", "0.7533012", "0.7503844", "0.7492885", "0.748036", "0.74627477", "0.7458164", "0.74459964", "0.74387854", "0.7420172", "0.7395414", "0.73920053", "0.7369442", "0.7353476", "0.7344854", "0.7336067", "0.7332756", "0.7323417", "0.73198754", "0.7316951", "0.73158205", "0.7314867", "0.73130935", "0.7299433", "0.72973174", "0.7296035", "0.72857165", "0.7283409", "0.72793454", "0.7251931", "0.72441244", "0.71950686", "0.7187178", "0.7185584", "0.7179236", "0.71763295", "0.71741515", "0.7155985", "0.71547014", "0.7154497", "0.7149845", "0.7141729", "0.71374077", "0.7135287", "0.7132725", "0.7121248", "0.71200633", "0.7115014", "0.71131617", "0.710838", "0.7098961", "0.709351", "0.70932466", "0.7078097", "0.707649", "0.7073898", "0.7069119", "0.70656776", "0.7056986", "0.7049467", "0.7026776", "0.7022604", "0.7018648", "0.7012705", "0.70091945", "0.69903636", "0.6971964", "0.69716746", "0.69705176", "0.6965289", "0.6964501", "0.69611126", "0.69574875", "0.6952497", "0.6947113", "0.6946255", "0.69447815", "0.69417846", "0.6941144", "0.6936249", "0.69099987", "0.6903162", "0.6898569", "0.6894568", "0.6891613" ]
0.7878952
6
CreateUser creates a user
func CreateUser(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var update models.User err := decoder.Decode(&update) u, err := user.CreateUser(update, r) if err != nil { httpext.AbortAPI(w, err.Error(), http.StatusInternalServerError) return } httpext.SuccessDataAPI(w, "Ok", u) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\trequestBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tvar user models.User\n\tif err = json.Unmarshal(requestBody, &user); err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tdb, err := database.OpenDbConnection()\n\tif err != nil {\n\t\tlog.Fatal(\"error\")\n\t}\n\n\trepository := repositories.UserRepository(db)\n\trepository.Create(user)\n}", "func CreateUser(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user models.User\n\tif err := json.NewDecoder(req.Body).Decode(&user); err != nil {\n\t\tmsg := \"Error while reading input body\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\t// Helper function to generate encrypted password hash\n\tpasswordHash := helpers.GeneratePasswordHash(user.Password)\n\n\tif passwordHash == \"\" {\n\t\tmsg := \"Error occurred while hashing the password\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tuser.ID = bson.NewObjectId()\n\tuser.Password = passwordHash\n\n\terr := db.CreateUser(user)\n\tif err != nil {\n\t\tmsg := \"Error occurred while creating user\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tmsg := \"User created successfully\"\n\tutils.ReturnSuccessReponse(http.StatusCreated, msg, user.ID, res)\n\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User\n\tbodyRequest, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(bodyRequest, &user); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := user.Prepare(true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := validateUniqueDataUser(user, true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tuser.Id, err = repository.Insert(user)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusCreated, user)\n\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tu := User{}\n\terr := json.NewDecoder(r.Body).Decode(&u)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = SaveUser(u.FullName, u.NickName, u.Email, u.Balance)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (s *Service) CreateUser(c *tokay.Context) {\n\tuParams := userStruct{}\n\n\terr = c.BindJSON(&uParams)\n\tif errorAlert(\"Bind fall down\", err, c) {\n\t\treturn\n\t}\n\tuParams.ID = ai.Next(\"user\")\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(uParams.Hash), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn\n\t}\n\tuParams.Hash = string(hash)\n\n\ttime := time.Now().Format(\"Jan 2, 2006 at 3:04pm\")\n\tuParams.RegistrationTime = time\n\n\terr = db.UserCol.Insert(uParams)\n\tif errorAlert(\"Error: Input parameteres already used\", err, c) {\n\t\treturn\n\t}\n\n\tc.JSON(200, obj{\"ok\": \"true\"})\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\n\tuser, err := json.Marshal(map[string]string{\n\t\t\"name\": r.FormValue(\"name\"),\n\t\t\"email\": r.FormValue(\"email\"),\n\t\t\"nick\": r.FormValue(\"nick\"),\n\t\t\"password\": r.FormValue(\"password\"),\n\t})\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\turl := fmt.Sprintf(\"%s/users\", config.APIURL)\n\tresponse, err := http.Post(url, \"application/json\", bytes.NewBuffer(user))\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, response.StatusCode, nil)\n}", "func CreateUser(user model.User) {\n\tfmt.Println(user)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\treq := &models.User{}\n\tif err := DecodeRequestBody(r, req); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error while decoding the request body\" + err.Error()))\n\t\treturn\n\t}\n\tif _, err := dal.GetUsers(req.Name); err == nil {\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write([]byte(\"already existing user\"))\n\t\treturn\n\t}\n\tif err := dal.CreateUser(req); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n}", "func CreateUser(c *gin.Context) {\n\t// Validate input\n\tvar user models.User\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\thashedPassword, _ := Hash(user.Password)\n\tuser.Password = string(hashedPassword)\n\n\tmodels.DB.Create(&user)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": user})\n}", "func CreateUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\trepo := users.NewUserRepository(db)\n\tuser := &users.User{}\n\tdecoder := json.NewDecoder(r.Body)\n\n\tif err := decoder.Decode(user); err != nil {\n\t\tutils.JsonResponse(w, utils.ErrorResponse{Error: err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\trepo.AddUser(user)\n\tutils.JsonResponse(w, user, http.StatusCreated)\n}", "func CreateUser(response http.ResponseWriter, request *http.Request) {\n\n\t\n\t\trequest.ParseForm()\n\t\tdecoder := json.NewDecoder(request.Body)\n\t\tvar newUser User\n\t\t\n\t\terr := decoder.Decode(&newUser)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t\n newUser.Password=hashAndSalt([]byte(newUser.Password))\n\t\t\n\t\tinsertUser(newUser)\n\t\n}", "func (a *App) CreateUser(w http.ResponseWriter, r *http.Request) {\n\thandler.CreateUser(a.DB, w, r)\n}", "func (context Context) CreateUser(id, password, name string) (string, error) {\n\n\tif id == \"\" {\n\t\tpanic(\"id argument cannot be empty\")\n\t}\n\tif password == \"\" {\n\t\tpanic(\"password argument cannot be empty\")\n\t}\n\tif nameRegex.MatchString(name) == false {\n\t\treturn \"\", errors.New(\"invalid user name\")\n\t}\n\n\thasher := sha256.New()\n\thasher.Write([]byte(password))\n\tpasswordHash := hex.EncodeToString(hasher.Sum(nil))\n\n\tuser := types.User{\n\t\tID: id,\n\t\tName: name,\n\t\tPasswordHash: passwordHash,\n\t}\n\n\tuserBytes, err := json.Marshal(&user)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := context.sendAPIPostRequest(\"users\", bytes.NewReader(userBytes), \"application/json\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn id, nil\n}", "func CreateUser(c *gin.Context) {\n\tvar user models.User\n\tc.BindJSON(&user)\n\terr := models.CreateUser(&user)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func CreateUser(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.SignUp(data.Email, data.Password, data.RoleID)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func (h *Handler) CreateUser(c *fiber.Ctx) error {\n\tvar service = services.NewUserService()\n\tvar usr = &user.User{}\n\tif err := c.BodyParser(usr); err != nil {\n\t\treturn c.Status(422).JSON(fiber.Map{\"status\": \"error\", \"message\": err})\n\t}\n\n\tnewUser, err := service.CreateUser(usr)\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\"status\": \"error\", \"message\": err.Error()})\n\t}\n\n\treturn c.JSON(fiber.Map{\"status\": \"success\", \"message\": \"Created usr\", \"data\": newUser})\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\r\n\tdefer r.Body.Close()\r\n\tvar user model.User\r\n\r\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\r\n\t\treturn\r\n\t}\r\n\r\n\tif resp, ok := validate(&user); !ok {\r\n\t\tlog.Println(resp)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, resp)\r\n\t\treturn\r\n\t}\r\n\r\n\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\r\n\tuser.Password = string(hashedPassword)\r\n\r\n\tif err := dao.DBConn.InsertUser(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusInternalServerError, err.Error())\r\n\t\treturn\r\n\t}\r\n\r\n\tuser.Token = model.GenerateToken(user.Email)\r\n\r\n\t// Delete password before response\r\n\tuser.Password = \"\"\r\n\r\n\tu.RespondWithJSON(w, http.StatusOK, user)\r\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t// Stub an user to be populated from the body\n\tu := models.User{}\n\n\t// Populate the user data\n\tjson.NewDecoder(r.Body).Decode(&u)\n\n\t// Add an Id\n\tu.Id = bson.NewObjectId()\n\n\thPass, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tu.HashPassword = hPass\n\t// clear the incoming text password\n\tu.Password = \"\"\n\n\t// Write the user to mongo\n\terr = uc.session.DB(\"todos\").C(\"users\").Insert(&u)\n\n\t// clear hashed password\n\tu.HashPassword = nil\n\n\t// Marshal provided interface into JSON structure\n\tuj, _ := json.Marshal(u)\n\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(201)\n\tfmt.Fprintf(w, \"%s\", uj)\n}", "func UserCreate(request *http.Request) (res *model.Result) {\n\tvar form userRequest\n\tmodel.FormToJson(request.Body, &form)\n\tif uerr := validateRegister(&form); uerr != nil {\n\t\tres = model.GetErrorResult(uerr)\n\t\treturn\n\t}\n\tnew_user := UserModel{\n\t\tName: form.Name,\n\t\tEmail: form.Email,\n\t\tPassword: form.Password,\n\t}\n\tif err := new_user.create(); err != nil {\n\t\tres = model.GetErrorResult(map[string]string{\"all\": err.Error()})\n\t\treturn\n\t}\n\tcommon.SendEmailUserRegistration(form.Email)\n\tres = model.GetOk(common.Mess().Regfin)\n\treturn\n}", "func (u *UserServiceHandler) Create(ctx context.Context, email, name, password, apiEnabled string, acls []string) (*User, error) {\n\n\turi := \"/v1/user/create\"\n\n\tvalues := url.Values{\n\t\t\"email\": {email},\n\t\t\"name\": {name},\n\t\t\"password\": {password},\n\t\t\"acls[]\": acls,\n\t}\n\n\tif apiEnabled != \"\" {\n\t\tvalues.Add(\"api_enabled\", apiEnabled)\n\t}\n\n\treq, err := u.client.NewRequest(ctx, http.MethodPost, uri, values)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := new(User)\n\n\terr = u.client.DoWithContext(ctx, req, user)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.Name = name\n\tuser.Email = email\n\tuser.APIEnabled = apiEnabled\n\tuser.ACL = acls\n\n\treturn user, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user User\n\tvar b []byte\n\tr.Body.Read(b)\n\terr := json.Unmarshal(b, &user)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(err)\n\t}\n}", "func (a *Server) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"create a new user\")\n}", "func CreateUser(c *gin.Context) {\n\t//intialize\n\tvar user users.User\n\t//fetch the json request and unmarshal the json file into struct\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := errors.NewBadRequestError(\"invalid json request while creating a user\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\t//send the user struct to the services\n\tresult, err := services.UsersService.CreateUser(user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, result.Marshall(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func UserCreate(w http.ResponseWriter, r *http.Request) {\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al leer el usuario a registrarse: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tif user.Password != user.ConfirmPassword {\n\t\tm.Message = \"Las contraseña no coinciden\"\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tuser.Password = password\n\tavatarmd5 := md5.Sum([]byte(user.Password))\n\tavatarstr := fmt.Sprintf(\"%x\", avatarmd5)\n\tuser.Avatar = \"https://gravatar.com/avatar/\" + avatarstr + \"?s=100\"\n\tdatabase := configuration.GetConnection()\n\tdefer database.Close()\n\terr = database.Create(&user).Error\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al crear el registro: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tm.Message = \"Usuario creado con éxito\"\n\tm.Code = http.StatusCreated\n\tcommons.DisplayMessage(w, m)\n}", "func CreateUser(name, email, password string) {\n\n\tm := make(map[string]interface{})\n\tm[\"Github\"] = \"\"\n\tm[\"Linkedin\"] = \"\"\n\tm[\"Twitter\"] = \"\"\n\n\tv, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Println(\"Marshal error: \", err)\n\t\treturn\n\t}\n\n\tuser := &User{Name: name, Email: email, Password: password, Meta: string(v)}\n\n\tDb.Debug().Create(&user)\n}", "func CreateUser(c *gin.Context) {\n\tlog.Println(\"CreateUser in db\")\n\tvar user models.User\n\tvar db = db.GetDB()\n\tif err := c.BindJSON(&user); err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\tlog.Println(\"Failed to create user in db\")\n\t\treturn\n\t}\n\t// hash the password\n\tuser.Password = security.HashAndSalt([]byte(user.Password))\n\n\tdb.Create(&user)\n\tc.JSON(http.StatusOK, &user)\n}", "func CreateUser(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"creating user\")\n\tvar user entity.User\n\tc.BindJSON(&user)\n\n\tvar checkUser entity.User\n\tif err := model.GetUserByUsername(&checkUser, *user.Username, client); err == nil {\n\t\tlog.Error(\"the email has been registered\")\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": \"the email has been registered!\",\n\t\t})\n\t\treturn\n\t}\n\n\terr := model.CreateUser(&user, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusCreated, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n\tlog.Info(\"user created\")\n}", "func (u *UserLogic) CreateUser(obj viewmodels.UserRequest) error {\n\tpasswordHash, err := HashPassword(obj.Password)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to hash password\")\n\t}\n\n\tuser := models.User{\n\t\tName: obj.Name,\n\t\tPassword: passwordHash,\n\t\tEmail: obj.Email,\n\t\tActive: true,\n\t}\n\tif _, err := u.DB.Insert(&user); err != nil {\n\t\treturn fmt.Errorf(\"Failed to create user\")\n\t}\n\treturn nil\n}", "func CreateUser(c *gin.Context) {\n\tvar user models.User\n\tc.BindJSON(&user)\n\terr := repository.CreateUser(&user)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func (h *userHandler) createUser(ctx context.Context, rw http.ResponseWriter, r *http.Request) {\n\n\tvar user = &model.User{}\n\n\terr := json.NewDecoder(r.Body).Decode(user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\n\t}\n\n\tif user.Login == \"\" || user.Password == \"\" {\n\n\t\th.serv.writeResponse(ctx, rw, \"Login or password are empty\", http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\terr = h.registerUser(ctx, user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\th.serv.writeResponse(ctx, rw, \"user was created: \"+user.Login, http.StatusCreated, user)\n\n}", "func CreateUser(db *gorm.DB) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\t// Get the mandatory query parameters.\n\t\tname, ok := c.GetPostForm(\"name\")\n\t\tif !ok {\n\t\t\terrors.Apply(c, errors.MissingParameters)\n\t\t\treturn\n\t\t}\n\t\tusername, ok := c.GetPostForm(\"username\")\n\t\tif !ok {\n\t\t\terrors.Apply(c, errors.MissingParameters)\n\t\t\treturn\n\t\t}\n\t\tif !usernameRegexp.MatchString(username) {\n\t\t\terrors.Apply(c, errors.BadParameters)\n\t\t\treturn\n\t\t}\n\t\tpassword, ok := c.GetPostForm(\"password\")\n\t\tif !ok {\n\t\t\terrors.Apply(c, errors.MissingParameters)\n\t\t\treturn\n\t\t}\n\n\t\t// Try getting type.\n\t\tuserType, ok := c.GetPostForm(\"type\")\n\t\tif !ok {\n\t\t\tuserType = models.General\n\t\t}\n\t\tif userType != models.Admin && userType != models.Writer && userType != models.General {\n\t\t\terrors.Apply(c, errors.BadParameters)\n\t\t\treturn\n\t\t}\n\t\tif _, ok := c.Get(\"user\"); userType != models.General && !ok {\n\t\t\terrors.Apply(c, errors.NoPermission)\n\t\t\treturn\n\t\t}\n\n\t\t// Check if any users have the same username.\n\t\tvar checkUsers []models.User\n\t\terr := db.Where(\"user_name = ?\", username).\n\t\t\tFind(&checkUsers).\n\t\t\tError\n\t\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\t\terrors.Apply(c, err)\n\t\t\treturn\n\t\t}\n\t\tif len(checkUsers) != 0 {\n\t\t\terrors.Apply(c, errors.UserExists)\n\t\t\treturn\n\t\t}\n\n\t\t// Create the user.\n\t\tuser := &models.User{\n\t\t\tType: userType,\n\t\t\tName: name,\n\t\t\tUserName: username,\n\t\t}\n\t\tif err := user.SetPassword(password); err != nil {\n\t\t\terrors.Apply(c, err)\n\t\t\treturn\n\t\t}\n\t\tif err := db.Create(user).Error; err != nil {\n\t\t\terrors.Apply(c, err)\n\t\t\treturn\n\t\t}\n\n\t\t// Respond with the user's JSON.\n\t\tc.JSON(200, user)\n\t}\n}", "func Create(c *gin.Context) {\n\tvar user models.User\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := rest_errors.NewBadRequestError(\"invalid json body\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\n\tresult, saveErr := services.UsersService.CreateUser(user)\n\tif saveErr != nil {\n\t\tc.JSON(saveErr.Status, saveErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, result.Marshal(c.GetHeader(\"X-Public\") == \"false\"))\n}", "func (handler *UserHandler) Create(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tpayload := &User{}\n\n\tif err := json.NewDecoder(req.Body).Decode(payload); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1001\",\n\t\t\t\"Invalid JSON payload supplied.\", err.Error()))\n\t\treturn\n\t}\n\n\tif err := payload.Validate(); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1002\",\n\t\t\t\"Unable to validate the payload provided.\", err.Error()))\n\t\treturn\n\t}\n\n\tuser, err := handler.UserService.CreateUser(payload)\n\n\tif err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1003\",\n\t\t\t\"Unable to create a new user.\", err.Error()))\n\t\treturn\n\t}\n\n\thandler.Formatter.JSON(w, http.StatusCreated, user.hidePassword())\n}", "func (_this *UserHandler) CreateUser() echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tvar request dtos.CreateUserRequest\n\t\tif err := c.Bind(&request); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresp, err := _this.userService.CreateUser(&request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.JSON(http.StatusOK, resp)\n\t}\n}", "func CreateUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tuser := models.AppUser{}\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(&user); err != nil {\n\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{models.AppUser{}, \"Erro interno del servidor\"})\n\t\treturn\n\t}\n\tuserTemp := getUserOrNull(db, user.AppUserID, w, r)\n\tif userTemp != nil {\n\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{models.AppUser{}, \"Ya existe un usuario con este ID\"})\n\t\treturn\n\t}\n\t//hashing the password\n\tpass := user.AppUserPassword\n\thashPass, err := bcrypt.GenerateFromPassword([]byte(pass), 10)\n\tif err != nil {\n\t\trespondJSON(w, http.StatusInternalServerError, JSONResponse{models.AppUser{}, \"Error Interno del servidor\"})\n\t\treturn\n\t}\n\ts := bytes.NewBuffer(hashPass).String()\n\tuser.AppUserPassword = s\n\t//end hashing\n\n\tif result := db.Create(&user); result.Error != nil || result.RowsAffected == 0 {\n\t\tif result.Error != nil {\n\t\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{models.AppUser{}, err.Error()})\n\t\t\treturn\n\t\t}\n\t\trespondJSON(w, http.StatusInternalServerError, JSONResponse{models.AppUser{}, \"Error No se pudo realizar el registro\"})\n\t\treturn\n\t}\n\trespondJSON(w, http.StatusCreated, JSONResponse{user, \"Registro realizado\"})\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tif err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusOK))\n}", "func CreateUser(af AuthForm) (user *User, err error) {\n\tuser = new(User)\n\tuser.HashedPassword, err = bcrypt.GenerateFromPassword([]byte(af.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn\n\t}\n\tuser.Username = af.Login\n\n\terr = SaveUser(user)\n\tif err != nil {\n\t\tif IsErrUnniqueConstraintFailed(err) {\n\t\t\terr = fmt.Errorf(\"Пользователь с таким именем уже существует\")\n\t\t}\n\t\treturn\n\t}\n\n\t_, err = CreateGroup(\"Главная\", user.ID)\n\n\treturn user, err\n}", "func CreateUser(c *gin.Context) {\n\tvar user Models.User\n\tc.BindJSON(&user)\n\n\tauth := c.Request.Header.Get(\"Authorization\")\n if auth != Utils.GetAuthToken() {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusUnauthorized,\n\t\t\t\"message\": \"Invalid Token\",\n\t\t}})\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar now = time.Now().Unix()\n\tnur := Models.User(user)\n\t err_password := validator.Validate(nur)\n\t if err_password != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err_password.Error(),\n\t\t}})\n\t\tfmt.Println(err_password.Error())\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\n\t//user.Password = Utils.EncodeBase64(user.Password)\n\tuser.Date_created = Utils.ConvertTimestampToDate(int64(now))\n\terr := Models.CreateUser(&user)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tfmt.Println(err.Error())\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t\tfmt.Println(\"usuario_creado\", user.Id)\n\t}\n}", "func (c Client) CreateUser(ctx context.Context, user api.User, password string) (api.Identifier, error) {\n\tuser.ID = xid.New().Bytes()\n\tif _, err := c.db.ExecContext(ctx, \"insert into users (id, email, password, first_name, last_name) values ($1, $2, $3, $4)\", user.ID, user.Email, password, user.FirstName, user.LastName); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user.ID, nil\n}", "func CreateUser(c *gin.Context) {\n\tvar json db.UserSignupForm\n\tif err := c.ShouldBind(&json); err != nil {\n\t\t// Form validation errors\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"Form doesn't bind.\",\n\t\t\t\"err\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\thash, _ := hashPassword(json.Password)\n\tuser := db.Users{\n\t\tUsername: json.Username,\n\t\tPassword: hash,\n\t\tEmail: json.Email,\n\t\tGender: json.Gender,\n\t}\n\tif err := db.DB.Create(&user).Error; err != nil {\n\t\t// User already exists\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"User already exists.\",\n\t\t\t\"err\": err,\n\t\t})\n\t} else {\n\t\t// Create new user\n\t\tc.JSON(http.StatusCreated, gin.H{\n\t\t\t\"msg\": user.Username,\n\t\t\t\"err\": \"\",\n\t\t})\n\t}\n}", "func CreateUser(name, phone, email, password string) {\n\tDb.Create(&User{Name: name, Phone: phone, Email: email, Password: password})\n}", "func CreateUser(c *gin.Context) {}", "func (c *Client) CreateUser(data, fingerprint, ipAddress string, idempotencyKey ...string) (*User, error) {\n\tlog.info(\"========== CREATE USER ==========\")\n\tvar user User\n\tuser.request = Request{\n\t\tclientID: c.ClientID,\n\t\tclientSecret: c.ClientSecret,\n\t\tfingerprint: fingerprint,\n\t\tipAddress: ipAddress,\n\t}\n\n\turl := buildURL(path[\"users\"])\n\tres, err := user.do(\"POST\", url, data, idempotencyKey)\n\tmapstructure.Decode(res, &user)\n\tuser.Response = res\n\n\treturn &user, err\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\tjson.NewDecoder(req.Body).Decode(&u)\n\n\tu.ID = \"007\"\n\n\tuj, err := json.Marshal(u)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tw.Header().Set(\"Contenty-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // STATYS 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func CreateUser(c *gin.Context) {\n\tvar user models.User\n\tvar db = db.GetDB()\n\n\t// Check admin right creation\n\t// Retrive user information\n\tjwtClaims := jwt.ExtractClaims(c)\n\tauthUserAccessLevel := jwtClaims[\"access_level\"].(float64)\n\n\tif authUserAccessLevel != 1 {\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"error\": \"Sorry 🤔 but only admins can create user\",\n\t\t})\n\t\treturn\n\t}\n\n\tif err := c.BindJSON(&user); err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t// Create user if no errors thrown by Validate method in user model\n\tif err := db.Create(&user); err.Error != nil {\n\n\t\t// convert array of errors to JSON\n\t\terrs := err.GetErrors()\n\t\tstrErrors := make([]string, len(errs))\n\t\tfor i, err := range errs {\n\t\t\tstrErrors[i] = err.Error()\n\t\t}\n\n\t\t// return errors\n\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{\n\t\t\t\"errors\": strErrors,\n\t\t})\n\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, &user)\n}", "func (uc UserController) CreateUser(c rest.Context) rest.ResponseSender {\n\tvar user User\n\n\tc.BindJSONEntity(&user)\n\n\tusers = append(users, user)\n\n\tuc.db.execute(fmt.Sprintf(\"INSERT INTO User (`firstName`, `lastName`) VALUES ('%v', '%v')\", user.FirstName, user.LastName))\n\n\treturn rest.NewCreatedJSONResponse(user)\n}", "func (h Handler) CreateUser(w http.ResponseWriter, r *http.Request) {\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(r.Body)\n\tdefer r.Body.Close()\n\n\tvar usersRequestDTO model.UserRequestDTO\n\n\t//Unmarshall body\n\n\tvar err error\n\tif err = json.Unmarshal(buf.Bytes(), &usersRequestDTO); err != nil {\n\t\thttp.Error(w, \"Invalid body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t//Validate dto\n\n\tif !users.ValidateUsersRequestDTO(usersRequestDTO) {\n\t\thttp.Error(w, \"Invalid body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t//Check If user exists\n\n\tvar found bool\n\tif _, found, err = h.Db.GetUser(usersRequestDTO.Username); found && err == nil {\n\t\thttp.Error(w, \"Username already exists\", http.StatusConflict)\n\t\treturn\n\t}\n\n\tif !found && err != nil {\n\t\thttp.Error(w, \"Error generating user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t//Create User\n\n\tvar user model.User\n\tif user, err = users.CreateUser(usersRequestDTO.Username, usersRequestDTO.Password); err != nil {\n\t\thttp.Error(w, \"Error generating user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t//Post user\n\n\tuser, err = h.Db.InsertUser(user)\n\tif err != nil {\n\t\thttp.Error(w, \"Error generating user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := json.NewEncoder(w).Encode(model.UserResponseDTO{user.Userid}); err != nil {\n\t\thttp.Error(w, \"Write error\", http.StatusInternalServerError)\n\t}\n}", "func CreateUser(db *mongo.Client, w http.ResponseWriter, r *http.Request) {\n\tuser, err := parseUser(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tuser.Password = encryptPassword([]byte(user.Password))\n\t_, err = db.Database(\"charon\").Collection(\"users\").InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tio.WriteString(w, \"User successfully added.\")\n}", "func CreateUser(w http.ResponseWriter, r *http.Request,\n\tu *model.User) *AppError {\n\n\tdefer r.Body.Close()\n\n\tif u != nil {\n\t\treturn &AppError{ErrAlreadyAuthorized, \"already logged in\",\n\t\t\thttp.StatusBadRequest}\n\t}\n\n\tuser, err := model.NewUser(r.Body)\n\tif err != nil {\n\t\treturn &AppError{err, err.Error(), http.StatusBadRequest}\n\t}\n\n\terr = database.SaveUser(user)\n\tif err != nil {\n\t\treturn &AppError{err, \"error saving user\", http.StatusInternalServerError}\n\t}\n\n\treturn renderJSON(w, user, http.StatusOK)\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqId(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t\treturn\n\t}\n\n\tu := model.UserModel{\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\n\t// Validate the data.\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t\treturn\n\t}\n\n\t// Encrypt the user password.\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t\treturn\n\t}\n\n\t// Insert the user to the database.\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatebase, nil)\n\t\treturn\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\n\t// Show the user information.\n\tSendResponse(c, nil, rsp)\n}", "func (c *MysqlUserController) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tuser := &openapi.User{}\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\n\tapiKey := r.Header.Get(\"apiKey\")\n\tresult, err := c.service.CreateUser(*user, apiKey)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tstatusCode := http.StatusCreated\n\topenapi.EncodeJSONResponse(result, &statusCode, w)\n}", "func CreateUser(w http.ResponseWriter, req *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(req.Body, 1048576))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := req.Body.Close(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar user User\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tw.WriteHeader(422)\n\t\tlog.Println(err.Error())\n\t}\n\n\tInsertUser(user)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n\tif err := json.NewEncoder(w).Encode(user); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (server Server) CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User // make a user\n\tvar res models.APIResponse // make a response\n\n\terr := json.NewDecoder(r.Body).Decode(&user) //decode the user\n\tif err != nil {\n\t\tlog.Printf(\"Unable to decode the request body. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to decode the request body\", nil)\n\t}\n\tif user.Name == \"\" || user.Email == \"\" || user.Password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Blank users cannot be created\", nil)\n\t} else {\n\t\tinsertID := insertUser(user, server.db) // call insert user function and pass the note\n\t\tres = models.BuildAPIResponseSuccess(fmt.Sprintf(\"User Created with %d id\", insertID), nil) // format a response object\n\t}\n\tjson.NewEncoder(w).Encode(res)\n\n}", "func (cli *OpsGenieUserV2Client) Create(req userv2.CreateUserRequest) (*userv2.CreateUserResponse, error) {\n\tvar response userv2.CreateUserResponse\n\terr := cli.sendPostRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tuid, err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest)\n\tif err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusCreated, gin.H{\n\t\t\"id\": uid,\n\t}))\n}", "func (ok AssumeSuccess) CreateUser(\n\tdisplayName,\n\temail,\n\tpassword string,\n) *gqlmod.User {\n\treturn ok.h.createUser(\"\", displayName, email, password)\n}", "func (a *App) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tresponse, err := a.Storage.CreateUser(user.Username, user.Password)\n\tif err != nil {\n\t\thttp.Error(w, \"username already in use\", http.StatusBadRequest)\n\t\treturn\n\t}\n\taddJSONPayload(w, http.StatusOK, response)\n}", "func Create(user User) error {\n\t\n}", "func (s *server) CreateUser(ctx context.Context, in *pb.UserRequest) (*pb.UserResponse, error) {\n\n\tlog.Printf(\"Received: %v\", \"create user\")\n\tif len(in.HashPassword) <= 6 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Invalid password\")\n\t}\n\thash, salt := hash(in.HashPassword)\n\n\temail, id, err := addUser(in.Email, hash, salt)\n\n\tid = id\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, \"database problem\")\n\t}\n\ttoken := GenerateSecureToken(32)\n\tis, err := CreateSession(in.Email, token)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, \"db problem\")\n\t}\n\n\t// add to profiles db\n\tCreateUser(email, token, \"Plese input your name\", \"Your description\")\n\t/*if res == false{\n\t\tlog.Printf(\"can create: %v\", err)\n\t\treturn nil,status.Error(codes.Internal,\"cant create\")\n\t}\n\t*/\n\n\treturn &pb.UserResponse{IsUser: is, Token: token}, nil\n}", "func (u UserControllerHandler) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tutil.Respond(w, util.Message(false, \"Error while decoding request body\"))\n\t\t//return\n\t}\n\tresponse := u.userService.CreateUser(user)\n\tutil.Respond(w, response)\n}", "func (user *User) CreateUser(ctx context.Context, privateKey *rsa.PrivateKey, fullname string) (*User, error) {\n\tpbts, err := x509.MarshalPKIXPublicKey(privateKey.Public())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparas := map[string]interface{}{\n\t\t\"session_secret\": base64.StdEncoding.EncodeToString(pbts),\n\t\t\"full_name\": fullname,\n\t}\n\n\tvar u User\n\tif err := user.Request(ctx, \"POST\", \"/users\", paras, &u); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.privateKey = privateKey\n\treturn &u, nil\n}", "func (h *User) CreateUser(c echo.Context) error {\n\tname := c.FormValue(\"name\")\n\taddress := c.FormValue(\"address\")\n\tctx := c.Request().Context()\n\n\tuser, err := h.Usecase.CreateUser(ctx, name, address)\n\tif err != nil {\n\t\tresult := response.UserBody{\n\t\t\tMessage: \"FAILED\",\n\t\t\tData: nil,\n\t\t\tError: &response.Error{\n\t\t\t\tMessage: err.Error(),\n\t\t\t},\n\t\t}\n\t\treturn c.JSON(helpers.GetStatusCode(err), result)\n\t}\n\n\tresult := response.UserBody{\n\t\tMessage: \"SUCCESS\",\n\t\tData: h.transformUser(&user),\n\t\tError: nil,\n\t}\n\n\treturn c.JSON(http.StatusOK, result)\n}", "func (s *Store) CreateUser(creds UserCredentials, details UserDetails) error {\r\n\terr := s.saveUserCredentials(creds)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\terr = s.saveUserDetails(details)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (s *service) createUser(ctx context.Context, newUser *auth.User) error {\n\treturn s.repoMngr.User().Create(ctx, newUser)\n}", "func CreateUser(context *fiber.Ctx) error {\n\tnew_user := new(models.User)\n\tif err := context.BodyParser(new_user); err != nil {\n\t\treturn context.Status(503).SendString(err.Error())\n\t}\n\n\thash, err := hashPassword(new_user.Pswd)\n\tif err != nil {\n\t\tmy_error := new(my_error)\n\t\tmy_error.My_error = \"failed to make a hash for password\"\n\t\tmy_error.Error = err.Error()\n\t\treturn context.JSON(my_error)\n\t}\n\tnew_user.Pswd = hash\n\n\tcreation := queries.CreateUser(new_user)\n\tif creation != \"OK\" {\n\t\treturn context.Status(503).SendString(creation)\n\t}\n\treturn context.JSON(new_user)\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\n\tjson.NewDecoder(r.Body).Decode(&u)\n\n\t// create bson ID\n\t// u.ID = bson.NewObjectId().String()\n\n\t// store the user in mongodb\n\tusers[u.ID] = u\n\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request){\n\n\t\tu := User{}\n\n\t\terr:= json.NewDecoder(r.Body).Decode(&u)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Checks if name is Empty\n\t\tfmt.Printf(\"name: [%+v]\\n\", u.Name)\n\t\tif u.Name == \"\" {\n\t\t\tfmt.Println(\"Empty string\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\n\t\t//start validation for username\n\t\tvar isStringAlphabetic = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`).MatchString\n\t\tif !isStringAlphabetic(u.Name){\n\t\t\tfmt.Println(\"is not alphanumeric\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//make the Name Uppercase\n\t\tu.Name = strings.ToUpper(u.Name)\n\n\t\t// check if username already exists\n\t\tuser := userExist(u.Name)\n\t\tif user != (User{}) {\n\t\t\tfmt.Println(\"Name already exists\")\n\t\t\tw.Write([]byte(`{\"status\":\"Name Exists\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//if it does exist create the user with a random ID and score = 0\n\t\tuuid, err := uuid.NewV4()\n\t\tu.ID = uuid.String()\n\t\tu.Score = 0\n\n\t\tquery := \"INSERT INTO users (id, name, score) VALUES ($1, $2, $3);\"\n\t\t_, err = db.Exec(query, u.ID, u.Name, u.Score);\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(201)\n\t\tjson.NewEncoder(w).Encode(u)\n\n}", "func CreateUser(user *models.User) error {\n\twhitelist := []string{\n\t\t\"email\",\n\t\t\"email_hash\",\n\t\t\"token_version\",\n\t}\n\n\thash := md5.Sum([]byte(user.Email))\n\tuser.EmailHash = hex.EncodeToString(hash[:])\n\n\tif user.Role != \"\" {\n\t\twhitelist = append(whitelist, \"role\")\n\t}\n\n\tif user.Username.Ptr() != nil {\n\t\twhitelist = append(whitelist, \"username\")\n\t}\n\n\tif user.DisplayName.Ptr() != nil {\n\t\twhitelist = append(whitelist, \"display_name\")\n\t}\n\n\tif user.Picture.Ptr() != nil {\n\t\twhitelist = append(whitelist, \"picture\")\n\t}\n\n\tif user.Password.Ptr() != nil {\n\t\twhitelist = append(whitelist, \"password\")\n\n\t\tif err := HashUserPassword(user); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tuser.TokenVersion = null.Int64From(time.Now().Unix())\n\t}\n\n\treturn user.InsertG(boil.Whitelist(whitelist...))\n}", "func (u *UserHandler) Create(c *fiber.Ctx) error {\n\tuser := models.User{}\n\terr := c.BodyParser(&user)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.Repo.Create(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Status(fiber.StatusOK).JSON(user)\n}", "func (s *service) CreateUser(ctx context.Context, user model.User) error {\n\tif p, err := util.HashPassword(user.Password); err == nil {\n\t\tuser.Password = p\n\t}\n\treturn s.repo.InsertUser(ctx, user)\n}", "func CreateUser(user users.User) (*users.User, *errors.RestErr) {\n\tif err := user.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.Status = users.StatusActive\n\tuser.DateCreated = date.GetNowDBFormat()\n\tuser.DateUpdated = user.DateCreated\n\tuser.Password = crypto.GetMd5(user.Password)\n\n\tif err := user.Save(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &user, nil\n}", "func(s *Server) CreateUser(user *User) (*User, error) {\n\t \n\t emailErr := s.ValidateEmail(user.Email)\n\t if emailErr != nil {\n\t\t return nil, emailErr\n\t }\n \n\t err := s.DB.Debug().Create(&user).Error\n\t if err != nil {\n\t\t return nil, err\n\t }\n \n\t return user, nil\n }", "func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"/users POST handled\")\n\n\treq := &CreateRequest{}\n\tif err := util.ScanRequest(r, req); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuser := &schema.User{\n\t\tName: req.Name,\n\t}\n\n\tif err := h.model.Validate(user); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tres, err := h.model.Create(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := util.JSONWrite(w, res, http.StatusCreated); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\t// create an empty user of type models.User\n\tvar user models.User\n\n\t// decode the json request to user\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to decode the request body. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !user.Valid() {\n\t\thttp.Error(w, \"Invalid User\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// set the header to content type x-www-form-urlencoded\n\t// Allow all origin to handle cors issue\n\tw.Header().Set(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\t//set the hash\n\thashedPass, err := user.HashPassword()\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create hash of the given password. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// call insert user function and pass the user\n\terr = database.InsertUser(user.Email, hashedPass, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to insert user. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttkn, err := models.CreateToken(user.Email)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create token. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// format a response object\n\tres := models.TokenResponse{\n\t\tToken: tkn,\n\t}\n\t// send the response\n\terr = json.NewEncoder(w).Encode(res)\n\tif err != nil {\n\t\tlogrus.Errorf(err.Error())\n\t\treturn\n\t}\n}", "func createUser(c echo.Context) error {\n\tvar errResp ErrorResponseData\n\tvar resp UserResponseData\n\n\treq := new(userRequest)\n\tif err := c.Bind(req); err != nil {\n\t\terrResp.Data.Code = \"request_binding_error\"\n\t\terrResp.Data.Description = \"Unable to bind request\"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusBadRequest)\n\t\treturn c.JSON(http.StatusBadRequest, errResp)\n\t}\n\n\tuser := req.mapToModel()\n\terr := storage.CreateUser(&user)\n\n\tif err != nil {\n\t\terrResp.Data.Code = \"create_account_error\"\n\t\terrResp.Data.Description = \"Unable to create account\"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusInternalServerError)\n\t\treturn c.JSON(http.StatusInternalServerError, errResp)\n\t}\n\n\tresp.mapFromModel(user)\n\treturn c.JSON(http.StatusCreated, resp)\n}", "func createUser(u *models.User, db *sql.DB) error {\n\tif err := u.CryptPwd(); err != nil {\n\t\treturn fmt.Errorf(\"Cryptage du mot de passe de %s : %v\", u.Name, err)\n\t}\n\tif err := u.Create(db); err != nil {\n\t\treturn fmt.Errorf(\"Création en base de données de %s : %v\", u.Name, err)\n\t}\n\treturn nil\n}", "func (us *usersService) CreateUser(u *users.User) *errors.RestError {\n\tvar err *errors.RestError\n\tif err = u.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = u.EncryptPassword(); err != nil {\n\t\treturn err\n\t}\n\tif err = u.Save(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *initServer) CreateUser(ctx context.Context, in *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {\t\n\tresp := createUserResp(ctx)\n\n\tc := newConn(\"createUser:user\")\n\tu := pbUser.NewUserServiceClient(c)\n\tdefer c.Close()\n\n\tcode, err := handleAuthCheck(ctx, u); \n\tif err != nil {\n\t\treturn resp(err.Error(), code)\n\t}\n\n\tres, err := u.UserCreate(ctx, &pbUser.UserCreateRequest{\n\t\tLogin: in.GetLogin(),\n\t\tName: in.GetName(),\n\t\tEmail: in.GetEmail(),\n\t\tPassword: in.GetPassword(),\n\t})\n\n\tif err != nil {\n\t\treturn resp(err.Error(), res.Code)\n\t}\n\n\treturn resp(res.GetMessage(), res.Code)\n}", "func (s *AuthService) CreateUser(user auth.User)(int, error){\n\tuser.Password = genereatePasswordHash(user.Password)\n\treturn s.repo.CreateUser(user)\n}", "func (dbHandler *Handler) CreateUser(name string, password string) (api.User, error) {\n\tuser := api.User{Name: name, Password: hashPassword(password)}\n\n\tdb := dbHandler.DB.Create(&user)\n\tif db.Error != nil {\n\t\treturn user, errors.WrapWithDetails(db.Error, \"cannot create user\", \"name\", name)\n\t}\n\n\treturn user, nil\n}", "func CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"CreateNewUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Creating new user\")\n\treq := &CreateNewUserRequest{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, req)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tisValidPassphrase := passphrase.Validate(req.Passphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\tuser, err := UserRepo.CreateUserRecord(r.Context(), req.Email, req.Passphrase)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.CreateUserRecord got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := &CreateNewUserResponse{\n\t\tRecordID: user.RecID,\n\t\tEmail: user.Email,\n\t\tEnabled: user.Enabled,\n\t\tSuspended: user.Suspended,\n\t\tLastSeen: user.LastSeen,\n\t\tLastLogin: user.LastLogin,\n\t\tTotpEnabled: user.Enable2FactorAuth,\n\t}\n\tfLog.Warnf(\"Sending email\")\n\tmailer.Send(r.Context(), &mailer.Email{\n\t\tFrom: config.Get(\"mailer.from\"),\n\t\tFromName: config.Get(\"mailer.from.name\"),\n\t\tTo: []string{user.Email},\n\t\tCc: nil,\n\t\tBcc: nil,\n\t\tTemplate: \"EMAIL_VERIFY\",\n\t\tData: user,\n\t})\n\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"Success creating user\", nil, resp)\n\treturn\n}", "func CreateNewUser(user model.User, password string) error {\n\n\t//Maybe we want to do this asynchronous\n\thash, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser.HashedPassword = hash\n\n\taccess := data.CreateDataAccess()\n\terr = access.CreateUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Created\n\treturn nil\n\n}", "func CreateUser(c *gin.Context) {\n\tdb := dbConn()\n\tvar user User\n\tif err := c.BindJSON(&user); err == nil {\n\t\tstatement, _ := db.Prepare(\"CALL create_user (?, ?, ?, ?, ?, ?, ?, ?, ?)\")\n\t\tstatement.Exec(user.UserName, user.UserEmail, user.FName, user.LName, user.Password, user.PasswordChange, user.PasswordExpired, user.LastLogon, user.AccountLocked)\n\t\tif err != nil {\n\t\t\tc.String(http.StatusInternalServerError, err.Error())\n\t\t}\n\t} else {\n\t\tc.String(http.StatusInternalServerError, err.Error())\n\t}\n\tdefer db.Close()\n}", "func createUser(name, password, passwordUpdateRequest string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"User\",\n \"name\": \"%s\",\n \"credential\": {\n \"type\": \"PasswordCredential\",\n\t\t\"password\": \"%s\",\n\t\t\"passwordUpdateRequest\": \"%s\"\n }\n}`, name, password, passwordUpdateRequest)\n}", "func (c *Client) CreateUser(email string, password string) (*AuthUser, error) {\n\trequest := fmt.Sprintf(userCreateRequest, email, password)\n\n\tresponse, err := c.QueryHouston(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"CreateUser Failed\")\n\t}\n\treturn response.Data.CreateUser, nil\n}", "func UserCreate(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 url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := auth.GetUserFromJSON(body)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"User\")\n\t\trespondErr(w, err)\n\t\tlog.Error(string(body[:]))\n\t\treturn\n\t}\n\n\tuuid := uuid.NewV4().String() // generate a new uuid to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\t// Get Result Object\n\tres, err := auth.CreateUser(uuid, urlUser, postBody.FirstName, postBody.LastName, postBody.Organization, postBody.Description,\n\t\tpostBody.Projects, token, postBody.Email, postBody.ServiceRoles, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"duplicate\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"invalid\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\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 (s *UsersService) Create(userIn NewUser, createAsActive bool) (*User, *Response, error) {\n\n\tu := fmt.Sprintf(\"users?activate=%v\", createAsActive)\n\n\treq, err := s.client.NewRequest(\"POST\", u, userIn)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnewUser := new(User)\n\tresp, err := s.client.Do(req, newUser)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn newUser, resp, err\n}", "func (h *Handler) createUser(c *gin.Context) handlerResponse {\n\n\tvar newUser types.User\n\tif err := c.ShouldBindJSON(&newUser); err != nil {\n\t\treturn handleBadRequest(err)\n\t}\n\tstoredUser, err := h.service.User.Create(newUser, h.who(c))\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\t// Remove password so we do not show in response\n\tstoredUser.Password = \"\"\n\treturn handleCreated(storedUser)\n}", "func Create(c *gin.Context) {\n\tvar user users.User\n\n\t// ShouldBindJSON - read request body and unmarshals the []bytes to user\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tbdErr := errors.NewBadRequestError(fmt.Sprintf(\"invalid json body: %s\", err.Error()))\n\t\tc.JSON(bdErr.Status, bdErr)\n\t\treturn\n\t}\n\n\tresult, err := services.UserServ.CreateUser(user)\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.StatusCreated, result.Marshall(isPublic))\n}", "func (u *userServer) Create(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {\n\tc, err := u.connect(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer c.Close()\n\n\tresult, err := c.ExecContext(ctx, \"INSERT INTO User(`FirstName`, `LastName`, `Address`) VALUES (?, ?, ?)\", req.User.FirstName, req.User.LastName, req.User.Address)\n\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to insert into User table\"+err.Error())\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to retrieve last inserted record for User\"+err.Error())\n\t}\n\n\treturn &pb.CreateUserResponse{\n\t\tId: id,\n\t}, nil\n}", "func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}", "func (u *User) Create(c echo.Context, req *schemago.ReqCreateUser) (*schemago.SUser, error) {\n\t// if err := u.rbac.AccountCreate(c, req.RoleID, req.CompanyID, req.LocationID); err != nil {\n\t// \treturn nil, err\n\t// }\n\treq.Password = u.sec.Hash(req.Password)\n\treturn u.udb.Create(u.db, u.ce, req)\n}", "func (u *usecase) Create(ctx context.Context, user *User) error {\n\tvalidate = validator.New()\n\tif err := validate.Struct(user); err != nil {\n\t\tvalidationErrors := err.(validator.ValidationErrors)\n\t\treturn validationErrors\n\t}\n\n\tuser.ID = u.newID()\n\tif err := u.repository.Create(ctx, user); err != nil {\n\t\treturn errors.Wrap(err, \"error creating new user\")\n\t}\n\n\treturn nil\n}", "func (uh UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(utils.InfoLog + \"UserHandler:CreateUser called\")\n\tvar newUser models.User\n\n\treqBody, genErr := ioutil.ReadAll(r.Body); if genErr != nil {\n\t\tutils.ReturnWithError(w, http.StatusBadRequest, http.StatusText(http.StatusBadRequest), genErr.Error())\n\t\tlog.Println(utils.ErrorLog + \"Unable to read request body\")\n\t\treturn\n\t}\n\n\tjson.Unmarshal(reqBody, &newUser)\n\t_, genErr = valid.ValidateStruct(&newUser) ; if genErr != nil {\n\t\tutils.ReturnWithError(w, http.StatusBadRequest, http.StatusText(http.StatusBadRequest), genErr.Error())\n\t\tlog.Println(utils.ErrorLog + \"Request body data invalid\")\n\t\treturn\n\t}\n\terr := models.ValidateUser(&newUser); if err != nil {\n\t\tutils.ReturnWithErrorLong(w, *err)\n\t\tlog.Println(utils.ErrorLog + \"Request body data invalid\") // TODO ??\n\t\treturn\n\t}\n\n\terr = uh.UserManager.CreateUser(&newUser); if err != nil {\n\t\tutils.ReturnWithErrorLong(w, *err)\n\t\tlog.Println(utils.ErrorLog + \"Insert body here\") // TODO ??\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(newUser)\n}", "func (c *Client) CreateUser(user *User) (createdUser *User, err error) {\n\n\t// Basic requirements\n\tif len(user.Email) == 0 {\n\t\terr = c.createError(fmt.Sprintf(\"missing required attribute: %s\", fieldEmail), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Permit fields before creating\n\tuser.permitFields()\n\n\t// Fire the Request\n\tvar response string\n\tif response, err = c.Request(modelUser, http.MethodPost, user); err != nil {\n\t\treturn\n\t}\n\n\t// Only a 201 is treated as a success\n\tif err = c.Error(http.StatusCreated, response); err != nil {\n\t\treturn\n\t}\n\n\t// Convert model response\n\tif err = json.Unmarshal([]byte(response), &createdUser); err != nil {\n\t\terr = c.createError(fmt.Sprintf(\"failed unmarshaling data: %s\", \"user\"), http.StatusExpectationFailed)\n\t}\n\treturn\n}", "func (c *Client) CreateUser(userRequest UserRequest) (User, error) {\n\tvar (\n\t\turi = \"/rest/users\"\n\t\tuser User\n\t)\n\n\tresponse, err := c.RestAPICall(rest.POST, uri, nil, userRequest)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif err := json.Unmarshal([]byte(response), &user); err != nil {\n\t\treturn user, apiResponseError(response, err)\n\t}\n\n\treturn user, err\n}", "func (a *AdminAPI) CreateUser(ctx context.Context, username, password, mechanism string) error {\n\tif username == \"\" {\n\t\treturn errors.New(\"invalid empty username\")\n\t}\n\tif password == \"\" {\n\t\treturn errors.New(\"invalid empty password\")\n\t}\n\tu := newUser{\n\t\tUser: username,\n\t\tPassword: password,\n\t\tAlgorithm: mechanism,\n\t}\n\treturn a.sendToLeader(ctx, http.MethodPost, usersEndpoint, u, nil)\n}", "func CreateUser(name, address, description string) *User {\n\treturn & User {\n\t\tName: name,\n\t\tAddress: address,\n\t\tDescription: description,\n\t}\n}", "func (c *Client) CreateUser(name string) (*User, error) {\n\n\tcreateUser := &CreateUserRequest{\n\t\tName: name,\n\t}\n\n\tvar u User\n\t_, err := c.sling.Post(\"users\").BodyJSON(createUser).ReceiveSuccess(&u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &u, nil\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqID(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t}\n\n\tu := model.UserModel{\n\t\t//BaseModel: model.BaseModel{},\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\t//fmt.Println()\n\t//log.Info(r.Username)\n\t//log.Info(r.Password)\n\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t}\n\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t}\n\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatabase, nil)\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\tSendResponse(c, nil, rsp)\n}" ]
[ "0.8186667", "0.8070818", "0.80625784", "0.8019643", "0.79885554", "0.7908014", "0.7880015", "0.7873839", "0.7863846", "0.7861369", "0.7836062", "0.7825336", "0.78246564", "0.782047", "0.7802029", "0.7778561", "0.7754207", "0.7750743", "0.77495056", "0.7747591", "0.77408284", "0.7733054", "0.7717997", "0.77169734", "0.77134997", "0.7696339", "0.76947594", "0.769046", "0.7680034", "0.7664721", "0.7664572", "0.76563096", "0.76542616", "0.7647166", "0.76091456", "0.7599485", "0.7593766", "0.7592906", "0.7592135", "0.7583991", "0.75834376", "0.7582491", "0.75786245", "0.75769496", "0.757316", "0.7570658", "0.756817", "0.7566929", "0.75492835", "0.75477886", "0.7542641", "0.7540295", "0.75390434", "0.7535139", "0.7526556", "0.7525841", "0.7523013", "0.7502334", "0.7496815", "0.749602", "0.74903554", "0.7488699", "0.7485389", "0.74852335", "0.7480906", "0.74808306", "0.7468446", "0.7464375", "0.7462793", "0.7462452", "0.7462232", "0.74619484", "0.7460611", "0.7459907", "0.74555093", "0.74540013", "0.7451341", "0.744903", "0.7448647", "0.7441215", "0.74411964", "0.74403214", "0.74372", "0.74347496", "0.7432971", "0.7432003", "0.74247444", "0.74245083", "0.7423247", "0.74226403", "0.74206406", "0.74190134", "0.74183726", "0.7413951", "0.741255", "0.74115765", "0.74086946", "0.7407648", "0.7403718", "0.74002796" ]
0.7953747
5
GetUser returns a user
func GetUser(w http.ResponseWriter, r *http.Request) { httpext.SuccessAPI(w, "ok") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetUser(c *gin.Context) *models.User {\n\tuser, _, _ := cookies.CurrentUser(c)\n\tif user == nil {\n\t\treturn &models.User{}\n\t}\n\treturn user\n}", "func GetUser(id int) (components.User, error) {\n\treturn getUser(id)\n}", "func GetUser(r *http.Request, db *gorm.DB) (User, error) {\n\t// Retrieve the auth token from the request context\n\ttoken, err := GetTokenFrom(r.Context())\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\t// Retrieve the client UID from the token\n\tcurrentUID := token.UID\n\n\t// Fetch the current user\n\tvar user User\n\tif result := db.FirstOrCreate(&user, User{ID: currentUID}); result.Error != nil {\n\t\treturn User{}, result.Error\n\t}\n\treturn user, nil\n}", "func GetUser(c *fiber.Ctx) error {\n\tclaims, err := utils.ExtractTokenMetadata(c)\n\tusername := claims.Username\n\t// check if the user requested is equel to JWT user\n\tif username != c.Params(\"user_name\") {\n\t\treturn c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{\n\t\t\t\"error\": true,\n\t\t\t\"msg\": \"Forbidden, requested user is different from JWT user\",\n\t\t})\n\t}\n\n\tuser, err := queries.GetUserByUsername(username)\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": true,\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t}\n\tif user == nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": true,\n\t\t\t\"msg\": \"Error, apparently we could not find you on the database\",\n\t\t})\n\t}\n\ttype user_simple struct {\n\t\tUsername string `json:\"Username\"`\n\t\tEmail string `json:\"Email\"`\n\t\tCreatedAt time.Time `json:\"CreatedAt\"`\n\t}\n\n\tvar my_user_simple user_simple\n\tmy_user_simple.Username = user.Username\n\tmy_user_simple.Email = user.Email\n\tmy_user_simple.CreatedAt = user.CreatedAt\n\n\treturn c.Status(200).JSON(user) //my_user_simple)\n}", "func (serv *AppServer) GetUser(uID int) User {\n\treturn *ParseUser(serv.ServerRequest([]string{\"GetUser\", strconv.Itoa(uID)}))\n}", "func (c *DefaultIdentityProvider) GetUser(ctx context.Context, name string, options *metav1.GetOptions) (*auth.User, error) {\n\t_, tenantID := authentication.GetUsernameAndTenantID(ctx)\n\tif tenantID != \"\" && tenantID != c.tenantID {\n\t\treturn nil, apierrors.NewBadRequest(\"must in the same tenant\")\n\t}\n\n\tlocalIdentity, err := c.localIdentityLister.Get(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif localIdentity.Spec.TenantID != c.tenantID {\n\t\treturn nil, apierrors.NewNotFound(auth.Resource(\"user\"), name)\n\t}\n\n\tuser := convertToUser(localIdentity)\n\treturn &user, nil\n}", "func (a Authorizer) GetUser(u string, req *http.Request) (user models.User, e error) {\n\t// This should search and fetch the user name based on the given value\n\t// and can also check whether the available users are already imported\n\t// into the database or not.\n\n\t//if username is me, get the currently loggedin user\n\tif u == authprovider.CurrentUser {\n\t\tsession, err := skyring.Store.Get(req, \"session-key\")\n\t\tif err != nil {\n\t\t\tlogger.Get().Error(\"Error getting the session for user: %s. error: %v\", u, err)\n\t\t\treturn user, err\n\t\t}\n\t\tif val, ok := session.Values[\"username\"]; ok {\n\t\t\tu = val.(string)\n\t\t} else {\n\t\t\tlogger.Get().Error(\"Unable to identify the user: %s from session\", u)\n\t\t\treturn user, mkerror(\"Unable to identify the user from session\")\n\t\t}\n\t}\n\tuser, e = a.userDao.User(u)\n\tif e != nil {\n\t\tlogger.Get().Error(\"Error retrieving the user: %s. error: %v\", user, e)\n\t\treturn user, e\n\t}\n\treturn user, nil\n}", "func (c *Client) GetUser() (User, error) {\n\n\tpath := c.url(\"user\")\n\n\tvar resp struct {\n\t\tUser User\n\t}\n\n\terr := c.do(http.MethodGet, path, nil, &resp)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\n\treturn resp.User, nil\n}", "func (s *Server) GetUser(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar (\n\t\tmeUser = p.ByName(\"userID\") == \"me\"\n\t\tresp = JSON(nil, res)\n\t)\n\n\t// handle other users later!\n\tif !meUser {\n\t\tresp.Error(errors.New(\"kljshadf\"), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tu := User{\n\t\tID: uuid.NewV1(),\n\t\tEmail: \"test\",\n\t}\n\n\t// switch err {\n\t// case nil:\n\tresp.Success(u)\n\t// case api.ErrInvalidUserID:\n\t// \tresp.Error(err, http.StatusNotFound)\n\t// default:\n\t// \tresp.Error(err, http.StatusInternalServerError)\n\t// }\n}", "func (c Client) GetUser(ctx context.Context, id string) (api.User, error) {\n\t// TODO (erik): Make this function handle emails properly.\n\tvar user api.User\n\tif err := c.db.GetContext(ctx, &user, \"select * from users where id = ?\", id); err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n\temail := chi.URLParam(r, \"email\")\n\n\tvar user User\n\tres := h.Collection.FindOne(context.TODO(), bson.M{\"_id\": email}, options.FindOne())\n\n\tif err := res.Decode(&user); err != nil {\n\t\tif strings.Contains(err.Error(), \"mongo: no documents in result\") {\n\t\t\thttp.Error(w, http.StatusText(404), 404)\n\t\t\treturn\n\t\t}\n\t\th.Logger.Errorf(\"err decoding item: %s\", err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\tuser.Password = \"\" // Never return password hashes\n\trender.JSON(w, r, user) // A chi router helper for serializing and returning json\n}", "func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.Atoi(r.URL.Query().Get(\"id\"))\n\tif err != nil {\n\t\trender.BadRequest(w, r, \"id must be an integer greater zero\")\n\t\treturn\n\t}\n\n\t// Query user details from userID\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.ID(id)).\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\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\trender.OK(w, r, user)\n}", "func (m *Model) GetUser(ctx context.Context, id string) (*dto.User, error) {\n\treturn m.userDAO.Get(ctx, id)\n}", "func (a Authorizer) GetUser(u string, req *http.Request) (user models.User, e error) {\n\t//if username is me, get the currently loggedin user\n\tif u == authprovider.CurrentUser {\n\t\tsession, err := skyring.Store.Get(req, \"session-key\")\n\t\tif err != nil {\n\t\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\t\treturn user, err\n\t\t}\n\t\tif val, ok := session.Values[\"username\"]; ok {\n\t\t\tu = val.(string)\n\t\t} else {\n\t\t\tlogger.Get().Error(\"Unable to identify the user from session\")\n\t\t\treturn user, mkerror(\"Unable to identify the user from session\")\n\t\t}\n\t}\n\tuser, e = a.userDao.User(u)\n\tif e != nil {\n\t\tlogger.Get().Error(\"Error retrieving the user: %s. error: %v\", u, e)\n\t\treturn user, e\n\t}\n\treturn user, nil\n}", "func GetUser(qy db.Queryer, userid int64) (*User, error) {\n\treturn GetUserWithID(qy, userid)\n}", "func (s *service) GetUser(ctx context.Context, userID string) (model.User, error) {\n\tlog.Trace(\"userservice.GetUser(%v) called\", userID)\n\n\tuser, err := s.repository.GetUser(ctx, userID)\n\tif err != nil {\n\t\tlog.Errorf(\"GetUser error: %v\", err)\n\t}\n\treturn user, s.errTranslator(err)\n}", "func (h *Handler) GetUser(c *fiber.Ctx) error {\n\tid, err := strconv.Atoi(c.Params(\"id\"))\n\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\"status\": \"error\", \"message\": \"User ID is invalid\"})\n\t}\n\n\tvar usr user.User\n\n\tusr, err = h.service.GetUserById(id)\n\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\"status\": \"error\", \"message\": \"Cannot get user\"})\n\t}\n\n\treturn c.Status(200).JSON(fiber.Map{\"status\": \"success\", \"data\": user.Response{\n\t\tEmail: usr.Email,\n\t\tName: usr.Name,\n\t}})\n}", "func GetUser(ctx *zion.Context) User {\n\textra := ctx.Extra(zion.ExtraUser)\n\tif extra != nil {\n\t\tuser, ok := extra.(User)\n\t\tif user != nil && ok {\n\t\t\treturn user\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *userServices) GetUser(userID uint64) (*userdata.User, *errors.RestErr) {\n\tresult := &userdata.User{ID: userID}\n\tif err := result.Get(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (u *userService) GetUser(userid int64) (*domain.User, *utils.ApplicationError) {\n\treturn domain.UserDto.GetUser(userid)\n}", "func (service Service) GetUser(string) user.User {\n\treturn user.User{}\n}", "func (u *UserAppInterface) GetUser(userId uint64) (*entity.User, error) {\n\treturn u.GetUserFn(userId)\n}", "func GetUser(c *gin.Context) {\n\t//authenticate the user and check the user by the auth_token\n\tif err := oauth.AuthenticateRequest(c.Request); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\t// strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\t// strconv.Atoi(c.Param(\"user_id\"))\n\tuserID, userErr := strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\tif userErr != nil {\n\t\terr := errors.NewBadRequestError(\"user id should be a number\")\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\t// send the id to the services\n\tuser, getErr := services.UsersService.GetUser(userID)\n\tif getErr != nil {\n\t\tc.JSON(getErr.Status, getErr)\n\t\treturn\n\t}\n\n\t//check whether the caller ID is the same with the user ID\n\tif oauth.GetCallerId(c.Request) == user.ID {\n\t\tc.JSON(http.StatusOK, user.Marshall(false))\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, user.Marshall(oauth.IsPublic(c.Request)))\n}", "func GetUser(ctx *aero.Context) *arn.User {\n\treturn arn.GetUserFromContext(ctx)\n}", "func (s *Store) GetUser(id bson.ObjectId) (*models.User, error) {\n\tvar user models.User\n\terr := s.Users.Find(bson.M{\"_id\": id}).One(&user)\n\treturn &user, err\n}", "func getUser(c *gin.Context, db *gorm.DB) *models.User {\n\tuserID, err := strconv.Atoi(c.Param(\"userID\"))\n\tif err != nil {\n\t\tjsonError(c, \"could not parse user id\", err)\n\t\treturn nil\n\t}\n\n\tuser := &models.User{}\n\tq := db.Where(\"id = ?\", userID).First(user)\n\tif err := q.Error; err != nil {\n\t\tjsonError(c, \"error looking up user\", err)\n\t\treturn nil\n\t} else if q.RecordNotFound() {\n\t\tjsonError(c, \"user not found\", nil)\n\t\treturn nil\n\t}\n\treturn user\n}", "func (svc *Service) GetUser(name string) (*model.User, error) {\n\tu, err := svc.Repository.GetUser(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Example of emitting webhook events\n\t// svc.Event.CreatedUser(name)\n\treturn u, nil\n}", "func (r *Repo) GetUser(_ context.Context, id int64) (entities.User, error) {\n\tvar u entities.User\n\terr := r.Get(&u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn entities.User{}, fmt.Errorf(\"error getting user: %w\", err)\n\t}\n\treturn u, nil\n}", "func (s *UserServiceImpl) GetUser(c *gin.Context, userID int) (*models.User, error) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\tuser := &models.User{}\n\terr := db.First(&user, userID).Error\n\treturn user, err\n}", "func (c CvpRestAPI) GetUser(userID string) (*SingleUser, error) {\n\tvar info SingleUser\n\n\tquery := &url.Values{\"userId\": {userID}}\n\n\tresp, err := c.client.Get(\"/user/getUser.do\", query)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"GetUser: %s\", err)\n\t}\n\n\tif err = json.Unmarshal(resp, &info); err != nil {\n\t\treturn nil, errors.Errorf(\"GetUser: %s Payload:\\n%s\", err, resp)\n\t}\n\n\tif err := info.Error(); err != nil {\n\t\treturn nil, errors.Errorf(\"GetUser: %s\", info.String())\n\t}\n\treturn &info, nil\n}", "func GetUser(userID int64) (*models.User, *utils.ApplicationError) {\n\treturn repositories.GetUser(userID)\n}", "func GetUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\tuser := getUserByID(db, id, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusOK, user)\n}", "func (db *DB) GetUser(w http.ResponseWriter, r *http.Request) {\n\t// get all parameters in form of map\n\tvars := mux.Vars(r)\n\n\tvar user User\n\n\tcollection := db.Database.C(\"users\")\n\tstatement := bson.M{\"_id\": bson.ObjectIdHex(vars[\"id\"])}\n\terr := collection.Find(statement).One(&user)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(\"No Such User\"))\n\t\tlog.Fatalln(\"error in retrieving the data\")\n\t} else {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tresponse, err := json.Marshal(user)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"error in converting struct to json \", err)\n\t\t}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.Write(response)\n\t}\n\n}", "func (u *UserHandler) GetUser(c *gin.Context) {\n\tuserID := c.Param(\"userid\")\n\n\tif userID != \"me\" {\n\t\terr := errors.New(\"cannot get info about other users\")\n\t\tapiError := api.NewAPIError(http.StatusBadRequest, err, \"cannot get info about other users\")\n\t\t_ = c.Error(apiError).SetType(gin.ErrorTypePublic)\n\t\treturn\n\t}\n\n\tuser, err := (*u.AuthMiddleware).GetUser(c)\n\tif err != nil {\n\t\t_ = c.Error(err).SetType(gin.ErrorTypePublic)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, adapter.UserDomainToDTO(user))\n}", "func (um *UserManager) GetUser(userID int) (*User, error) {\n\treturn GetUser(um.logger, um.db, um.oauthConf, userID)\n}", "func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n\t// Parse the content of the url\n\tid := chi.URLParam(r, \"ID\")\n\tuserID, err := strconv.Atoi(id)\n\tif err != nil {\n\t\th.log.WithError(err)\n\t\tweb.RespondWithCodedError(w, r, http.StatusBadRequest, \"bad request\", err)\n\t\treturn\n\t}\n\t// Go out to the db and try to get the hashed password associated with the provided email\n\tu, err := user.GetByID(h.db, userID)\n\n\tif err != nil {\n\t\t// The user was not in the db\n\t\tif err == sql.ErrNoRows {\n\t\t\th.log.WithError(err).Info()\n\t\t\tweb.RespondWithCodedError(w, r, http.StatusBadRequest, \"user does not exist\", errors.Wrap(err, \"get user\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Something else went wrong\n\t\th.log.WithError(err).Info()\n\t\tweb.RespondWithCodedError(w, r, http.StatusInternalServerError, \"\", errors.Wrap(err, \"login\"))\n\t\treturn\n\t}\n\n\tweb.Respond(w, r, getResponse{\n\t\tResponse: web.Response{\n\t\t\tMessage: \"success\",\n\t\t},\n\t\tUser: u,\n\t}, http.StatusOK)\n}", "func (c Companion) GetUser() *User {\n\tdb := db.GetDb()\n\tuser := new(User)\n\tdb.First(&user, c.UserID)\n\treturn user\n}", "func (r *UsersResource) GetUser(c *gin.Context) {\n\tuserID := c.Param(\"user\")\n\n\tif user, err := r.userStore.User(userID); err == nil {\n\t\tif user == nil {\n\t\t\tc.Status(http.StatusNotFound)\n\t\t} else {\n\t\t\tc.JSON(http.StatusOK, user)\n\t\t}\n\t} else {\n\t\tc.Error(err)\n\t\tc.Status(http.StatusInternalServerError)\n\t}\n}", "func (service Service) GetUser(context echo.Context) User {\n\tid := context.Get(\"id\").(int)\n\tuser := context.Get(\"username\").(string)\n\temail := context.Get(\"email\").(string)\n\trole := context.Get(\"role\").(AccessRole)\n\n\treturn User{\n\t\tID: id,\n\t\tUsername: user,\n\t\tEmail: email,\n\t\tRole: role,\n\t}\n}", "func (c *Client) GetUser(userID string) (out *User, err error) {\n\treturn c.GetUserWithContext(context.Background(), userID)\n}", "func (c *Client) GetUser(userID, fingerprint, ipAddress string, queryParams ...string) (*User, error) {\n\tlog.info(\"========== GET USER ==========\")\n\turl := buildURL(path[\"users\"], userID)\n\tres, err := c.do(\"GET\", url, \"\", queryParams)\n\n\tvar user User\n\tmapstructure.Decode(res, &user)\n\tuser.Response = res\n\trequest := Request{\n\t\tclientID: c.ClientID,\n\t\tclientSecret: c.ClientSecret,\n\t\tfingerprint: fingerprint,\n\t\tipAddress: ipAddress,\n\t}\n\tuser.request = request\n\n\treturn &user, err\n}", "func (c *Client) GetUser(userId string) (user User, err error) {\n\tresp, err := req.Post(c.url+\"/usermanager/api/v1/users/\"+userId, c.header, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.Response().StatusCode >= 300 {\n\t\tvar reqErr Error\n\t\tresp.ToJSON(&reqErr)\n\t\terr = reqErr\n\t\treturn\n\t}\n\n\terr = resp.ToJSON(&user)\n\treturn\n}", "func (c *Client) GetUser(ctx context.Context, id string) (*UserResponse, error) {\n\tvar resp struct {\n\t\tUser UserResponse `json:\"user\"`\n\t}\n\n\tvariables := make(map[string]interface{})\n\tvariables[\"id\"] = id\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery User($id: String!) {\n\t\t\tuser(id: $id) {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, variables, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resp.User, nil\n}", "func GetUser(c *fiber.Ctx) {\n\tvar user User\n\tid := c.Params(\"id\")\n\tdatabase.DBConn.First(&user, \"name = ?\", id)\n\tif user.Name == \"\" {\n\t\tc.Status(500).Send(\"Cannot find user with the ID of \", id)\n\t\treturn\n\t}\n\tc.JSON(user)\n}", "func (m *UserResource) GetUser(ctx context.Context, userId string) (*User, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v\", 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 user *User\n\n\tresp, err := rq.Do(ctx, req, &user)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn user, resp, nil\n}", "func (repo *GormRepository) GetUser(userID uint) (*models.User, error) {\n\tuser := models.User{\n\t\tID: userID,\n\t}\n\t// if err := repo.db.First(&user).Error; err != nil {\n\t// \treturn nil, err\n\t// }\n\t// return &user, nil\n\treturn getUser(repo.db, false, &user)\n}", "func (c *OAuthClient) GetUser(user *model.User, firstConnect bool) (*User, *AuthError) {\n\tzoomUser, err := c.getUserViaOAuth(user, firstConnect)\n\tif err != nil {\n\t\tif c.isAccountLevel {\n\t\t\tif err == errNotFound {\n\t\t\t\treturn nil, &AuthError{fmt.Sprintf(zoomEmailMismatch, user.Email), err}\n\t\t\t}\n\n\t\t\treturn nil, &AuthError{fmt.Sprintf(\"Error fetching user: %s\", err), err}\n\t\t}\n\n\t\treturn nil, &AuthError{fmt.Sprintf(OAuthPrompt, c.siteURL), err}\n\t}\n\n\treturn zoomUser, nil\n}", "func (u *UserService) GetUser(ctx context.Context, principal jwt.User, id string) (model.User, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"user_service_get_user\")\n\tdefer span.Finish()\n\n\terr := u.AuthService.AssertUserAccess(ctx, principal, id)\n\tif err != nil {\n\t\treturn model.User{}, err\n\t}\n\n\tuser, found, err := u.UserRepo.Find(ctx, id)\n\tif err != nil {\n\t\treturn model.User{}, err\n\t}\n\n\tif !found {\n\t\terr = fmt.Errorf(\"user with id %s does not exist\", id)\n\t\treturn model.User{}, httputil.NotFoundError(err)\n\t}\n\n\tu.AuditLog.Read(ctx, principal.ID, \"user:%s\", id)\n\treturn user, nil\n}", "func (s *Server) GetUser(ctx context.Context) (*model.User, context.Context, error) {\n\tuser, _ := ctx.Value(GetUserCtx).(*model.User)\n\tif user != nil {\n\t\treturn user, ctx, nil\n\t}\n\ttoken, ok := ctx.Value(TokenCtx).(*jwt.Token)\n\tif !ok {\n\t\treturn nil, ctx, errors.New(`no token in context`)\n\t}\n\tid := token.Claims.(jwt.MapClaims)[\"id\"].(int)\n\tuser, err := s.model.GetUserById(id)\n\tif err != nil {\n\t\treturn nil, ctx, err\n\t}\n\tctx = context.WithValue(ctx, GetUserCtx, user)\n\treturn user, ctx, nil\n}", "func GetUser(ctx context.Context) *user.User {\n\tx, _ := ctx.Value(userKey{}).(*user.User)\n\treturn x\n}", "func (m *User) GetUser(id int64) (interface{}, error) {\n\tm.ID = id\n\te := m.Read()\n\treturn m, e\n}", "func (m *User) GetUser(id int64) (interface{}, error) {\n\tm.ID = id\n\te := m.Read()\n\treturn m, e\n}", "func (g Graph) GetUser(w http.ResponseWriter, r *http.Request) {\n\tuserID := chi.URLParam(r, \"userID\")\n\tuserID, err := url.PathUnescape(userID)\n\tif err != nil {\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, \"unescaping user id failed\")\n\t}\n\n\tif userID == \"\" {\n\t\terrorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, \"missing user id\")\n\t\treturn\n\t}\n\n\tuser, err := g.identityBackend.GetUser(r.Context(), userID)\n\n\tif err != nil {\n\t\tvar errcode errorcode.Error\n\t\tif errors.As(err, &errcode) {\n\t\t\terrcode.Render(w, r)\n\t\t} else {\n\t\t\terrorcode.GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())\n\t\t}\n\t}\n\n\trender.Status(r, http.StatusOK)\n\trender.JSON(w, r, user)\n}", "func (s *Store) GetUser(ctx context.Context, name string) (user *User, err error) {\n\tif name, err = CheckName(name); err != nil {\n\t\treturn nil, err\n\t}\n\tuser, err = s.rawUser(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn secureUser(user), nil\n}", "func (c *Client) GetUser(userID int) (*User, error) {\n\tuserIDStr := strconv.Itoa(userID)\n\n\tresp := &User{}\n\terr := c.apiget(\"/users/\"+userIDStr, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (test *Test) GetUser(username string) (models.User, error) {\n\tif tests.NormalUser.Name == username {\n\t\treturn tests.NormalUser, nil\n\t}\n\treturn models.User{}, errors.New(\"User not found\")\n}", "func GetUser(c *gin.Context) {\n\tlog.Println(\"GetUser from db\")\n\tvar user models.User\n\tid := c.Param(\"id\")\n\tdb := db.GetDB()\n\tif err := db.Where(\"id = ?\", id).First(&user).Error; err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tlog.Println(\"Failed to GetUser in db\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, user)\n}", "func getUser(ctx context.Context, Username string) (*User, error) {\n\tkey := datastore.NameKey(\"Users\", strings.ToLower(Username), nil)\n\tcurUser := &User{}\n\tif err := dbclient.Get(ctx, key, curUser); err != nil {\n\t\treturn &User{}, err\n\t}\n\n\treturn curUser, nil\n}", "func GetUser(userID int64) (*users.User, *errors.RestErr) {\n\tresult := &users.User{ID: userID}\n\tif err := result.Get(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (u *UserService) GetUser(id string) (*User, error) {\n\tuser := &User{}\n\terr := u.QueryRow(\"SELECT id, name, phone, email, password FROM users WHERE id=$1 LIMIT 1\", id).Scan(&user.ID, &user.Name, &user.Phone, &user.Email, &user.HashedPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (_this *UserHandler) GetUser() echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tid, _ := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\n\t\tresp, err := _this.userService.GetUser(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.JSON(http.StatusOK, resp)\n\t}\n}", "func (p Provider) GetUser(email string) (User, error) {\n\tuser, err := p.Storage.User(email)\n\tif err != nil {\n\t\tif errors.Is(err, storage.ErrUserNotFound) {\n\t\t\treturn User{}, ErrUserNotFound\n\t\t}\n\n\t\treturn User{}, fmt.Errorf(\"failed to find user with email %q: %w\", email, err)\n\t}\n\n\treturn User{\n\t\tEMail: user.EMail,\n\t\tPassword: blankedPassword,\n\t\tClaims: user.Claims,\n\t}, nil\n}", "func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t// Grab id\n\tid := p.ByName(\"id\")\n\n\t// Verify id is ObjectId, otherwise bail\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Grab id\n\toid := bson.ObjectIdHex(id)\n\n\t// Stub user\n\tu := models.User{}\n\n\t// Fetch user\n\tif err := uc.session.DB(\"todos\").C(\"users\").FindId(oid).One(&u); err != nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Marshal provided interface into JSON structure\n\tuj, _ := json.Marshal(u)\n\n\t// Write content-type, statuscode, payload\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}", "func GetUser(c *gin.Context) {\n\tif userCollection == nil {\n\t\tuserCollection = db.GetUserCollection()\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tvar userInfo entity.User\n\tid, _ := primitive.ObjectIDFromHex(c.Param(\"id\"))\n\n\terr := userCollection.FindOne(ctx, entity.User{ID: id}).Decode(&userInfo)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(501, gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"User\": &userInfo})\n}", "func GetUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\trepo := users.NewUserRepository(db)\n\tvars := mux.Vars(r)\n\n\ttarget, _ := strconv.Atoi(vars[\"id\"])\n\tuser, changed := repo.GetUser(users.User{}, target)\n\n\tif !changed {\n\t\tutils.JsonResponse(w, utils.ErrorResponse{Error: \"User matching query not found\"}, http.StatusNotFound)\n\t} else {\n\t\tutils.JsonResponse(w, user, http.StatusOK)\n\t}\n}", "func GetUser(ctx context.Context) *models.User {\n\traw := ctx.Value(ctxKey)\n\trawConvert, isValid := raw.(map[string]interface{})\n\tvar oUser *models.User\n\n\tif isValid {\n\t\toUser = rawConvert[\"user\"].(*models.User)\n\t}\n\n\treturn oUser\n}", "func GetUser(ctx *enliven.Context) *User {\n\t// If they're not logged in or this app isn't installed, return 0\n\tif !ctx.Enliven.AppInstalled(\"user\") || ctx.Booleans[\"UserLoggedIn\"] == false {\n\t\treturn nil\n\t}\n\n\t// The user may be cached from an earlier lookup.\n\tif user, ok := ctx.Storage[\"User\"]; ok {\n\t\treturn user.(*User)\n\t}\n\n\tvar user User\n\tdbUserID, _ := ctx.Integers[\"UserID\"]\n\tdatabase.GetDatabase().Preload(\"Groups\").Preload(\"Groups.Permissions\").First(&user, dbUserID)\n\n\t// Caching the user lookup for later.\n\tctx.Storage[\"User\"] = &user\n\n\treturn &user\n}", "func (c *Client) GetUser(id string) (*dto.User, error) {\n\tvar user *dto.User\n\n\tr, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"users/%s\", id),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\t_, err = c.Do(r, &user)\n\treturn user, err\n}", "func (u *UsersAPI) GetUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\tuser, err := u.service.GetUser(id)\n\tif err != nil {\n\t\thandler.RespondError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\thandler.RespondJSON(w, http.StatusOK, user)\n}", "func (auth *Authenticator) GetUser(name string) (User, error) {\n\tprinc, err := auth.getPrincipal(docIDForUser(name), func() Principal { return &userImpl{} })\n\tif err != nil {\n\t\treturn nil, err\n\t} else if princ == nil {\n\t\tif name == \"\" {\n\t\t\tprinc = auth.defaultGuestUser()\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tprinc.(*userImpl).auth = auth\n\treturn princ.(User), err\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\tid, _ := strconv.Atoi(mux.Vars(r)[\"id\"])\n\tuser, err := models.GetUser(id)\n\n\tif err != nil {\n\t\tfmt.Fprintln(w, http.StatusNotFound)\n\t} else {\n\t\tjson.NewEncoder(w).Encode(user)\n\t}\n}", "func GetUser(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tvar result User\n\tdb.FindId(id).One(&result)\n\tresult.Token = \"\"\n\treturn result\n}", "func (s *AutograderService) GetUser(ctx context.Context, in *pb.Void) (*pb.User, error) {\n\tusr, err := s.getCurrentUser(ctx)\n\tif err != nil {\n\t\ts.logger.Errorf(\"GetUser failed: authentication error: %w\", err)\n\t\treturn nil, ErrInvalidUserInfo\n\t}\n\tdbUsr, err := s.db.GetUserWithEnrollments(usr.GetID())\n\tif err != nil {\n\t\ts.logger.Errorf(\"GetUser failed to get user with enrollments: %w \", err)\n\t}\n\treturn dbUsr, nil\n\n}", "func (c Controller) GetUser(w http.ResponseWriter, r *http.Request) {\n\tuserID := chi.URLParam(r, \"userID\")\n\tuser, err := c.userService.GetUser(r.Context(), userID)\n\tif err != nil {\n\t\thttp.Error(w, \"could not fetch user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif user == nil {\n\t\thttp.Error(w, \"user not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\trender.JSON(w, r, user)\n}", "func (u *User) GetUser(db *sql.DB) (*User, error){\n\taccount := &User{}\n\tvar err error\n\tdefer func() {\n\t\tlog.Printf(\"get user: err %v\", err)\n\t}()\n\t//log.Printf(u.Email)\n\terr = db.QueryRow(\"select first_name, last_name, id, password from users where email = $1\", u.Email).\n\t\tScan(&u.FirstName, &u.LastName, &u.ID, &u.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn account, nil\n}", "func (s *ServiceContext) GetUser(userIDOrPrincipal string) (User, error) {\n\treturn s.GetUserWithFields(userIDOrPrincipal, UserDefaultFields)\n}", "func GetUser(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(req)\n\tuserID := bson.ObjectIdHex(params[\"userID\"])\n\n\tquery := bson.M{\n\t\t\"_id\": userID,\n\t}\n\n\tselector := bson.M{\n\t\t\"_id\": 1,\n\t\t\"name\": 1,\n\t\t\"email\": 1,\n\t}\n\n\tuser, err := db.GetUser(query, selector)\n\tif err != nil {\n\t\tif err.Error() == mgo.ErrNotFound.Error() {\n\t\t\tmsg := \"User not found\"\n\n\t\t\tutils.ReturnErrorResponse(http.StatusNotFound, msg, \"\", nil, nil, res)\n\t\t\treturn\n\t\t}\n\n\t\tmsg := \"Error occurred while getting user details\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tmsg := \"Your request processed successfully\"\n\tutils.ReturnSuccessReponse(http.StatusOK, msg, user, res)\n\n}", "func (s *server) GetUser(ctx context.Context, in *pb.UserRequest) (*pb.UserResponse, error) {\n\tlog.Printf(\"Received: %v\", in.UserId)\n\n\tdb, err := SetupDB()\n\n\tif err != nil {\n\t\tlog.Print(\"database disconnect\")\n\t\treturn nil, status.Error(codes.Internal, \"database disconnect\")\n\t}\n\n\t// create a value into which the result can be decoded\n\tvar u User\n\n\terr = db.Collection(\"user\").FindOne(context.TODO(), bson.D{primitive.E{Key: \"_id\", Value: in.UserId}}).Decode(&u)\n\n\tif err != nil {\n\t\tlog.Printf(\"id %v was not found\", in.UserId)\n\t\treturn nil, status.Error(codes.NotFound, \"id was not found\")\n\t}\n\n\tlog.Printf(\"Found a single document: %+v\\n\", u)\n\n\treturn &pb.UserResponse{User: &pb.User{\n\t\tId: u.Id,\n\t\tFirstName: u.FirstName,\n\t\tLastName: u.LastName,\n\t\tDateOfBirth: u.DateOfBirth.Unix(),\n\t}}, nil\n}", "func (c UserController) GetUser(db *sql.DB) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tparams := mux.Vars(r)\n\t\tvar user models.User\n\t\tvar error models.Error\n\t\tif !utils.IsAuthorized(r) {\n\t\t\terror.Message = \"unauthorized access\"\n\t\t\tutils.SendError(w, http.StatusUnauthorized, error)\n\t\t\treturn\n\t\t}\n\n\t\tuserRepo := userrepository.UserRepository{}\n\t\tid, _ := strconv.Atoi(params[\"id\"])\n\n\t\tuser, err := userRepo.GetUser(db, id)\n\t\tif err != nil {\n\t\t\terror.Message = \"Server error\"\n\t\t\tutils.SendError(w, http.StatusInternalServerError, error)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tutils.SendSuccess(w, user)\n\n\t}\n}", "func (db *Client) GetUser(query *models.User) (*models.User, error) {\n\tuser := &models.User{}\n\tresult := db.Where(query).Find(user)\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\tif result.RowsAffected == 0 {\n\t\treturn nil, nil\n\t}\n\treturn user, nil\n}", "func (s Session) GetUser(ctx context.Context) (middleware.User, error) {\n\tuser, err := loader.Loader.GetUser(ctx, s.UserID)\n\treturn User{Row: user}, err\n}", "func (mp *MongoUserDB) GetUser(ctx context.Context, email string) (User, error) {\r\n\t// This object will store the user data if we find it.\r\n\tuser := User{}\r\n\r\n\t// Query the database...\r\n\tresult := mp.client.Database(\"userdb\").Collection(\"users\").FindOne(ctx, bson.D{{Key:\"email\", Value:email}})\r\n\r\n\t// If we successfully got a user with the email...\r\n\tif result.Err() != nil {\r\n\t\treturn user, result.Err()\r\n\t}\r\n\r\n\t// Decode the bson into a usable struct.\r\n\tresult.Decode(&user)\r\n\r\n\treturn user, nil\r\n}", "func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\n\t//get the param first\n\tid := params.ByName(\"id\")\n\n\t//verify id is objectid hex representation, otherwise return status not found\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(http.StatusNotFound) //404\n\t\treturn\n\t}\n\n\t//objectidhex returns as object id from the provided hex representation\n\toid := bson.ObjectIdHex(id)\n\n\tu := models.User{}\n\n\t//fetch user\n\tif err := uc.session.DB(\"go-web-dev-db\").C(\"users\").FindId(oid).One(&u); err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tuj, err := json.Marshal(u)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application.json\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n\n}", "func (userController UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tid := p.ByName(\"id\")\n\n\tif !bson.IsObjectIdHex(id) {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\toid := bson.ObjectIdHex(id)\n\n\tu := models.User{}\n\n\tif err := userController.session.DB(\"office_space\").C(\"users\").FindId(oid).One(&u); err != nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\tuj, _ := json.Marshal(u)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", uj)\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tuserID, err := strconv.ParseInt(params[\"id\"], 10, 64)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\tuser, err := repository.GetUserById(userID)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tif user.Id == 0 {\n\t\tresponses.Error(w, http.StatusNotFound, errors.New(\"Usuarios não encontrado\"))\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, user)\n\n}", "func (s *Service) GetUser(c context.Context, username string) (usr *user.User, err error) {\n\tusr = &user.User{}\n\terr = s.DB.Where(\"username = ?\", username).First(usr).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\tusr.UserName = username\n\t\tusr.NickName = username\n\t\terr = s.DB.Create(usr).Error\n\t}\n\tif err != nil {\n\t\tlog.Error(\"apmSvc.GetUser error(%v)\", err)\n\t\treturn\n\t}\n\ts.ranksCache.Lock()\n\tif s.ranksCache.Map[username] != nil {\n\t\tusr.AvatarURL = s.ranksCache.Map[username].AvatarURL\n\t} else {\n\t\tusr.AvatarURL, _ = s.dao.GitLabFace(c, username)\n\t}\n\ts.ranksCache.Unlock()\n\treturn\n}", "func GetUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tuserId := vars[\"user_id\"]\n\tuser, err := dal.GetUsers(userId)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tcommon.WriteResponse(w, user[0])\n}", "func (s *SSO) GetUser(r *http.Request) (u crowd.User, err error) {\n\tcurrentCookie, err := r.Cookie(s.CookieConfig.Name)\n\tif err == http.ErrNoCookie {\n\t\treturn u, errors.New(\"no session cookie\")\n\t}\n\n\tuserSession, err := s.CrowdApp.GetSession(currentCookie.Value)\n\tif err != nil {\n\t\treturn u, errors.New(\"session not valid\")\n\t}\n\n\treturn userSession.User, nil\n}", "func GetUser(ctx *gin.Context, req *userparam.GetRequest) (*userparam.GetResponse, error) {\n\tres := userparam.NewGetResponse()\n\tif err := res.Convert(me.Get(ctx)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (s *UserRepository) GetUser(id string) (*akwad.Account, error) {\n\treturn nil, nil\n}", "func (d *DB) GetUser(id int) (User, error) {\n\tvar user User\n\terr := d.db.Find(&user, id).Error\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (c *Client) GetUser(username string) (*api.User, error) {\n\tout := &api.User{}\n\trawURL := fmt.Sprintf(pathUser, c.base.String(), username)\n\terr := c.get(rawURL, true, out)\n\treturn out, errio.Error(err)\n}", "func getUser(c *gin.Context) user.User {\n\tvar u user.User\n\tif v, ok := c.Get(session); ok {\n\t\tu = v.(user.User)\n\t}\n\treturn u\n}", "func GetUser(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *UserState, opts ...pulumi.ResourceOption) (*User, error) {\n\tvar resource User\n\terr := ctx.ReadResource(\"alicloud:bastionhost/user:User\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func GetUser(id int64) (*User, error) {\n\tuser := User{}\n\terr := meddler.QueryRow(db, &user, userFindIdStmt, id)\n\treturn &user, err\n}", "func (this *SSNDB) GetUser() User {\n\tvar user User\n\tthis.First(&user)\n\tlogger.AssertError(user.Id != 0, \"main user does not exist in db!\")\n\treturn user\n}", "func (db *DB) GetUser(id string) (*model.User, error) {\n\tvar user model.User\n\n\tcursor := db.collections.users.FindOne(\n\t\tcontext.Background(),\n\t\tbson.D{primitive.E{\n\t\t\tKey: \"_id\",\n\t\t\tValue: id,\n\t\t}},\n\t)\n\n\tif cursor.Err() != nil {\n\t\treturn nil, cursor.Err()\n\t}\n\n\terr := cursor.Decode(&user)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func (client *ShorelineClient) GetUser(userID, token string) (*UserData, 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, \"user\", userID)\n\n\treq, _ := http.NewRequest(\"GET\", host.String(), nil)\n\treq.Header.Add(\"x-tidepool-session-token\", token)\n\n\tres, err := client.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failure to get a user\")\n\t}\n\tdefer res.Body.Close()\n\n\tswitch res.StatusCode {\n\tcase http.StatusOK:\n\t\tud, err := extractUserData(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn ud, nil\n\tcase http.StatusNoContent:\n\t\treturn &UserData{}, 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 (s Set) GetUser(ctx context.Context, a string) (model.GetUserResponse, error) {\n\tresp, err := s.GetUserEndpoint(ctx, model.GetUserRequest{A: a})\n\tif err != nil {\n\t\treturn model.GetUserResponse{}, err\n\t}\n\tresponse := resp.(model.GetUserResponse)\n\treturn response, response.Err\n}", "func GetUser(w http.ResponseWriter, r *http.Request) GSUser {\n\tvar u GSUser\n\tcookie, err := r.Cookie(\"session\")\n\tif err == nil {\n\t\tif s, ok := gs.sessions[cookie.Value]; ok {\n\t\t\tu = gs.users[s.userName]\n\t\t\treturn u\n\t\t}\n\t}\n\treturn u\n}", "func GetUser(UserID, APIID string) *types.User {\n\tvar user types.User\n\tif err := db.Where(\"id = ? AND api_id = ?\", UserID, APIID).First(&user).Error; err != nil {\n\t\treturn nil\n\t}\n\treturn &user\n}" ]
[ "0.8062321", "0.8035611", "0.7954273", "0.79248595", "0.78996885", "0.7898914", "0.7882361", "0.78709865", "0.7867528", "0.78379095", "0.78259015", "0.7816404", "0.7814401", "0.7807357", "0.77910733", "0.7782622", "0.777936", "0.7777736", "0.77773476", "0.7764939", "0.7760323", "0.7754908", "0.77524906", "0.7747329", "0.77430063", "0.77420354", "0.7738285", "0.77376515", "0.7732342", "0.77279514", "0.7700901", "0.76852375", "0.76806563", "0.76756895", "0.7665731", "0.7655557", "0.76492", "0.76482546", "0.7642911", "0.7641357", "0.7641006", "0.76397085", "0.7626306", "0.76176906", "0.76075125", "0.75985736", "0.7597503", "0.75974274", "0.7586779", "0.75743407", "0.7568591", "0.7568591", "0.75680023", "0.7560592", "0.7546741", "0.75454485", "0.75413513", "0.75371087", "0.7533191", "0.7532835", "0.75319546", "0.7529924", "0.75252986", "0.75212234", "0.7516923", "0.7515168", "0.7514372", "0.75083876", "0.7504905", "0.750457", "0.7502273", "0.7500491", "0.7497006", "0.7494648", "0.7491829", "0.7490871", "0.74877816", "0.74809796", "0.7479189", "0.7477048", "0.7468953", "0.7463149", "0.746199", "0.746123", "0.7458721", "0.74550724", "0.7453589", "0.74483365", "0.7445584", "0.7445126", "0.7444112", "0.7441813", "0.7438965", "0.74386346", "0.74370944", "0.74360615", "0.74317086", "0.74243003", "0.7416555", "0.741558", "0.7410229" ]
0.0
-1
UpdateUser updates a user
func UpdateUser(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var update models.User err := decoder.Decode(&update) u, err := user.UpdateUser(update, r) if err != nil { httpext.AbortAPI(w, err.Error(), http.StatusInternalServerError) return } httpext.SuccessDataAPI(w, "Ok", u) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func updateUser(c *gin.Context) {\n\tvar user user\n\tuserID := c.Param(\"id\")\n\n\tdb.First(&user, userID)\n\n\tif user.Id == 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": http.StatusNotFound, \"message\": \"No user found!\"})\n\t\treturn\n\t}\n\n\tdb.Model(&user).Update(\"login\", c.PostForm(\"login\"))\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tdb.Model(&user).Update(\"password\", password)\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": \"User updated successfully!\"})\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Updating a user\"))\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\temail, err := getEmailFromTokenHeader(r)\n\tif err != nil || email == \"\" {\n\t\thttp.Error(w, \"Invalid Token\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"PUT\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\t// create an empty user of type models.User\n\tvar user models.User\n\t// decode the json request to user\n\terr = json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Unable to decode the request body. %v\", err)\n\t\thttp.Error(w, \"Invalid Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// call update user to update the user\n\tupdatedRows, err := database.UpdateUser(email, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlogrus.Errorf(\"failed updating user. %v\", err)\n\t\thttp.Error(w, \"Invalid Request\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlogrus.Debugf(\"User updated successfully. Total rows/record affected %v\", updatedRows)\n}", "func (a *App) UpdateUser(w http.ResponseWriter, r *http.Request) {\n\thandler.UpdateUser(a.DB, w, r)\n}", "func UpdateUser(\n\tctx context.Context,\n\ttx *sql.Tx,\n\trequest *models.UpdateUserRequest,\n) error {\n\t//TODO\n\treturn nil\n}", "func UpdateUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\tuser := getUserByID(db, id, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&user); err != nil {\n\t\tRespondError(w, http.StatusBadRequest, \"\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tif err := db.Save(&user).Error; err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusOK, user)\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Update user endpoint hit\")\n\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\n\temail := r.FormValue(\"email\")\n\n\tuser := &models.User{}\n\n\tuser.Update(id, email)\n\n\tjson.NewEncoder(w).Encode(user)\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tuserID, err := strconv.ParseInt(params[\"id\"], 10, 64)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tuserIDToken, err := authentication.ExtractUserId(r)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\n\tif userIDToken != userID {\n\t\tresponses.Error(w, http.StatusForbidden, errors.New(\"não é possível manipular usuário de terceiros\"))\n\t\treturn\n\t}\n\n\tbodyRequest, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tvar user models.User\n\tif err := json.Unmarshal(bodyRequest, &user); err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif err := user.Prepare(false); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Id = userID\n\tif err := validateUniqueDataUser(user, false); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\tif err = repository.UpdateUser(userID, user); err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusNoContent, nil)\n\n}", "func UpdateUser(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(req)\n\tuserID := bson.ObjectIdHex(params[\"userID\"])\n\n\tvar user models.User\n\tif err := json.NewDecoder(req.Body).Decode(&user); err != nil {\n\t\tmsg := \"Error while reading input body\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\t// Helper function to generate encrypted password hash\n\tpasswordHash := helpers.GeneratePasswordHash(user.Password)\n\n\tif passwordHash == \"\" {\n\t\tmsg := \"Error occurred while hashing the password\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tquery := bson.M{\n\t\t\"_id\": userID,\n\t}\n\n\tupdate := bson.M{\n\t\t\"$set\": user,\n\t}\n\n\terr := db.UpdateUser(query, update)\n\tif err != nil {\n\t\tif err.Error() == mgo.ErrNotFound.Error() {\n\t\t\tmsg := \"User not found\"\n\n\t\t\tutils.ReturnErrorResponse(http.StatusNotFound, msg, \"\", nil, nil, res)\n\t\t\treturn\n\t\t}\n\n\t\tmsg := \"Error occurred while updating the user\"\n\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tmsg := \"User updated successfully\"\n\tutils.ReturnSuccessReponse(http.StatusOK, msg, userID, res)\n\n}", "func UpdateUser(c *gin.Context) {\n\tdb := dbConn()\n\tvar user User\n\tif err := c.BindJSON(&user); err == nil {\n\t\tstatement, _ := db.Prepare(\"CALL update_user (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\")\n\t\tstatement.Exec(user.ID, user.UserName, user.UserEmail, user.FName, user.LName, user.Password, user.PasswordChange, user.PasswordExpired, user.LastLogon, user.AccountLocked)\n\t\tif err != nil {\n\t\t\tc.String(http.StatusInternalServerError, err.Error())\n\t\t}\n\t} else {\n\t\tc.String(http.StatusInternalServerError, err.Error())\n\t}\n\tdefer db.Close()\n}", "func (c *Config) UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tu := middleware.UserFromContext(ctx)\n\n\tvar payload updateUserPayload\n\tif err := bjson.ReadJSON(&payload, r); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif err := valid.Raw(&payload); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif payload.Password {\n\t\tif err := c.Mail.SendPasswordResetEmail(u,\n\t\t\tu.GetPasswordResetMagicLink(c.Magic)); err != nil {\n\t\t\tlog.Alarm(err)\n\t\t}\n\t}\n\n\tif payload.FirstName != \"\" && payload.FirstName != u.FirstName {\n\t\tu.FirstName = payload.FirstName\n\t}\n\n\tif payload.LastName != \"\" && payload.LastName != u.LastName {\n\t\tu.LastName = payload.LastName\n\t}\n\n\tif payload.SendDigest != nil {\n\t\tu.SendDigest = *payload.SendDigest\n\t}\n\n\tif payload.SendThreads != nil {\n\t\tu.SendThreads = *payload.SendThreads\n\t}\n\n\tif payload.SendEvents != nil {\n\t\tu.SendEvents = *payload.SendEvents\n\t}\n\n\tif err := c.UserStore.Commit(ctx, u); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tbjson.WriteJSON(w, u, http.StatusOK)\n}", "func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) {\n\tusr := new(User)\n\terr := request.ReadEntity(&usr)\n\tif err == nil {\n\t\tdb.WLock()\n\t\tdefer db.WUnlock() //unlock when exit this method\n\n\t\tif _, err = db.Engine.Id(usr.ID).Update(usr); err != nil {\n\t\t\tresponse.WriteHeaderAndEntity(http.StatusInternalServerError, UsersResponse{Error: err.Error()})\n\t\t} else {\n\t\t\tresponse.WriteEntity(UsersResponse{Success: true})\n\t\t}\n\t} else {\n\t\tresponse.WriteHeaderAndEntity(http.StatusInternalServerError, UsersResponse{Error: err.Error()})\n\t}\n}", "func UpdateUser(c *gin.Context) {\n\t// Get model if exist\n\tvar user models.User\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&user).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\t// Validate input\n\tvar input RequestUpdateUserInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tmodels.DB.Model(&user).Updates(input.User)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": user})\n}", "func UpdateUser(user *models.User, id string) (err error) {\n\tfmt.Println(user)\n\tconfig.DB.Save(user)\n\treturn nil\n}", "func (u *UserCtr) UpdateUser(c *gin.Context) {\n\tid,err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tvar newuser model.User\n\tc.BindJSON(&newuser)\n\tuser, err := model.UpdateUser(u.DB,id,newuser.Name,newuser.Email)\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": user,\n\t})\n\treturn\n}", "func UserUpdate(w http.ResponseWriter, r *http.Request, u *User) error {\n\t// set the name and email from the form data\n\tu.Name = r.FormValue(\"name\")\n\tu.SetEmail(r.FormValue(\"email\"))\n\n\tif err := u.Validate(); err != nil {\n\t\treturn RenderError(w, err, http.StatusBadRequest)\n\t}\n\tif err := database.SaveUser(u); err != nil {\n\t\treturn RenderError(w, err, http.StatusBadRequest)\n\t}\n\n\treturn RenderText(w, http.StatusText(http.StatusOK), http.StatusOK)\n}", "func UpdateUser(c *gin.Context) {\n\tuser, err := getUserFromParams(c)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif currentUser := c.Value(\"currentUser\").(models.User); currentUser.ID != user.ID {\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unable to update other users\"})\n\t\treturn\n\t}\n\n\tc.BindJSON(&user)\n\terr = repository.UpdateUser(&user, fmt.Sprint(user.ID))\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func (u *UserServiceHandler) Update(ctx context.Context, user *User) error {\n\n\turi := \"/v1/user/update\"\n\n\tvalues := url.Values{\n\t\t\"USERID\": {user.UserID},\n\t}\n\n\t// Optional\n\tif user.Email != \"\" {\n\t\tvalues.Add(\"email\", user.Email)\n\t}\n\tif user.Name != \"\" {\n\t\tvalues.Add(\"name\", user.Name)\n\t}\n\tif user.Password != \"\" {\n\t\tvalues.Add(\"password\", user.Password)\n\t}\n\tif user.APIEnabled != \"\" {\n\t\tvalues.Add(\"api_enabled\", user.APIEnabled)\n\t}\n\tif len(user.ACL) > 0 {\n\t\tfor _, acl := range user.ACL {\n\t\t\tvalues.Add(\"acls[]\", acl)\n\t\t}\n\t}\n\n\treq, err := u.client.NewRequest(ctx, http.MethodPost, uri, values)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = u.client.DoWithContext(ctx, req, nil)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func UpdateUser(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\t// Get model if exist\n\tvar user models.User\n\tif err := db.Where(\"id = ?\", c.Param(\"id\")).First(&user).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\t// Validate input\n\tvar input models.UpdateUserInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tdb.Model(&user).Updates(input)\n\tc.JSON(http.StatusOK, gin.H{\"data\": user})\n}", "func updateUser(user UserID, params map[string]interface{}, client *Client) error {\n\treturn client.Put(params, \"/access/users/\"+user.ToString())\n}", "func UpdateUser(c *gin.Context) {\n\tuserID, userErr := strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\tif userErr != nil {\n\t\terr := errors.NewBadRequestError(\"user id should be a number\")\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\t//intialize\n\tvar user users.User\n\t//check whether the given json body is valid or not\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tinvalidErr := errors.NewInternalServerError(\"invalid json body\")\n\t\tc.JSON(invalidErr.Status, invalidErr)\n\t\treturn\n\t}\n\n\t//send the user struct to the services\n\tuser.ID = userID\n\t//check whether the request method is PATCH and PUT\n\tisPartial := c.Request.Method == http.MethodPatch\n\n\tresult, err := services.UsersService.UpdateUser(isPartial, user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\t//final implementation\n\tc.JSON(http.StatusOK, result.Marshall(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func UpdateUser(ctx iris.Context) {\n\tvar (\n\t\tuser model.User\n\t\tnewUser model.User\n\t\tresult iris.Map\n\t)\n\tid := ctx.Params().Get(\"id\") // get id by params\n\tdb := config.GetDatabaseConnection()\n\tdefer db.Close()\n\terr := db.First(&user, id).Error\n\tif err != nil {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"true\",\n\t\t\t\"status\": iris.StatusBadRequest,\n\t\t\t\"message\": \"user not found\",\n\t\t\t\"result\": nil,\n\t\t}\n\t}\n\tctx.ReadJSON(&newUser)\n\terr = db.Model(&user).Updates(newUser).Error\n\tif err != nil {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"true\",\n\t\t\t\"status\": iris.StatusBadRequest,\n\t\t\t\"message\": \"error when update user\",\n\t\t\t\"result\": err.Error(),\n\t\t}\n\t} else {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"false\",\n\t\t\t\"status\": iris.StatusOK,\n\t\t\t\"message\": \"success update user\",\n\t\t\t\"result\": newUser,\n\t\t}\n\t}\n\tctx.JSON(result)\n\treturn\n}", "func UpdateUser(c *gin.Context) {\n\tvar user models.User\n\tid := c.Params.ByName(\"id\")\n\terr := models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, user)\n\t}\n\tc.BindJSON(&user)\n\terr = models.UpdateUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func (h *Handler) updateUser(c *gin.Context) handlerResponse {\n\n\tvar updatedUser types.User\n\tif err := c.ShouldBindJSON(&updatedUser); err != nil {\n\t\treturn handleBadRequest(err)\n\t}\n\tif updatedUser.Name != c.Param(userParameter) {\n\t\treturn handleNameMismatch()\n\t}\n\tstoredUser, err := h.service.User.Update(updatedUser, h.who(c))\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\t// Remove password so we do not show in response\n\tstoredUser.Password = \"\"\n\treturn handleOK(storedUser)\n}", "func UpdateUser(c *gin.Context) {\n\tid := c.Param(\"id\")\n\tlog.Printf(\"UpdateUser in db %v\", id)\n\tvar user models.User\n\n\tdb := db.GetDB()\n\tif err := db.Where(\"id = ?\", id).First(&user).Error; err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tlog.Println(\"Failed to UpdateUser in db\")\n\t\treturn\n\t}\n\tc.BindJSON(&user)\n\tdb.Save(&user)\n\tc.JSON(http.StatusOK, &user)\n}", "func UpdateUser(c *gin.Context) {\n\tuuid := c.Param(\"uuid\")\n\tvar user models.User\n\n\tdb := db.GetDB()\n\tif err := db.Where(\"uuid = ?\", uuid).First(&user).Error; err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\tdb.Where(\"uuid = ?\", uuid)\n\n\tif user.ID != 0 {\n\n\t\tjwtClaims := jwt.ExtractClaims(c)\n\t\tauthUserAccessLevel := jwtClaims[\"access_level\"].(float64)\n\t\tauthUserUUID := jwtClaims[\"uuid\"].(string)\n\t\tif authUserAccessLevel != 1 {\n\t\t\tif authUserUUID != uuid {\n\t\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\n\t\t\t\t\t\"error\": \"Sorry but you can't Update, ONLY admin user can\",\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvar newUser models.User\n\t\tc.Bind(&newUser)\n\n\t\tif newUser.FirstName != \"\" {\n\t\t\tuser.FirstName = newUser.FirstName\n\t\t}\n\n\t\tif newUser.LastName != \"\" {\n\t\t\tuser.LastName = newUser.LastName\n\t\t}\n\n\t\tif newUser.Email != \"\" {\n\t\t\tuser.Email = newUser.Email\n\t\t}\n\n\t\tif newUser.AccessLevel == 0 || newUser.AccessLevel == 1 {\n\t\t\tuser.AccessLevel = newUser.AccessLevel\n\t\t}\n\n\t\tif !newUser.DateOfBirth.IsZero() {\n\t\t\tuser.DateOfBirth = newUser.DateOfBirth\n\t\t}\n\n\t\t// Update multiple attributes with `struct`, will only update those changed\n\n\t\tif err := db.Save(&user); err != nil {\n\t\t\t// convert array of errors to JSON\n\t\t\terrs := err.GetErrors()\n\n\t\t\tif len(errs) > 0 {\n\t\t\t\tstrErrors := make([]string, len(errs))\n\t\t\t\tfor i, err := range errs {\n\t\t\t\t\tstrErrors[i] = err.Error()\n\t\t\t\t}\n\n\t\t\t\t// return errors\n\t\t\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{\n\t\t\t\t\t\"errors\": strErrors,\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Display modified data in JSON message \"success\"\n\t\tc.JSON(http.StatusOK, &user)\n\n\t}\n\n}", "func UpdateUser(res http.ResponseWriter, req *http.Request) {\n\tvar response responses.User\n\tuser := new(model.User)\n\tID := req.Context().Value(\"ID\").(string)\n\tdata := req.Context().Value(\"data\").(*validation.UpdateUser)\n\tnow := time.Now()\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\tcopier.Copy(&user, data)\n\tuser.UpdatedAt = now.Unix()\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\tresponse.ID = docKey\n\tcopier.Copy(&response, user)\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}", "func UpdateUser(c *gin.Context) {\n\tvar user Models.User\n\tid := c.Params.ByName(\"id\")\n\tfmt.Println(\"id\", id)\n\terr := Models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": \"Not Found\",\n\t\t}})\n\t\treturn\n\t} else {\n\tc.BindJSON(&user)\n\t\n\terr = Models.UpdateUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"data\":gin.H { \n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusBadRequest,\n\t\t\t\"message\": \"Can´t update user\",\n\t\t}}})\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}\n}", "func UpdateUser(c *gin.Context) {\n\tvar json db.UserUpdateForm\n\tif errs := c.ShouldBind(&json); errs != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"Form doesn't bind.\",\n\t\t\t\"err\": errs,\n\t\t})\n\t\treturn\n\t}\n\tuserID := sessions.Default(c).Get(\"userID\")\n\tvar user db.Users\n\tif err := db.DB.Unscoped().\n\t\tWhere(\"id = ?\", userID).\n\t\tFirst(&user).Error; err != nil {\n\t\t// User not found\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not found in database.\",\n\t\t\t\"err\": err,\n\t\t})\n\t\treturn\n\t}\n\tif checkPasswordHash(json.Password, user.Password) {\n\t\tvar newHash string\n\t\tif json.NewPass != \"\" {\n\t\t\tnewHash, _ = hashPassword(json.NewPass)\n\t\t} else {\n\t\t\tnewHash = user.Password\n\t\t}\n\n\t\tdb.DB.Model(&user).\n\t\t\tUpdates(map[string]interface{}{\n\t\t\t\t\"password\": newHash,\n\t\t\t\t\"email\": json.Email,\n\t\t\t}).\n\t\t\tWhere(\"id = ?\", userID)\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": user.Username,\n\t\t\t\"err\": \"\",\n\t\t})\n\t} else {\n\t\t// Old password doesn't match\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"msg\": fmt.Sprintf(\"Check password hash failed for user %s\", user.Username),\n\t\t\t\"err\": user.Username,\n\t\t})\n\t}\n}", "func (u *UsersAPI) UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\tuser, err := u.service.GetUser(id)\n\tif err != nil {\n\t\thandler.RespondError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&user); err != nil {\n\t\thandler.RespondError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tif err := u.service.UpdateUser(id, user); err != nil {\n\t\thandler.RespondError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\thandler.RespondJSON(w, http.StatusOK, user)\n}", "func UpdateUser(c *gin.Context) {}", "func (client *ShorelineClient) UpdateUser(userID string, userUpdate UserUpdate, token string) error {\n\thost := client.getHost()\n\tif host == nil {\n\t\treturn errors.New(\"No known user-api hosts.\")\n\t}\n\n\t//structure that the update are given to us in\n\ttype updatesToApply struct {\n\t\tUpdates UserUpdate `json:\"updates\"`\n\t}\n\n\thost.Path = path.Join(host.Path, \"user\", userID)\n\n\tif jsonUser, err := json.Marshal(updatesToApply{Updates: userUpdate}); err != nil {\n\t\treturn &status.StatusError{\n\t\t\tstatus.NewStatusf(http.StatusInternalServerError, \"Error getting user updates [%s]\", err.Error())}\n\t} else {\n\n\t\treq, _ := http.NewRequest(\"PUT\", host.String(), bytes.NewBuffer(jsonUser))\n\t\treq.Header.Add(\"x-tidepool-session-token\", token)\n\n\t\tres, err := client.httpClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failure to get a user\")\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tswitch res.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn &status.StatusError{\n\t\t\t\tstatus.NewStatusf(res.StatusCode, \"Unknown response code from service[%s]\", req.URL)}\n\t\t}\n\t}\n}", "func (u *User) UpdateUser(db *sql.DB) error {\n\tstatement := fmt.Sprintf(\"UPDATE users SET name='%s', age=%d WHERE id=%d\", u.Name, u.Age, u.ID)\n\t_, err := db.Exec(statement)\n\treturn err\n}", "func Update(c *gin.Context) {\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\tvar user models.User\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := rest_errors.NewBadRequestError(\"invalid json body\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\n\tuser.Id = userId\n\n\tisPartial := c.Request.Method == http.MethodPatch\n\n\tresult, err := services.UsersService.UpdateUser(isPartial, user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, result.Marshal(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func UpdateUser(c *gin.Context) {\n\tif userCollection == nil {\n\t\tuserCollection = db.GetUserCollection()\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tid, _ := primitive.ObjectIDFromHex(c.Param(\"id\"))\n\n\tvar userInfo entity.User\n\tif err := c.ShouldBindJSON(&userInfo); err != nil {\n\t\tc.AbortWithStatusJSON(400, gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\n\tresult, err := userCollection.UpdateOne(ctx, entity.User{ID: id}, bson.M{\"$set\": userInfo})\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(500, gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"Result\": result})\n}", "func (user *User) UpdateUser(id int) error {\n\n\t_, err := db.Model(user).Where(\"id = ?\", id).Returning(\"*\").UpdateNotZero()\n\treturn err\n}", "func UpdateUser(c echo.Context) error {\n\tnu := &models.User{}\n\tif err := c.Bind(nu); err != nil {\n\t\treturn err\n\t}\n\n\tid, _ := strconv.Atoi(c.Param(\"id\"))\n\tusers[id].Name = nu.Name\n\tusers[id].Email = nu.Email\n\n\treturn c.JSON(http.StatusOK, users[id])\n}", "func (arg Users) UpdateUser(ctx context.Context) error {\n\tdb, err := DBInit()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = db.ExecContext(ctx, updateUser,\n\t\targ.ID,\n\t\targ.Name,\n\t\targ.Role,\n\t)\n\treturn err\n}", "func (a *UserApiService) UpdateUser(ctx context.Context, username string) UserApiUpdateUserRequest {\n\treturn UserApiUpdateUserRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tusername: username,\n\t}\n}", "func UpdateUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tuser := models.AppUser{}\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(&user); err != nil {\n\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{models.AppUser{}, \"Error petición mal estructurada\"})\n\t\treturn\n\t}\n\tuserTemp := getUserOrNull(db, user.AppUserID, w, r)\n\tif userTemp == nil {\n\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{Message: \"Error el usuario no existe\"})\n\t\treturn\n\t}\n\tif userTemp.CompanyID != user.CompanyID {\n\t\trespondJSON(w, http.StatusBadRequest, JSONResponse{Message: \"Este usuario no pertenece a su organización\"})\n\t\treturn\n\t}\n\tif err := db.Model(&user).Where(\"company_id = ?\", user.CompanyID).Omit(\"AppUserID\", \"CompanyID\", \"AppUserCreationDate\", \"AppUserPassword\").Save(user).Error; err != nil {\n\t\trespondJSON(w, http.StatusInternalServerError, JSONResponse{Message: \"Error interno del servidor\"})\n\t\treturn\n\t}\n\trespondJSON(w, http.StatusOK, JSONResponse{user, \"Actualización realizada!\"})\n}", "func Update(user User) error {\n\n}", "func (s *server) UpdateUser(ctx context.Context, in *pb.UserRequest) (*pb.UserResponse, error) {\n\tlog.Printf(\"Received: %v\", \"Update user\")\n\thash, salt := hash(in.HashPassword)\n\t// if user exist we update\n\temail, pass, salt, err := updateUser(in.Email, hash, salt)\n\n\tpass = pass\n\tsalt = salt\n\tif err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Can't create or update.\")\n\t}\n\ttoken := GenerateSecureToken(32)\n\tis, err := CreateSession(email, token)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, \"database problem\")\n\t}\n\n\treturn &pb.UserResponse{IsUser: is, Token: token}, nil\n}", "func (cli *OpsGenieUserV2Client) Update(req userv2.UpdateUserRequest) (*userv2.UpdateUserResponse, error) {\n\tvar response userv2.UpdateUserResponse\n\terr := cli.sendPatchRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (s *UserRepository) UpdateUser(u *akwad.Account) error {\n\n\treturn nil\n}", "func UpdateUser(user *User) error {\n\tif user == nil {\n\t\treturn errors.New(\"user can not be nil\")\n\t}\n\tif user.Username == \"\" {\n\t\treturn errors.New(\"user.username is empty\")\n\t}\n\n\targs := bson.M{}\n\tif user.Password != \"\" {\n\t\targs[\"password\"] = user.Password\n\t}\n\tif user.Role > 0 {\n\t\targs[\"role\"] = user.Role\n\t}\n\tif user.Status > 0 {\n\t\targs[\"status\"] = user.Status\n\t}\n\tif user.Icon != \"\" {\n\t\targs[\"icon\"] = user.Icon\n\t}\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\targs[\"update\"] = tools.NowMillisecond()\n\t_, err := C(CollectionUser).FindId(user.Username).Apply(mgo.Change{\n\t\tUpdate: bson.M{\"$set\": args},\n\t\tReturnNew: true,\n\t}, user)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"username\": user.Username,\n\t\t\t\"set\": goutil.Struct2Json(args),\n\t\t\t\"err\": err,\n\t\t}).Error(\"UpdateUser update user info err\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *User) Update(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\t// @todo we might want extra check that /users/id equals to user.ID received in body\n\tuser, err := validator.UserCreate(body)\n\tif err != nil || user.ID == 0 {\n\t\tlog.Println(err)\n\t\tR.JSON400(w)\n\t\treturn\n\t}\n\n\terr = h.Storage.UpdateUser(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tR.JSON200OK(w)\n}", "func (s *Store) UpdateUser(name, password string) error {\n\t// Hash the password before serializing it.\n\thash, err := HashPassword(password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serialize command and send it to the leader.\n\treturn s.exec(internal.Command_UpdateUserCommand, internal.E_UpdateUserCommand_Command,\n\t\t&internal.UpdateUserCommand{\n\t\t\tName: proto.String(name),\n\t\t\tHash: proto.String(string(hash)),\n\t\t},\n\t)\n}", "func UpdateUser(c echo.Context) error {\n\tid := c.FormValue(\"id\")\n\tusername := c.FormValue(\"username\")\n\temail := c.FormValue(\"email\")\n\troles := c.FormValue(\"roles\")\n\n\tconvID, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\tconvRoles, err := strconv.Atoi(roles)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\tresult, err := models.UpdateUser(convID, username, email, convRoles)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn c.JSON(http.StatusOK, result)\n}", "func (c CvpRestAPI) UpdateUser(user string, userObj *SingleUser) error {\n\tparam := &url.Values{\"userId\": {user}}\n\tresp, err := c.client.Post(\"/user/updateUser.do\", param, userObj)\n\tif err != nil {\n\t\treturn errors.Errorf(\"UpdateUser: %v\", err)\n\t}\n\tvar msg struct {\n\t\tResponseMessage string `json:\"data\"`\n\t\tErrorResponse\n\t}\n\tif err = json.Unmarshal(resp, &msg); err != nil {\n\t\treturn errors.Errorf(\"UpdateUsers: JSON unmarshal error: \\n%v\", err)\n\t}\n\tvar retErr error\n\tif err = msg.Error(); err != nil {\n\t\tif msg.ErrorCode == SUPERUSER_EDIT_ATTEMPT {\n\t\t\tretErr = errors.Errorf(\"UpdateUsers: can not edit super user '%s'\", defaultUser)\n\t\t} else {\n\t\t\tretErr = errors.Errorf(\"UpdateUsers: %v\", err)\n\t\t}\n\t} else {\n\t\tlowerCaseResp := strings.ToLower(msg.ResponseMessage)\n\t\tif !strings.Contains(lowerCaseResp, successMsg) {\n\t\t\tretErr = errors.New(\"UpdateUsers: Successful updation response not found\")\n\t\t}\n\t}\n\treturn retErr\n}", "func Update(c *gin.Context) {\n\tuserID, err := getUserID(c.Param(\"user_id\"))\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tvar newUser users.User\n\tif err := c.ShouldBindJSON(&newUser); err != nil {\n\t\tbdErr := errors.NewBadRequestError(fmt.Sprintf(\"invalid json body %s\", err.Error()))\n\t\tc.JSON(bdErr.Status, bdErr)\n\t\treturn\n\t}\n\n\tnewUser.ID = userID\n\tisPartial := c.Request.Method == http.MethodPatch\n\n\tresult, updateErr := services.UserServ.UpdateUser(newUser, isPartial)\n\tif err != nil {\n\t\tc.JSON(updateErr.Status, updateErr)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusOK, result.Marshall(isPublic))\n}", "func UpdateUser(data interface{}, token string) error {\n\t// declarations\n\tvalues := makeStringMap(data)\n\tuser := User{\n\t\tGH_Id: makeInt64(values[\"id\"]),\n\t\tUser_name: makeString(values[\"login\"]),\n\t\tReal_name: makeString(values[\"name\"]),\n\t\tEmail: makeString(values[\"email\"]),\n\t\tToken: token,\n\t\tWorker_token: nonExistingRandString(Token_length,\n\t\t\t\"SELECT 42 FROM users WHERE worker_token = $1\"),\n\t\tAdmin: false,\n\t}\n\n\t// update user information\n\tif existsUser(user.GH_Id) {\n\t\tupdateUser(&user)\n\t} else {\n\t\tcreateUser(&user)\n\t}\n\n\treturn nil\n}", "func (server Server) UpdateUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) // mux params\n\tid, err := strconv.Atoi(vars[\"id\"]) // convert the id type from string to int\n\tvar res models.APIResponse // make a response\n\tvar user models.User // make a user\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to convert the string into an int. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to convert the string into an int.\", nil)\n\t} else {\n\t\terr = json.NewDecoder(r.Body).Decode(&user) // decode the json request to note\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to decode the request body. %v\", err)\n\t\t\tres = models.BuildAPIResponseFail(\"Unable to decode the request body.\", nil)\n\t\t} else {\n\t\t\tupdatedRows := updateUser(int64(id), user, server.db) // call update note to update the note\n\t\t\tres = models.BuildAPIResponseSuccess(\"User updated successfully.\", updatedRows)\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(res) // send the response\n}", "func UpdateUser(c *gin.Context) {\n\tvar user, data, condition Users\n\n\tuserID, _ := strconv.ParseUint(c.Param(\"id\"), 10, 64)\n\tcondition.ID = uint(userID)\n\tuser.FindOne(condition)\n\n\tif err := c.BindJSON(&data); err == nil {\n\t\treturnMessage := user.Update(data)\n\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": returnMessage.Status,\n\t\t\t\"message\": returnMessage.Description,\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"message\": err.Error(),\n\t\t})\n\t}\n}", "func (h *auth) Update(c echo.Context) error {\n\t// Filter params\n\tvar params service.UpdateUserParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"Could not get parameters.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tservice := service.NewUser(h.db, h.sessions, params.APIVersion)\n\tupdate, err := service.Update(currentUser(c), params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.JSON(http.StatusOK, update)\n}", "func (e Endpoints) UpdateUser(ctx context.Context, token string, user registry.User) (err error) {\n\trequest := UpdateUserRequest{\n\t\tToken: token,\n\t\tUser: user,\n\t}\n\tresponse, err := e.UpdateUserEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(UpdateUserResponse).Err\n}", "func UpdateUser(db *sql.DB, user *models.UserResponse) (int, error) {\n\t_, err := db.Exec(\"UPDATE users SET username = ?, email = ? WHERE id = ?\", user.Username, user.Email, user.ID)\n\tif err != nil {\n\t\tlog.Errorf(\"Error inserting\")\n\t\tlog.Error(err)\n\t\treturn 0, err\n\t}\n\treturn user.ID, nil\n}", "func (c APIClient) UpdateUser(user *User) error {\n\treturn c.doHTTPBoth(\"POST\", fmt.Sprintf(\"https://api.nsone.net/v1/account/users/%s\", user.Username), user)\n}", "func (u *User) Update() *errorsutils.RestErr {\n\tstmt, err := usersdb.Client.Prepare(queryUpdateUser)\n\tif err != nil {\n\t\tlogger.Error(\"error when trying to prepare update user statement\", err)\n\t\treturn errorsutils.NewInternalServerError(\"database error\", errors.New(\"database error\"))\n\t}\n\tdefer stmt.Close()\n\n\tif _, err = stmt.Exec(u.FirstName, u.LastName, u.Email, u.ID); err != nil {\n\t\tlogger.Error(\"error when trying to update user\", err)\n\t\treturn errorsutils.NewInternalServerError(\"database error\", errors.New(\"database error\"))\n\t}\n\n\treturn nil\n}", "func (s *Mortgageplatform) UpdateUser(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n\terr := updateUser(APIstub,args)\n\tif err != nil { return shim.Error(err.Error()) }\n\treturn shim.Success(nil)\n}", "func (a *Users) Update(w http.ResponseWriter, r *http.Request) {\n\tid := getUserID(r)\n\ta.l.Println(\"[DEBUG] get record id\", id)\n\n\t// fetch the user from the context\n\tacc := r.Context().Value(KeyUser{}).(*models.User)\n\tacc.ID = id\n\ta.l.Println(\"[DEBUG] updating user with id\", acc.ID)\n\n\terr := models.UpdateUser(acc)\n\n\tif err == models.ErrUserNotFound {\n\t\ta.l.Println(\"[ERROR] user not found\", err)\n\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tmodels.ToJSON(&GenericError{Message: \"User not found in database\"}, w)\n\t\treturn\n\t}\n\n\t// write the no content success header\n\tw.WriteHeader(http.StatusNoContent)\n}", "func UpdateUser(db *sql.DB, id string, display sql.NullString, passwdHash string) {\n\tbuilder := sqlbuilder.NewUpdateBuilder()\n\tsql, args :=\n\t\tbuilder.Update(\"users\").Where(builder.Equal(\"id\", id)).Set(\n\t\t\tbuilder.Assign(\"display\", display),\n\t\t\tbuilder.Assign(\"passwd\", passwdHash),\n\t\t).Build()\n\n\t_, err := db.Query(sql, args...)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (userRepository UserRepository) Update(userId uint64, user models.User) error {\n\tstatement, err := userRepository.db.Prepare(\n\t\t\"update users set name = ?, nick = ?, email = ? where id = ?\",\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tif _, err = statement.Exec(user.Name, user.Nick, user.Email, userId); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\n\t// w.Header().Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t// w.Header().Set(\"Access-Control-Allow-Methods\", \"PUT\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\t// get the userid from the request params, key is \"id\"\n\tparams := mux.Vars(r)\n\n\t// convert the id type from string to int\n\tid, err := strconv.Atoi(params[\"id\"])\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to convert the string into int. %v\", err)\n\t}\n\n\t// create an empty user of type models.User\n\tvar user TempUsers\n\n\t// decode the json request to user\n\terr = json.NewDecoder(r.Body).Decode(&user)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to decode the request body. %v\", err)\n\t}\n\n\tdb := createConnection()\n\t// close the db connection\n\tdefer db.Close()\n\n\t// create the update sql query\n\tsqlStatement := `UPDATE users SET full_name=$2, email=$3, mobile_no=$4, username=$5, passwd=$6, created_at=$7 WHERE userid=$1`\n\n\t// execute the sql statement\n\tres, err := db.Exec(sqlStatement, id, user.FullName, user.Email, user.MobileNo, user.UserName, user.Password, time.Now())\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to execute the query. %v\", err)\n\t}\n\n\t// check how many rows affected\n\trowsAffected, err := res.RowsAffected()\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while checking the affected rows. %v\", err)\n\t}\n\n\tif rowsAffected > 0 {\n\t\tmsg := map[string]string{\"msg\": \"Updated Successfully.\"}\n\t\tjson.NewEncoder(w).Encode(msg)\n\t} else {\n\t\tmsg := map[string]string{\"msg\": \"Unable to Update, ID does not exists.\"}\n\t\tjson.NewEncoder(w).Encode(msg)\n\t}\n}", "func (us *usersService) UpdateUser(u *users.User) *errors.RestError {\n\tvar err *errors.RestError\n\tif err = u.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = u.Update(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (db Database) UpdateUser(user *User) (err error) {\n\t// Connect to database\n\tconnection, err := sql.Open(\"postgres\", db.getDBConnectionString())\n\tif err != nil {\n\t\tdefer connection.Close()\n\t\treturn\n\t}\n\n\t// Update user in database\n\t_, err = connection.Exec(`\n\tUPDATE \"Users\"\n\tSET \"ExpiresAt\" = $1,\n\t\t\"ExpiresIn\" = $2,\n\t\t\"AccessToken\" = $3,\n\t\t\"RefreshToken\" = $4,\n\t\t\"IsHistoryFetched\" = $5\n\tWHERE \"UserIdentifier\" = $6;\n\t`, &user.ExpiresAt, &user.ExpiresIn, &user.AccessToken, &user.RefreshToken, &user.IsHistoryFetched, &user.UserIdentifier)\n\n\tdefer connection.Close()\n\treturn\n}", "func UpdateUser(userId int64, userData *UserEntry) error {\n _ , nerr := model.Database.Exec(\"UPDATE users SET username = ?, isadmin = ?, email = ? WHERE userid = ?\", userData.Username, userData.IsAdmin, userData.Email, userId)\n if nerr != nil {\n return nerr\n }\n return nil\n}", "func (a *AdminAPI) UpdateUser(ctx context.Context, username, password, mechanism string) error {\n\tif username == \"\" {\n\t\treturn errors.New(\"invalid empty username\")\n\t}\n\tif password == \"\" {\n\t\treturn errors.New(\"invalid empty password\")\n\t}\n\n\tif mechanism != ScramSha256 && mechanism != ScramSha512 {\n\t\treturn fmt.Errorf(\"invalid mechanism, should either %q or %q\", ScramSha256, ScramSha512)\n\t}\n\tu := newUser{\n\t\tPassword: password,\n\t\tAlgorithm: mechanism,\n\t}\n\t// This is because the api endpoint is userEndpoint/{user}.\n\tpath := usersEndpoint + \"/\" + url.PathEscape(username)\n\treturn a.sendToLeader(ctx, http.MethodPut, path, u, nil)\n}", "func UpdateUser(u *User) error {\n\treturn db.Save(u).Error\n}", "func (c *Client) UpdateUser(user *User) (updatedUser *User, err error) {\n\n\t// Basic requirements\n\tif user.ID == 0 {\n\t\terr = c.createError(fmt.Sprintf(\"missing required attribute: %s\", fieldID), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Permit fields before updating\n\tuser.permitFields()\n\n\t// Fire the Request\n\tvar response string\n\tif response, err = c.Request(modelUser, http.MethodPut, user); err != nil {\n\t\treturn\n\t}\n\n\t// Only a 200 is treated as a success\n\tif err = c.Error(http.StatusOK, response); err != nil {\n\t\treturn\n\t}\n\n\t// Convert model response\n\tif err = json.Unmarshal([]byte(response), &updatedUser); err != nil {\n\t\terr = c.createError(fmt.Sprintf(\"failed unmarshaling data: %s\", \"user\"), http.StatusExpectationFailed)\n\t}\n\treturn\n}", "func HandleUserUpdate(c *gin.Context) {\n\tuid := c.Param(\"uid\")\n\tvar u User\n\tu.Username = c.DefaultPostForm(\"username\", \"\")\n\tu.Password = c.DefaultPostForm(\"password\", \"\")\n\tu.Nickname = c.DefaultPostForm(\"nickname\", \"\")\n\n\tuser, err := u.Update(uid)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"code\": 1,\n\t\t\t\"msg\": err.Error(),\n\t\t\t\"data\": gin.H{},\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"code\": 0,\n\t\t\"msg\": \"ok\",\n\t\t\"data\": user,\n\t})\n}", "func (s *service) UpdateUser(ctx context.Context, user model.User, optimisticLock bool) error {\n\tlog.Trace(\"userservice.UpdateUser(%v) called\", user)\n\n\terr := s.repository.UpdateUser(ctx, user, optimisticLock)\n\tif err != nil {\n\t\tlog.Errorf(\"UpdateUser error: %v\", err)\n\t}\n\treturn s.errTranslator(err)\n}", "func (c *APIClient) UpdateUser(ctx _context.Context, id int32) apiUpdateUserRequest {\n\treturn apiUpdateUserRequest{\n\t\tclient: c,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func (w *ServerInterfaceWrapper) UpdateUser(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"id\" -------------\n\tvar id int\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"id\", ctx.Param(\"id\"), &id)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter id: %s\", err))\n\t}\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.UpdateUser(ctx, id)\n\treturn err\n}", "func (client IdentityClient) updateUser(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPut, \"/users/{userId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response UpdateUserResponse\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 (b *ServerBackend) UpdateUser(nUser *NewUser) {\n\tuser := b.GetUser(nUser.Id)\n\tif user == nil {\n\t\treturn\n\t}\n\n\tif user.Name == nUser.Name {\n\t\treturn\n\t}\n\n\tupdate := fromilyclient.User{\n\t\tId: user.Id,\n\t\tName: nUser.Name,\n\t}\n\terr := b.Client.UpdateUser(&update)\n\tif err != nil {\n\t\tuser.Name = nUser.Name\n\t}\n}", "func (a *Client) UserUpdate(params *UserUpdateParams) (*UserUpdateOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUserUpdateParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"User.update\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/user\",\n\t\tProducesMediaTypes: []string{\"application/javascript\", \"application/xml\", \"text/javascript\", \"text/xml\"},\n\t\tConsumesMediaTypes: []string{\"application/x-www-form-urlencoded\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &UserUpdateReader{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.(*UserUpdateOK), nil\n\n}", "func updateUser(user *User) {\n\tvar dummy string\n\n\t// update user information\n\tdb.QueryRow(\"UPDATE users SET username=$1, realname=$2, email=$3, token=$4\"+\n\t\t\" WHERE gh_id=$5\", user.User_name, user.Real_name, user.Email,\n\t\tuser.Token, user.GH_Id).Scan(&dummy)\n}", "func (f *Factory) UpdateUser(id string,firstname string, lastname string, age int) * domain.User {\n\treturn &domain.User{\n\t\tID:\t\t\tid,\t\t\n\t\tFirstname: firstname,\n\t\tLastname: lastname,\n\t\tAge: age,\n\t}\n\n}", "func (s *Server) PostUpdateUser(w rest.ResponseWriter, r *rest.Request) {\n\tresponse := models.BaseResponse{}\n\tresponse.Init(w)\n\n\tcurrentUser, err := s.LoginProcess(response, r)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tuser := models.User{}\n\tr.DecodeJsonPayload(&user)\n\n\tif user.ID != currentUser.ID {\n\t\tresponse.SendError(ErrorUnauthorizedAction)\n\t\treturn\n\t}\n\n\tcurrentUser.Avatar = user.Avatar\n\tcurrentUser.Name = user.Name\n\n\tif err = currentUser.Update(s.Db); err != nil {\n\t\tresponse.SendError(err.Error())\n\t\treturn\n\t}\n\n\tcurrentUser.IsReturning = true\n\n\tresponse.SendSuccess(currentUser)\n}", "func (u User) Update(ctx context.Context, user model.User) error {\n\tspan, _ := jtrace.Tracer.SpanFromContext(ctx, \"get user model\")\n\tdefer span.Finish()\n\tspan.SetTag(\"model\", fmt.Sprintf(\"update user with id: %d\", user.ID))\n\n\ttx := mysql.Storage.GetDatabase().Begin()\n\n\tusr, err := u.Get(ctx, \"users\", \"username = ?\", user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update usr fileds\n\tusr.Name = user.Name\n\tusr.LastName = user.LastName\n\tusr.Phone = user.Phone\n\tusr.Email = user.Email\n\tusr.BirthDate = user.BirthDate\n\tusr.Gender = user.Gender\n\tusr.RoleID = user.RoleID\n\n\tif err := tx.Table(\"users\").Where(\"username = ?\", user.Username).Select(\"*\").Updates(&usr).Error; err != nil {\n\t\tlog := logger.GetZapLogger(false)\n\t\tlogger.Prepare(log).\n\t\t\tAppend(zap.Any(\"error\", fmt.Sprintf(\"update user error: %s\", err))).\n\t\t\tLevel(zap.ErrorLevel).\n\t\t\tDevelopment().\n\t\t\tCommit(\"env\")\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\n\treturn nil\n}", "func UpdateUser(ex db.Execer, u User) error {\n\treturn u.Update(ex)\n}", "func updateUser(w http.ResponseWriter, r *http.Request) {\r\n\tparams := mux.Vars(r)\r\n\tstmt, err := db.Prepare(\"UPDATE users SET name = ? WHERE id = ?\")\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tbody, err := ioutil.ReadAll(r.Body)\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tkeyVal := make(map[string]string)\r\n\tjson.Unmarshal(body, &keyVal)\r\n\tnewName := keyVal[\"name\"]\r\n\t_, err = stmt.Exec(newName, params[\"id\"])\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tfmt.Fprintf(w, \"User with id = %s was updated\", params[\"id\"])\r\n}", "func (h *User) UpdateUser(c echo.Context) error {\n\tuuid := c.Param(\"uuid\")\n\tname := c.FormValue(\"name\")\n\taddress := c.FormValue(\"address\")\n\tctx := c.Request().Context()\n\n\tuser, err := h.Usecase.UpdateUser(ctx, uuid, name, address)\n\tif err != nil {\n\t\tresult := response.UserBody{\n\t\t\tMessage: \"FAILED\",\n\t\t\tData: nil,\n\t\t\tError: &response.Error{\n\t\t\t\tMessage: err.Error(),\n\t\t\t},\n\t\t}\n\t\treturn c.JSON(helpers.GetStatusCode(err), result)\n\t}\n\n\tresult := response.UserBody{\n\t\tMessage: \"SUCCESS\",\n\t\tData: h.transformUser(&user),\n\t\tError: nil,\n\t}\n\n\treturn c.JSON(http.StatusOK, result)\n}", "func (s *UserService) UpdateUser(user *spotify.PrivateUser, token *oauth2.Token) (*models.User, error) {\n\n\tregisteredUser := &models.User{}\n\t\n\t//check if user or email is registered\n\ts.DB.Where(&models.User{\n\t\tSpotifyID: user.ID, \n\t\tEmail: user.Email}).First(registeredUser)\n\n\tif (models.User{}) == *registeredUser {\n\t\tuserinfo := fmt.Sprintf(\"No User found with SpotifyId: %s and SpotifyEmail: %s\", user.ID, user.Email)\n\t\terr:= errors.New(userinfo)\n\t\treturn nil,err\n\t}\t\n\n\tregisteredUser.SpotifyToken=token.AccessToken\n\tregisteredUser.SpotifyRefreshToken=token.RefreshToken\n\tregisteredUser.SpotifyTokenType=token.TokenType\n\tregisteredUser.SpotifyTokenExpiry=strconv.FormatInt(token.Expiry.Unix(), 10)\n\ts.DB.Save(registeredUser)\n\t\t\n\treturn registeredUser, nil\n}", "func (client *Client) UpdateUser(userID string, password string, roles []string, domains []string) (string, error) {\n\tuserData := UserData{\n\t\tID: userID,\n\t\tCredential: password,\n\t\tRoles: strings.Join(roles, \",\"),\n\t\tDomainName: strings.Join(domains, \",\"),\n\t}\n\tuserDataJSON, err := json.Marshal(userData)\n\n\tresRaw, err := client.UpdateClient(userDataJSON)\n\treturn string(resRaw), err\n}", "func (m User) UpdateUser() error {\n\tc := newUserCollection()\n\tdefer c.Close()\n\n\terr := c.Session.Update(bson.M{\n\t\t\"_id\": m.ID,\n\t}, bson.M{\n\t\t\"$set\": bson.M{\n\t\t\t\"username\": m.Username, \"birth\": m.Birth, \"updatedAt\": time.Now()},\n\t})\n\treturn err\n}", "func UpdateUser(c echo.Context) (err error) {\n\tuserIDParam := c.Param(\"id\")\n\tvar m models.ResponseMessage\n\n\tuserID, err := utils.Atoi(userIDParam)\n\tif err != nil || userID == 0 {\n\t\tm.Error = fmt.Sprintf(\"%v: id\", errs.ErrInvalidParam)\n\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, m)\n\t}\n\n\tvar user models.User\n\n\tif err = c.Bind(&user); err != nil {\n\t\tm.Error = errs.ErrInvalidBody\n\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, m)\n\t}\n\n\tdbuserI, err := helpers.ParseModelToDBModel(user)\n\tif err != nil {\n\t\tc.Logger().Error(err)\n\n\t\treturn echo.ErrInternalServerError\n\t}\n\n\tdbUser := dbuserI.(dbm.User)\n\n\tdb, err := database.Get()\n\tif err != nil {\n\t\tc.Logger().Error(err)\n\n\t\treturn echo.ErrInternalServerError\n\t}\n\n\terr = dbu.UpdateUser(\n\t\tdb,\n\t\tdbm.User{\n\t\t\tID: int64(userID),\n\t\t},\n\t\tdbUser,\n\t)\n\tif err != nil {\n\t\tif errors.Is(err, errs.ErrNotExistentObject) {\n\t\t\tm.Error = fmt.Sprintf(\"%v: user\", errs.ErrExistentObject)\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, m)\n\t\t}\n\t\tc.Logger().Error(err)\n\n\t\treturn echo.ErrInternalServerError\n\t}\n\n\tm.Message = \"Updated.\"\n\n\treturn c.JSON(http.StatusOK, m)\n}", "func (u *usecase) Update(ctx context.Context, id string, user *UpdateUser) error {\n\tvalidate = validator.New()\n\tif err := validate.Struct(user); err != nil {\n\t\tvalidationErrors := err.(validator.ValidationErrors)\n\t\treturn validationErrors\n\t}\n\n\tif err := u.repository.Update(ctx, id, user); err != nil {\n\t\treturn errors.Wrap(err, \"error updating user\")\n\t}\n\treturn nil\n}", "func UserUpdate(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 url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := auth.GetUserFromJSON(body)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"User\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Get Result Object\n\tuserUUID := auth.GetUUIDByName(urlUser, refStr)\n\tmodified := time.Now().UTC()\n\tres, err := auth.UpdateUser(userUUID, postBody.FirstName, postBody.LastName, postBody.Organization, postBody.Description,\n\t\tpostBody.Name, postBody.Projects, postBody.Email, postBody.ServiceRoles, modified, true, refStr)\n\n\tif err != nil {\n\n\t\t// In case of invalid project or role in post body\n\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"invalid\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"duplicate\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\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 (us *UserService) Update(ctx context.Context, user resources.User,\n\tblueprint blueprint.Interface, updateType UpdateType) (*resources.User, error) {\n\tuserID, err := user.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblueprintText, err := blueprint.Render()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresArr, err := us.call(ctx, \"one.user.update\", userID, blueprintText, updateType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn us.RetrieveInfo(ctx, int(resArr[resultIndex].ResultInt()))\n}", "func (user *User) Update() *errors.RestErr {\n\tstmt, err := usersdb.Client.Prepare(queryUdpdateUser)\n\tif err != nil {\n\t\treturn errors.NewInternalServerError(err.Error())\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(user.FirstName, user.LastName, user.Email, user.ID)\n\tif err != nil {\n\t\treturn errors.ParseError(err)\n\n\t}\n\treturn nil\n\n}", "func UpdateUser(db *pg.DB, u *models.User) error {\n\n\t// Load experiences\n\texps, err := ListUserExperiences(db, u.UserName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\texps = []*models.Experience{}\n\t}\n\n\t// Reset points\n\tfor _, v := range u.Streams {\n\t\tv.LearningTargets[u.LearnerProfile.CurrentYear][1] = 0\n\t}\n\n\t// Update points based on experiences\n\tfor _, ex := range exps {\n\t\tfor k, v := range u.Streams {\n\t\t\tif ex.Stream.Name == k {\n\t\t\t\tv.LearningTargets[u.LearnerProfile.CurrentYear][1] += ex.Points\n\t\t\t}\n\t\t}\n\t}\n\n\tif u.Language == \"\" {\n\t\tu.Language = \"en-ca\"\n\t}\n\n\tif u.Role == \"\" {\n\t\tu.Role = \"user\"\n\t}\n\n\tif u.IsAdmin {\n\t\tu.Role = \"admin\"\n\t}\n\n\t// Update user\n\terr = db.Update(u)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn err\n}", "func (s *UserService) UpdateUser(p *UpdateUserParams) (*UpdateUserResponse, error) {\n\tresp, err := s.cs.newRequest(\"updateUser\", p.toURLValues())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r UpdateUserResponse\n\tif err := json.Unmarshal(resp, &r); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &r, nil\n}", "func (service *ContrailService) UpdateUser(\n\tctx context.Context,\n\trequest *models.UpdateUserRequest) (*models.UpdateUserResponse, error) {\n\tmodel := request.User\n\tif model == nil {\n\t\treturn nil, common.ErrorBadRequest(\"Update body is empty\")\n\t}\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\treturn db.UpdateUser(ctx, tx, request)\n\t\t}); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"resource\": \"user\",\n\t\t}).Debug(\"db update failed\")\n\t\treturn nil, common.ErrorInternal\n\t}\n\treturn &models.UpdateUserResponse{\n\t\tUser: model,\n\t}, nil\n}", "func (u *User) UpdateUser(ctx context.Context, inUser *pb.User, resp *pb.Response) error {\n\t_ = ctx\n\n\toutUser := &pb.User{}\n\tif errVal := u.BeforeUpdateUser(ctx, inUser, &pb.ValidationErr{}); errVal != nil {\n\t\treturn errVal\n\t}\n\n\tsqlStatement := statements.SqlUpdate.String()\n\n\tconvertedDates, err := globalUtils.TimeStampPPBToTime(inUser.GetValidFrom(), inUser.GetValidThru())\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalidFrom, validThru := convertedDates[0], convertedDates[1]\n\n\tvar createDate time.Time\n\tupdateDate := time.Now()\n\tfmt.Printf(\"updatedate: %v\\n\", updateDate)\n\n\terr = conn.QueryRow(context.Background(), sqlStatement,\n\t\tinUser.GetFirstname(),\n\t\tinUser.GetLastname(),\n\t\tvalidFrom,\n\t\tvalidThru,\n\t\tinUser.GetActive(),\n\t\tinUser.GetPwd(),\n\t\tinUser.GetEmail(),\n\t\tinUser.GetCompany(),\n\t\tupdateDate,\n\t\tinUser.GetId(),\n\t).Scan(\n\t\t&outUser.Id,\n\t\t&outUser.Firstname,\n\t\t&outUser.Lastname,\n\t\t&validFrom,\n\t\t&validThru,\n\t\t&outUser.Active,\n\t\t&outUser.Pwd,\n\t\t&outUser.Name,\n\t\t&outUser.Email,\n\t\t&outUser.Company,\n\t\t&createDate,\n\t\t&updateDate,\n\t)\n\tif err != nil {\n\t\tlog.Printf(userErr.UpdateError(err))\n\t\treturn err\n\t}\n\n\tconvertedTimes, err := globalUtils.TimeToTimeStampPPB(validFrom, validThru, createDate, updateDate)\n\tif err != nil {\n\t\treturn err\n\t}\n\toutUser.ValidFrom, outUser.ValidThru = convertedTimes[0], convertedTimes[1]\n\toutUser.Createdate, outUser.Updatedate = convertedTimes[2], convertedTimes[3]\n\n\tresp.User = outUser\n\tfailureDesc, err := u.getAfterAlerts(ctx, outUser, \"AfterUpdateUser\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp.ValidationErr = &pb.ValidationErr{FailureDesc: failureDesc}\n\n\treturn nil\n}", "func (u *User) Update(data string) (*User, error) {\n\tlog.info(\"========== UPDATE USER ==========\")\n\turl := buildURL(path[\"users\"], u.UserID)\n\n\tres, err := u.do(\"PATCH\", url, data, nil)\n\tmapstructure.Decode(res, u)\n\tu.Response = res\n\n\treturn u, err\n}", "func (u *User) UpdateUser(db *pg.DB) error {\n\tcount, err := db.Model(u).WherePK().Count()\n\n\tif count < 1 {\n\t\treturn errors.New(\"User does not exist\")\n\t}\n\t_, err = db.Model(u).WherePK().Update()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func UpdateUser(w http.ResponseWriter, r *http.Request) {\n\n}", "func (b *UserServiceImpl) UpdateUser(ctx context.Context, req models.User) (*models.User, error) {\n\n\tlog.Logger(ctx).Info(\"UpdateUser: \", req)\n\t//Created filter to find and update\n\tfilter := bson.M{\"_id\": bson.M{\"$eq\": req.ID}}\n\tupdateResp, err := b.userRepository.UpdateUser(ctx, filter, req)\n\tif err != nil {\n\t\tlog.Logger(ctx).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn updateResp, nil\n}", "func APIUserUpdate(context echo.Context) error {\n\tuser := &models.User{}\n\n\t// Attempt to bind request to User struct\n\terr := context.Bind(user)\n\tif err != nil {\n\t\treturn ServeWithError(context, 500, err)\n\t}\n\n\t// Parse out id\n\tid, err := strconv.ParseUint(context.Param(\"id\"), 10, 64)\n\tif err != nil {\n\t\treturn ServeWithError(context, 500, err)\n\t}\n\tuser.ID = id\n\n\tcurrentUser := getUser(context)\n\tif !(currentUser != nil && (currentUser.ID == id || currentUser.Role == enums.RoleAdmin)) {\n\t\treturn ServeWithError(context, 403, fmt.Errorf(\"not allowed to access this user\"))\n\t}\n\n\t// Return an error when an unauthorized request to change role was made\n\tif user.Role != enums.RoleAdmin && user.Role != \"\" {\n\t\treturn ServeWithError(context, 403, fmt.Errorf(\"not allowed to change the user role\"))\n\t}\n\n\tif user.Role == \"\" {\n\t\tuser.Role = currentUser.Role\n\t}\n\n\t// Update\n\tuserCollection := models.UserCollection{}\n\terr = userCollection.Update(user)\n\tif err != nil {\n\t\treturn ServeWithError(context, 500, err)\n\t}\n\n\treturn Serve(context, 200)\n}" ]
[ "0.81026113", "0.80925", "0.8079478", "0.8026077", "0.80224335", "0.79828835", "0.7959214", "0.79233134", "0.7879859", "0.78727734", "0.7851507", "0.7851014", "0.7847162", "0.7837235", "0.7834976", "0.78338504", "0.7829921", "0.7805386", "0.7763033", "0.7750823", "0.7749645", "0.77394193", "0.7735433", "0.7711844", "0.77015305", "0.7669994", "0.7667845", "0.76566464", "0.7630494", "0.7621088", "0.76188165", "0.7618159", "0.7617787", "0.76167476", "0.7580025", "0.7564048", "0.75377125", "0.7532942", "0.7532667", "0.7519367", "0.75162", "0.7491504", "0.74909955", "0.74890226", "0.7480149", "0.7472785", "0.7469689", "0.7465553", "0.7462212", "0.7452713", "0.74526066", "0.7438392", "0.74338037", "0.7430088", "0.74241614", "0.74221706", "0.7419785", "0.7414077", "0.74081004", "0.74053454", "0.74005306", "0.739975", "0.739829", "0.7395467", "0.7394934", "0.73927844", "0.7384237", "0.73793596", "0.73793244", "0.73483866", "0.7345348", "0.7341738", "0.7337078", "0.73369986", "0.7332159", "0.7331428", "0.7329751", "0.73293996", "0.73280096", "0.7324223", "0.73127437", "0.73116934", "0.7291924", "0.72849315", "0.7281196", "0.7278002", "0.7276633", "0.7270851", "0.7269342", "0.7261604", "0.7259073", "0.7255474", "0.7239278", "0.7237577", "0.72337615", "0.722492", "0.7223451", "0.7221219", "0.7219324", "0.72096664" ]
0.78768617
9
DeleteUser deletes a user
func DeleteUser(w http.ResponseWriter, r *http.Request) { httpext.SuccessAPI(w, "ok") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\tuser := getUserByID(db, id, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\tif err := db.Delete(&user).Error; err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusNoContent, nil)\n}", "func DeleteUser(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tid := vars[\"id\"]\n\n\tif err := db.Remove(id); err != nil {\n\t\thandleError(err, \"Failed to remove User: %v\", w)\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"OK\"))\n}", "func DeleteUser(c *gin.Context) {\n\tvar user models.User\n\tid := c.Params.ByName(\"id\")\n\terr := models.DeleteUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"id\" + id: \"is deleted\"})\n\t}\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\tuserID, err := strconv.ParseInt(params[\"id\"], 10, 64)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuserIDToken, err := authentication.ExtractUserId(r)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\n\tif userIDToken != userID {\n\t\tresponses.Error(w, http.StatusForbidden, errors.New(\"não é possível manipular usuário de terceiros\"))\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tif err := repository.DeleteUser(userID); err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusNoContent, nil)\n}", "func DeleteUser(c *gin.Context) {\n\tid := c.Param(\"id\")\n\tlog.Printf(\"DeleteUser in db %v\", id)\n\tvar user models.User\n\tdb := db.GetDB()\n\n\tif err := db.Where(\"id = ?\", id).First(&user).Error; err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tlog.Println(\"Failed to DeleteUser in db\")\n\t\treturn\n\t}\n\n\tdb.Delete(&user)\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\r\n\tdefer r.Body.Close()\r\n\tuser := r.Context().Value(\"user\").(string)\r\n\r\n\tif err := dao.DBConn.RemoveUserByEmail(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"User doesn't exist or has already been deleted\")\r\n\t\treturn\r\n\t}\r\n\r\n\tif err := dao.DBConn.RemoveUserExpenses(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"User doesn't exist or has already been deleted\")\r\n\t\treturn\r\n\t}\r\n\r\n\tu.RespondWithJSON(w, http.StatusOK, \"User deleted\")\r\n}", "func DeleteUser(c *gin.Context) {\n\tvar user Models.User\n\tid := c.Params.ByName(\"id\")\n\terr := Models.DeleteUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else { \n\t\tc.JSON(http.StatusOK, gin.H{\"id\":\"is deleted\"})\n\t}\n}", "func DeleteUser(user *models.User, id string) (err error) {\n\tconfig.DB.Where(\"id = ?\", id).Delete(user)\n\treturn nil\n}", "func DeleteUser(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"deleting user\")\n\tvar user entity.User\n\tid := c.Params.ByName(\"id\")\n\terr := model.DeleteUser(&user, id, client)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"id\" + id: \"is deleted\"})\n\t}\n\tlog.Info(\"user deleted\")\n}", "func DeleteUser(id int) {\n\tvar i int\n\ti = GetIndexOfUser(id)\n\tDeleteUserFromDatabase(i)\n}", "func (uc UserController) DeleteUser(w http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprint(w, \"Write code to delete user\\n\")\n}", "func DeleteUser(c *gin.Context) {\n\t// Get model if exist\n\tvar user models.User\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&user).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\tmodels.DB.Delete(&user)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func DeleteUser(c echo.Context) error {\n\tid, _ := strconv.Atoi(c.Param(\"id\"))\n\tdelete(users, id)\n\treturn c.NoContent(http.StatusNoContent)\n}", "func (a *Server) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"delete a user\")\n}", "func DeleteUser(user *entity.User, id string, client *statsd.Client) (err error) {\n\tt := client.NewTiming()\n\tif config.DB.Where(\"id = ?\", id).First(&user); user.ID == \"\" {\n\t\treturn errors.New(\"the user doesn't exist!!!\")\n\t}\n\tconfig.DB.Where(\"id = ?\", id).Delete(&user)\n\tt.Send(\"delete_user.query_time\")\n\treturn nil\n}", "func (s *Service) DeleteUser(c *tokay.Context) {\n\tID := uint64(c.ParamUint(\"id\"))\n\n\tfilter := obj{\"_id\": ID}\n\terr = db.UserCol.Remove(filter)\n\tif errorAlert(\"User was not deleted\", err, c) {\n\t\treturn\n\t}\n\n\tc.JSON(200, obj{\"ok\": \"true\"})\n}", "func UserDelete(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\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\tuserUUID := auth.GetUUIDByName(urlUser, refStr)\n\n\terr := auth.RemoveUser(userUUID, refStr)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write empty response if anything ok\n\trespondOK(w, output)\n\n}", "func (u *UserCtr) DeleteUser(c *gin.Context) {\n\tid,err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\terr = model.DeleteUser(u.DB,id)\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t})\n\treturn\n}", "func DeleteUser(c *gin.Context) {\n\tuserID := c.Param(\"userID\")\n\tuser := &userModel.User{ID: userID}\n\n\terr := dbConnect.Delete(user)\n\tif err != nil {\n\t\tlog.Printf(\"Error while deleting a single user, Reason: %v\\n\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"message\": \"Something went wrong\",\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": http.StatusOK,\n\t\t\"message\": \"User deleted successfully\",\n\t})\n\treturn\n}", "func DeleteUser(db *pg.DB, pk int64) error {\n\n\tuser := models.User{ID: pk}\n\n\tfmt.Println(\"Deleting User...\")\n\n\terr := db.Delete(&user)\n\n\treturn err\n}", "func Delete(c *gin.Context) {\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\tif err := services.UsersService.DeleteUser(userId); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func DeleteUser(id int) error {\n\tuser := User{ID: id}\n\t_, err := db.Model(&user).WherePK().Delete()\n\treturn err\n}", "func DeleteUser(ctx iris.Context) {\n\tvar (\n\t\tuser model.User\n\t\tresult iris.Map\n\t)\n\tid := ctx.Params().Get(\"id\") // get id by params\n\tdb := config.GetDatabaseConnection()\n\tdefer db.Close()\n\terr := db.First(&user, id).Error\n\tif err != nil {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"true\",\n\t\t\t\"status\": iris.StatusBadRequest,\n\t\t\t\"message\": \"User not found\",\n\t\t\t\"result\": nil,\n\t\t}\n\t}\n\n\terr = db.Where(\"id = ?\", id).Delete(&user, id).Error\n\tif err != nil {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"true\",\n\t\t\t\"status\": iris.StatusBadRequest,\n\t\t\t\"message\": \"Failed Delete user\",\n\t\t\t\"result\": err.Error(),\n\t\t}\n\t} else {\n\t\tresult = iris.Map{\n\t\t\t\"error\": \"false\",\n\t\t\t\"status\": iris.StatusOK,\n\t\t\t\"message\": \"Failed Delete user\",\n\t\t\t\"result\": nil,\n\t\t}\n\t}\n\tctx.JSON(result)\n\treturn\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Delete user endpoint hit\")\n\t\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\n\tvar user models.User\n\n\tmessage := user.Destroy(id)\n\n json.NewEncoder(w).Encode(message)\n}", "func Delete(c *gin.Context) {\n\tuserID, err := getUserID(c.Param(\"user_id\"))\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tif err := services.UserServ.DeleteUser(userID); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func deleteUser(w http.ResponseWriter, r *http.Request) {\r\n\tparams := mux.Vars(r)\r\n\tstmt, err := db.Prepare(\"DELETE FROM users WHERE id = ?\")\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\t_, err = stmt.Exec(params[\"id\"])\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tfmt.Fprintf(w, \"User with id = %s was deleted\", params[\"id\"])\r\n}", "func DeleteUser(c *gin.Context) {\n\tuuid := c.Params.ByName(\"uuid\")\n\tvar user models.User\n\tdb := db.GetDB()\n\tif uuid != \"\" {\n\n\t\tjwtClaims := jwt.ExtractClaims(c)\n\t\tauthUserAccessLevel := jwtClaims[\"access_level\"].(float64)\n\t\tauthUserUUID := jwtClaims[\"uuid\"].(string)\n\t\tif authUserAccessLevel != 1 {\n\t\t\tif authUserUUID != uuid {\n\t\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\n\t\t\t\t\t\"error\": \"Sorry but you can't delete user, ONLY admins can\",\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// DELETE FROM users WHERE uuid= user.uuid\n\t\t// exemple : UPDATE users SET deleted_at=date.now WHERE uuid = user.uuid;\n\t\tif err := db.Where(\"uuid = ?\", uuid).Delete(&user).Error; err != nil {\n\t\t\t// error handling...\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Display JSON result\n\t\t// c.JSON(200, gin.H{\"success\": \"User #\" + uuid + \" deleted\"})\n\t\tc.JSON(200, gin.H{\"success\": \"User successfully deleted\"})\n\t} else {\n\t\t// Display JSON error\n\t\tc.JSON(404, gin.H{\"error\": \"User not found\"})\n\t}\n\n}", "func deleteUser(c *gin.Context) {\n\tvar user user\n\tuserID := c.Param(\"id\")\n\n\tdb.First(&user, userID)\n\n\tif user.Id == 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": http.StatusNotFound, \"message\": \"No user found!\"})\n\t\treturn\n\t}\n\n\tdb.Delete(&user)\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": \"User deleted successfully!\"})\n}", "func (us *UserService) Delete(ctx context.Context, user resources.User) error {\n\tuserID, err := user.ID()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = us.call(ctx, \"one.user.delete\", userID)\n\n\treturn err\n}", "func (db Database) DeleteUser(username string) error {\n\treturn errors.New(\"I'm not implemented yet\")\n}", "func DeleteUser(c *gin.Context) {}", "func DeleteUser(id int32) error {\n\treturn dalums.DeleteUser(id)\n}", "func (uc UserController) DeleteUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tid := p.ByName(\"id\")\n\n\tif _, ok := users[id]; !ok {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Delete user\n\tdelete(users, id)\n\n\tw.WriteHeader(http.StatusOK) // 200\n\tfmt.Fprint(w, \"Deleted user\", id, \"\\n\")\n}", "func DeleteUser(id int) (err error) {\n\to := orm.NewOrm()\n\tv := User{Id: id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Delete(&User{Id: id}); err == nil {\n\t\t\tfmt.Println(\"Number of records deleted in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func (app *application) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tid := chi.URLParam(r, \"id\")\n\tuserID, _ := strconv.Atoi(id)\n\n\terr := app.DB.DeleteUser(userID)\n\tif err != nil {\n\t\tapp.badRequest(w, r, err)\n\t\treturn\n\t}\n\n\tvar resp struct {\n\t\tError bool `json:\"error\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\n\tresp.Error = false\n\tapp.writeJSON(w, http.StatusOK, resp)\n}", "func (s *UserRepository) DeleteUser(id string) error {\n\n\treturn nil\n}", "func deleteUser(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\t_, err := db.Exec(`\n\t\tDELETE FROM accounts\n\t\tWHERE username = $1;`, p.ByName(\"username\"),\n\t)\n\tif err != nil {\n\t\tlog.Println(\"deleteUser:\", err)\n\t}\n\n\twriteJSON(res, 200, jsMap{\"status\": \"OK\"})\n}", "func (arg Users) DeleteUser(ctx context.Context) error {\n\tdb, err := DBInit()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = db.ExecContext(ctx, deleteUser, arg.ID)\n\treturn err\n}", "func (serv *AppServer) DeleteUser(delID int) {\n\tserv.ServerRequest([]string{\"DeleteUser\", strconv.Itoa(delID)})\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Deleting a user\"))\n}", "func DeleteUser(c *gin.Context) {\n\tuserID, err := strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\tif err != nil {\n\t\tparamErr := errors.NewBadRequestError(\"user id should be a number\")\n\t\tc.JSON(paramErr.Status, paramErr)\n\t\treturn\n\t}\n\n\t//send the userID to the services\n\tresult, deleteErr := services.UsersService.DeleteUser(userID)\n\tif deleteErr != nil {\n\t\tc.JSON(deleteErr.Status, deleteErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, result)\n}", "func DeleteUser(user *User) {\n\tDb.Delete(&user)\n}", "func (app *App) deleteUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tuser := &users.User{ID: int64(id)}\n\terr = user.DeleteUser(app.Db)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\n\trespondWithJSON(w, http.StatusOK, map[string]string{\"message\": \"User deleted successfully\"})\n}", "func (u *User) Delete() *errorsutils.RestErr {\n\tstmt, err := usersdb.Client.Prepare(queryDeleteUser)\n\tif err != nil {\n\t\tlogger.Error(\"error when trying to prepare delete user statement\", err)\n\t\treturn errorsutils.NewInternalServerError(\"database error\", errors.New(\"database error\"))\n\t}\n\tdefer stmt.Close()\n\n\tif _, err = stmt.Exec(u.ID); err != nil {\n\t\tlogger.Error(\"error when trying to delete user\", err)\n\t\treturn errorsutils.NewInternalServerError(\"database error\", errors.New(\"database error\"))\n\t}\n\n\treturn nil\n}", "func DeleteUser(id int, db *gorm.DB) (err error) {\n\tvar user User\n\tif err = db.First(&user, id).Error; err != nil {\n\t\terr = ErrUserNotFound\n\t} else {\n\t\tdb.Delete(&user)\n\t}\n\treturn\n}", "func DeleteUser(c *gin.Context) {\n\tuser, err := getUserFromParams(c)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif currentUser := c.Value(\"currentUser\").(models.User); currentUser.ID != user.ID {\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unable to delete other users\"})\n\t\treturn\n\t}\n\n\terr = repository.DeleteUser(&user, fmt.Sprint(user.ID))\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"result\": \"user is deleted\"})\n\t}\n}", "func (user *User) Delete() *errors.RestErr {\n\t//prepare and execute the delete query\n\tstmt, err := usersdb.Client.Prepare(queryDeleteUser)\n\tif err != nil {\n\t\treturn errors.NewInternalServerError(err.Error())\n\t}\n\tdefer stmt.Close()\n\n\t//\n\tif _, err = stmt.Exec(user.ID); err != nil {\n\t\treturn errors.ParseError(err)\n\t}\n\n\treturn nil\n\n}", "func DeleteUser(c echo.Context) error {\n\tid := c.FormValue(\"id\")\n\n\tconvID, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\tresult, err := models.DeleteUser(convID)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn c.JSON(http.StatusOK, result)\n}", "func UserDelete(w http.ResponseWriter, r *http.Request, u *User) error {\n\t// the user must confirm their password before deleting\n\tpassword := r.FormValue(\"password\")\n\tif err := u.ComparePassword(password); err != nil {\n\t\treturn RenderError(w, err, http.StatusBadRequest)\n\t}\n\t// TODO we need to delete all repos, builds, commits, branches, etc\n\t// TODO we should transfer ownership of all team-owned projects to the team owner\n\t// delete the account\n\tif err := database.DeleteUser(u.ID); err != nil {\n\t\treturn RenderError(w, err, http.StatusBadRequest)\n\t}\n\n\tLogout(w, r)\n\treturn nil\n}", "func (s *Server) deleteUser(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// get user-id and put into temp\n\tuserId := request.PathParameter(\"user-id\")\n\tif err := s.dataStore.DeleteUser(userId); err != nil {\n\t\tinternalServerError(response, err)\n\t\treturn\n\t}\n\tok(response, Success{RowAffected: 1})\n}", "func (u UserController) DeleteUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tid := p.ByName(\"id\")\n\tuser, err := u.userRepository.GetByID(id)\n\tif err != nil {\n\t\tif _, ok := err.(models.UserNotFoundError); ok {\n\t\t\thttp.Error(w, \"not found\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"service unavailable\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tif err := u.userRepository.Delete(*user); err != nil {\n\t\thttp.Error(w, \"service unavailable\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusNoContent)\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\turl := fmt.Sprintf(\"%s/users/%d\", config.APIURL, userID)\n\n\tresponse, err := requests.RequestsWithAuthentication(r, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, response.StatusCode, nil)\n}", "func (s *Server) deleteUser(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// get user-id and put into temp\n\tuserId := request.PathParameter(\"user-id\")\n\tif err := s.DataStore.DeleteUser(userId); err != nil {\n\t\tinternalServerError(response, err)\n\t\treturn\n\t}\n\tok(response, Success{RowAffected: 1})\n}", "func DeleteUser(person *Person, id string) (err error) {\n\tConfig.DB.Where(\"id = ?\", id).Delete(person)\n\treturn nil\n}", "func DeleteUser(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(req)\n\tuserID := bson.ObjectIdHex(params[\"userID\"])\n\n\tquery := bson.M{\n\t\t\"_id\": userID,\n\t}\n\n\terr := db.DeleteUser(query)\n\tif err != nil {\n\t\tif err.Error() == mgo.ErrNotFound.Error() {\n\t\t\tmsg := \"User not found\"\n\n\t\t\tutils.ReturnErrorResponse(http.StatusNotFound, msg, \"\", nil, nil, res)\n\t\t\treturn\n\t\t}\n\n\t\tmsg := \"Error occurred while deleting user\"\n\t\tutils.ReturnErrorResponse(http.StatusBadRequest, msg, \"\", nil, nil, res)\n\t\treturn\n\t}\n\n\tmsg := \"User deleted successfully\"\n\tutils.ReturnSuccessReponse(http.StatusOK, msg, nil, res)\n}", "func DeleteUser(props neoism.Props) error {\n\n\t// return error if user is not found in the database\n\tif u, _ := FindUser(props); u == nil {\n\t\treturn errors.New(\"user not found\")\n\t}\n\n\tdb := vantaadb.Connect()\n\tcq := neoism.CypherQuery{\n\t\tStatement: `MATCH (u:User)\n OPTIONAL MATCH (s:Session)-[r]->(u)\n WHERE ` + vantaadb.PropString(\"u\", props) + `DELETE u, s, r`,\n\t\tParameters: props,\n\t}\n\tif err := db.Cypher(&cq); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"DeleteUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\tparams, err := helper.ParsePathParams(fmt.Sprintf(\"%s/management/user/{userRecId}\", apiPrefix), r.URL.Path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tuser, err := UserRepo.GetUserByRecID(r.Context(), params[\"userRecId\"])\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByRecID got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User recid %s not found\", params[\"userRecId\"]), nil, nil)\n\t\treturn\n\t}\n\tUserRepo.DeleteUser(r.Context(), user)\n\tRevocationRepo.Revoke(r.Context(), user.Email)\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"User deleted\", nil, nil)\n}", "func DeleteUser(c *gin.Context) {\n\tnID := c.Param(\"user_id\")\n\tdb := dbConn()\n\tstatement, _ := db.Prepare(\"CALL delete_user(?)\")\n\tstatement.Exec(nID)\n\tdefer db.Close()\n}", "func DeleteUser(userID int64) *errors.RestErr {\n\tuser := &users.User{ID: userID}\n\treturn user.Delete()\n}", "func (m *MgoUserManager) DeleteUser(id interface{}) error {\n\toid, err := getId(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn m.UserColl.RemoveId(oid)\n}", "func (server Server) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) //mux params\n\tid, err := strconv.Atoi(vars[\"id\"]) // convert the id in string to int\n\tvar res models.APIResponse // make a response\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to convert the string into int. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to convert the string into int\", nil)\n\t} else {\n\t\tdeletedRows := deleteUser(int64(id), server.db) // call the deleteUser, convert the int to int64\n\t\tres = models.BuildAPIResponseSuccess(\"User updated successfully.\", deletedRows)\n\t}\n\t// send the response\n\tjson.NewEncoder(w).Encode(res)\n}", "func DeleteUser(\n\tctx context.Context,\n\ttx *sql.Tx,\n\trequest *models.DeleteUserRequest) error {\n\tdeleteQuery := deleteUserQuery\n\tselectQuery := \"select count(uuid) from user where uuid = ?\"\n\tvar err error\n\tvar count int\n\tuuid := request.ID\n\tauth := common.GetAuthCTX(ctx)\n\tif auth.IsAdmin() {\n\t\trow := tx.QueryRowContext(ctx, selectQuery, uuid)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"not found\")\n\t\t}\n\t\trow.Scan(&count)\n\t\tif count == 0 {\n\t\t\treturn errors.New(\"Not found\")\n\t\t}\n\t\t_, err = tx.ExecContext(ctx, deleteQuery, uuid)\n\t} else {\n\t\tdeleteQuery += \" and owner = ?\"\n\t\tselectQuery += \" and owner = ?\"\n\t\trow := tx.QueryRowContext(ctx, selectQuery, uuid, auth.ProjectID())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"not found\")\n\t\t}\n\t\trow.Scan(&count)\n\t\tif count == 0 {\n\t\t\treturn errors.New(\"Not found\")\n\t\t}\n\t\t_, err = tx.ExecContext(ctx, deleteQuery, uuid, auth.ProjectID())\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete failed\")\n\t}\n\n\terr = common.DeleteMetaData(tx, uuid)\n\tlog.WithFields(log.Fields{\n\t\t\"uuid\": uuid,\n\t}).Debug(\"deleted\")\n\treturn err\n}", "func DeleteUser(c *gin.Context) {\n\tvar json db.UserDeleteForm\n\tif err := c.ShouldBind(&json); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"Form doens't bind.\",\n\t\t\t\"err\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tsession := sessions.Default(c)\n\tuserID := session.Get(\"userID\")\n\tvar user db.Users\n\tif err := db.DB.Where(userID).\n\t\tFirst(&user).Error; gorm.IsRecordNotFoundError(err) {\n\t\t// User not found\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not found in database.\",\n\t\t\t\"err\": err,\n\t\t})\n\t\treturn\n\t}\n\tif checkPasswordHash(json.Password, user.Password) {\n\t\tsession.Clear()\n\t\tsession.Save()\n\t\t// Soft delete user\n\t\tdb.DB.Where(userID).Delete(&user)\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": user.Username,\n\t\t\t\"err\": \"\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"msg\": fmt.Sprintf(\"Check password hash failed for user %s\", user.Username),\n\t\t\t\"err\": user.Username,\n\t\t})\n\t}\n}", "func DeleteUser(id int) error {\n\tq := \"DELETE FROM users WHERE id=$1\"\n\t_, err := dbConn.Exec(q, id)\n\treturn err\n}", "func DeleteUser(c *gin.Context) {\n\tif userCollection == nil {\n\t\tuserCollection = db.GetUserCollection()\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tid, _ := primitive.ObjectIDFromHex(c.Param(\"id\"))\n\tresult, err := userCollection.DeleteOne(ctx, entity.User{ID: id})\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(500, gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"Result\": result})\n}", "func DeleteUser(dbmap *gorp.DbMap, id string) error {\n\tvar u User\n\terr := dbmap.SelectOne(&u, \"SELECT * FROM user WHERE object_id = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx, err := dbmap.Begin()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t_, err = tx.Exec(\"DELETE FROM user_session WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"DELETE FROM user_role WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"DELETE FROM domain_user WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Delete(&u)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (c *Client) DeleteUser(ctx context.Context, path string) (*http.Response, error) {\n\tvar body io.Reader\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"DELETE\", 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\tc.SignerJWT.Sign(ctx, req)\n\treturn c.Client.Do(ctx, req)\n}", "func (u UserAPI) DeleteUser(ctx *gin.Context) {\n\tusername := ctx.Param(\"username\")\n\tauthUsername := ctx.MustGet(AuthUserKey)\n\n\tif username == \"\" {\n\t\tctx.JSON(http.StatusBadRequest, models.ApiResponse{\n\t\t\tMessage: \"username is required\",\n\t\t})\n\t\treturn\n\t}\n\tif username != authUsername {\n\t\t// user can only delete themselves\n\t\tctx.JSON(http.StatusForbidden, models.ApiResponse{\n\t\t\tMessage: \"invalid username\",\n\t\t})\n\t\treturn\n\t}\n\terr := u.DB.DeleteOne(ctx, username)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, models.ApiResponse{\n\t\t\tMessage: \"database error: \" + err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t// delete user posts\n\terr = db.NewPostStore().DeleteMany(ctx, username)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, models.ApiResponse{\n\t\t\tMessage: \"database error: \" + err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, models.ApiResponse{})\n}", "func (db *DB) DeleteUser(id string) error {\n\tcursor := db.collections.users.FindOneAndDelete(\n\t\tcontext.Background(),\n\t\tbson.D{primitive.E{\n\t\t\tKey: \"_id\",\n\t\t\tValue: id,\n\t\t}},\n\t)\n\n\tif cursor.Err() != nil {\n\t\treturn cursor.Err()\n\t}\n\n\treturn nil\n}", "func (d *DB) DeleteUser(id uint) error {\n\tvar user User\n\tuser.Model.ID = id\n\terr := d.db.Delete(&user).Error\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (auh *AdminUserHandler) DeleteUser(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\tvar apiKey = r.Header.Get(\"api-key\")\n\tif apiKey == \"\" || (apiKey != adminApiKey && apiKey != userApiKey) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\treturn\n\t}\n\tid, err := strconv.Atoi(ps.ByName(\"id\"))\n\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\t_, errs := auh.userService.DeleteUser(uint(id))\n\n\tif len(errs) > 0 {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusNoContent)\n\treturn\n}", "func (c *MysqlUserController) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tuser := params[\"user\"]\n\tapiKey := r.Header.Get(\"apiKey\")\n\tresult, err := c.service.DeleteUser(user, apiKey)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\topenapi.EncodeJSONResponse(result, nil, w)\n}", "func (a *AdminAPI) DeleteUser(ctx context.Context, username string) error {\n\tif username == \"\" {\n\t\treturn errors.New(\"invalid empty username\")\n\t}\n\t// This is because the api endpoint is userEndpoint/{user}.\n\tpath := usersEndpoint + \"/\" + url.PathEscape(username)\n\treturn a.sendToLeader(ctx, http.MethodDelete, path, nil, nil)\n}", "func (userRepo *PostUserRepository) DeleteUser(id int) error {\n\n\t_, err := userRepo.conn.Exec(\"DELETE FROM users WHERE id=$1\", id)\n\tif err != nil {\n\t\treturn errors.New(\"Delete has failed\")\n\t}\n\n\treturn nil\n}", "func (h *Handler) deleteUser(c *gin.Context) handlerResponse {\n\n\tdeletedUser, err := h.service.User.Delete(c.Param(userParameter), h.who(c))\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\t// Remove password so we do not show in response\n\tdeletedUser.Password = \"\"\n\treturn handleOK(deletedUser)\n}", "func (us *UserStorage) DeleteUser(id string) error {\n\treturn nil\n}", "func (user *User) Delete() {\n\tdb := common.GetDatabase()\n\n\tdb.Delete(&user)\n}", "func (s *Sqlite) DeleteUser(user gogios.User) error {\n\tdb, err := s.openConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tdb.Where(\"Username = ?\", user.Username).Update(\"password\", \"\")\n\tdb.Where(\"Username = ?\", user.Username).Delete(&user)\n\n\treturn nil\n}", "func (*userDAO) DeleteUser() error {\n\treturn DBInstance.Delete(&User{}).Error\n}", "func (r *Rabbit) DeleteUser(name string) error {\n\t_, err := r.doRequest(\"DELETE\", \"/api/users/\"+name, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteUser(serverURI, username, password, feedback string) {\n\tpayload := `{\"password\":\"` + password + `\",\"feedback\":\"` + feedback + `\"}`\n\treq, err := http.NewRequest(\"DELETE\", serverURI+\"/v3/user\", bytes.NewBuffer([]byte(payload)))\n\tΩ(err).ShouldNot(HaveOccurred())\n\terr = APIClient.Do(req, nil)\n\tΩ(err).ShouldNot(HaveOccurred())\n}", "func DeleteUser(ctx context.Context, user *model.User) (err error) {\n\tc := userCollection()\n\t_, err = c.DeleteOne(ctx, bson.D{{Key: \"_id\", Value: user.ID}})\n\treturn\n}", "func Delete(w http.ResponseWriter, r *http.Request) {\n\tuserID := context.Get(r, \"userID\").(int)\n\n\t// Excluindo usuário logado\n\terr := ServiceUser.Delete(userID)\n\n\tif err != nil {\n\t\tw.Write(util.MessageInfo(\"message\", err.Error()))\n\t\treturn\n\t}\n\n\tw.Write(util.MessageInfo(\"message\", \"Excluído com sucesso\"))\n}", "func (a Authorizer) DeleteUser(username string) error {\n\terr := a.userDao.DeleteUser(username)\n\tif err != nil {\n\t\tlogger.Get().Error(\"Unable delete the user: %s. error: %v\", username, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Repository) DeleteUser(data *User) (err error) {\n\n\terr = r.db.Delete(data).Error\n\n\treturn\n}", "func DeleteUser(username string) error {\n\tvar err error\n\n\terr = database.Delete(\"USER\", username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (u *UserServiceHandler) Delete(ctx context.Context, userID string) error {\n\n\turi := \"/v1/user/delete\"\n\n\tvalues := url.Values{\n\t\t\"USERID\": {userID},\n\t}\n\n\treq, err := u.client.NewRequest(ctx, http.MethodPost, uri, values)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = u.client.DoWithContext(ctx, req, nil)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Shell) DeleteUser(c *cli.Context) (err error) {\n\temail := c.String(\"email\")\n\tif email == \"\" {\n\t\treturn s.errorOut(errors.New(\"email flag is empty, must specify an email\"))\n\t}\n\n\tresponse, err := s.HTTP.Delete(fmt.Sprintf(\"/v2/users/%s\", email))\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := response.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(response, &AdminUsersPresenter{}, \"Successfully deleted API user\")\n}", "func DeleteUser(id string) error {\n\t_, err := db.Exec(\"DELETE FROM web_users WHERE ID = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (uv *userValidator) Delete(id uint) error{\n\tvar user User\n\tuser.ID = id\n\terr := runUserValidatorFunction(&user, uv.idGreaterThan(0))\n\tif err != nil{\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (a Authorizer) DeleteUser(username string) error {\n\terr := a.userDao.DeleteUser(username)\n\tif err != nil {\n\t\tlogger.Get().Error(\"Unable to delete the user: %s. error: %v\", username, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteUser(db sqlx.Execer, id int64) error {\n\tres, err := db.Exec(\"delete from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete error\")\n\t}\n\tra, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get rows affected error\")\n\t}\n\tif ra == 0 {\n\t\treturn ErrDoesNotExist\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"id\": id,\n\t}).Info(\"user deleted\")\n\treturn nil\n}", "func (fc FlarumClient) DeleteUser(userId string) error {\n\tvar payload = map[string]interface{}{\n\t\t\"data\": map[string]interface{}{\n\t\t\t\"type\": \"users\",\n\t\t\t\"id\": userId,\n\t\t},\n\t}\n\n\t_, err := fc.sendApiRequest(request.DELETE, \"/users/\"+userId, payload)\n\treturn err\n}", "func (u *User) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !u._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif u._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM test_database.users WHERE user_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, u.UserID)\n\t_, err = db.Exec(sqlstr, u.UserID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tu._deleted = true\n\n\treturn nil\n}", "func (uri UserRepositoryImpl) DeleteUser(id int) error {\n\t_, err := uri.conn.Exec(\"DELETE FROM users WHERE id=$1\", id)\n\tif err != nil {\n\t\treturn errors.New(\"Deleting a user from database has failed\")\n\t}\n\treturn nil\n}", "func (_UserCrud *UserCrudTransactor) DeleteUser(opts *bind.TransactOpts, userAddress common.Address) (*types.Transaction, error) {\n\treturn _UserCrud.contract.Transact(opts, \"deleteUser\", userAddress)\n}", "func DeleteUser(id int64) error {\n\tdb.Exec(\"DELETE FROM members WHERE user_id = ?\", id)\n\tdb.Exec(\"DELETE FROM users WHERE id = ?\", id)\n\t// TODO delete all projects\n\treturn nil\n}", "func (tc TeresaClient) DeleteUser(ID int64) error {\n\tparams := users.NewDeleteUserParams()\n\tparams.UserID = ID\n\t_, err := tc.teresa.Users.DeleteUser(params, tc.apiKeyAuthFunc)\n\treturn err\n}", "func (g *Game) deleteUser(user *User) {\n\tdelete(g.Players, (*user).Name)\n\tlog.Println(\"Deleted user \" + (*user).Name)\n}", "func (us *UserStorage) DeleteUser(id string) error {\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn model.ErrorWrongDataFormat\n\t}\n\ts := us.db.Session(UsersCollection)\n\tdefer s.Close()\n\n\terr := s.C.RemoveId(bson.ObjectIdHex(id))\n\treturn err\n}" ]
[ "0.82981205", "0.82952017", "0.82247216", "0.82235473", "0.8219142", "0.8207494", "0.8198762", "0.8190993", "0.8171767", "0.8157415", "0.81248444", "0.81179225", "0.8099745", "0.8091513", "0.8079702", "0.8063075", "0.80567044", "0.8046376", "0.8039773", "0.8031342", "0.8030444", "0.80223304", "0.8018385", "0.8002431", "0.79817116", "0.79760855", "0.7972081", "0.79718554", "0.796957", "0.7956655", "0.79519755", "0.7949488", "0.79494673", "0.79428315", "0.7942494", "0.7939104", "0.79356813", "0.79347354", "0.7927864", "0.7926903", "0.7925867", "0.79219127", "0.79088974", "0.7908621", "0.790838", "0.7903497", "0.79028076", "0.78972954", "0.78949624", "0.78766364", "0.78605115", "0.7852375", "0.78240734", "0.7815582", "0.7814198", "0.7809685", "0.77941006", "0.77896166", "0.7788448", "0.778652", "0.7777351", "0.7776993", "0.7772211", "0.77693", "0.7764586", "0.7762383", "0.7760719", "0.7753779", "0.7744671", "0.7734297", "0.77171767", "0.7717057", "0.77101654", "0.7707978", "0.77070314", "0.77007633", "0.7690102", "0.76893336", "0.7683947", "0.7679924", "0.76757735", "0.7675485", "0.7674782", "0.76739526", "0.7672637", "0.76724213", "0.76619613", "0.7661166", "0.7658053", "0.76574624", "0.7656695", "0.76531094", "0.7652009", "0.7650144", "0.76417804", "0.7629235", "0.7617631", "0.76174265", "0.7608715", "0.76085794" ]
0.8223412
4
New creates a new kubernetes executor.
func New(config Config) *KubernetesExecutor { k := &KubernetesExecutor{ kl: config.Kubelet, updateChan: config.Updates, state: disconnectedState, tasks: make(map[string]*kuberTask), pods: make(map[string]*api.Pod), sourcename: config.SourceName, client: config.APIClient, done: make(chan struct{}), outgoing: make(chan func() (mesos.Status, error), 1024), dockerClient: config.Docker, suicideTimeout: config.SuicideTimeout, kubeletFinished: config.KubeletFinished, suicideWatch: &suicideTimer{}, shutdownAlert: config.ShutdownAlert, exitFunc: config.ExitFunc, podStatusFunc: config.PodStatusFunc, initialRegComplete: make(chan struct{}), staticPodsConfigPath: config.StaticPodsConfigPath, } // watch pods from the given pod ListWatch _, k.podController = framework.NewInformer(config.PodLW, &api.Pod{}, podRelistPeriod, &framework.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { pod := obj.(*api.Pod) log.V(4).Infof("pod %s/%s created on apiserver", pod.Namespace, pod.Name) k.handleChangedApiserverPod(pod) }, UpdateFunc: func(oldObj, newObj interface{}) { pod := newObj.(*api.Pod) log.V(4).Infof("pod %s/%s updated on apiserver", pod.Namespace, pod.Name) k.handleChangedApiserverPod(pod) }, DeleteFunc: func(obj interface{}) { pod := obj.(*api.Pod) log.V(4).Infof("pod %s/%s deleted on apiserver", pod.Namespace, pod.Name) }, }) return k }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(kl *kubelet.Kubelet, ch chan<- interface{}, ns string, cl *client.Client, w watch.Interface, dc dockertools.DockerInterface) *KubernetesExecutor {\n\t//TODO(jdef) do something real with these events..\n\tevents := w.ResultChan()\n\tif events != nil {\n\t\tgo func() {\n\t\t\tfor e := range events {\n\t\t\t\t// e ~= watch.Event { ADDED, *api.Event }\n\t\t\t\tlog.V(1).Info(e)\n\t\t\t}\n\t\t}()\n\t}\n\tk := &KubernetesExecutor{\n\t\tkl: kl,\n\t\tupdateChan: ch,\n\t\tstate: disconnectedState,\n\t\ttasks: make(map[string]*kuberTask),\n\t\tpods: make(map[string]*api.BoundPod),\n\t\tsourcename: ns,\n\t\tclient: cl,\n\t\tevents: events,\n\t\tdone: make(chan struct{}),\n\t\toutgoing: make(chan func() (mesos.Status, error), 1024),\n\t\tdockerClient: dc,\n\t}\n\tgo k.sendLoop()\n\treturn k\n}", "func New(client *containerd.Client, root, cgroup string, networkProviders map[pb.NetMode]network.Provider, dnsConfig *oci.DNSConfig) executor.Executor {\n\t// clean up old hosts/resolv.conf file. ignore errors\n\tos.RemoveAll(filepath.Join(root, \"hosts\"))\n\tos.RemoveAll(filepath.Join(root, \"resolv.conf\"))\n\n\treturn &containerdExecutor{\n\t\tclient: client,\n\t\troot: root,\n\t\tnetworkProviders: networkProviders,\n\t\tcgroupParent: cgroup,\n\t\tdnsConfig: dnsConfig,\n\t\trunning: make(map[string]chan error),\n\t}\n}", "func New(client docker.APIClient) executor.Executor {\n\treturn &dockerExecutor{\n\t\tclient: client,\n\t}\n}", "func New() Executor {\n\treturn make(Executor)\n}", "func New(env v1alpha1.Environment) (*Kubernetes, error) {\n\t// setup client\n\tctl, err := client.New(env.Spec.APIServer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// setup diffing\n\tif env.Spec.DiffStrategy == \"\" {\n\t\tenv.Spec.DiffStrategy = \"native\"\n\n\t\tif ctl.Info().ServerVersion.LessThan(semver.MustParse(\"1.13.0\")) {\n\t\t\tenv.Spec.DiffStrategy = \"subset\"\n\t\t}\n\t}\n\n\tk := Kubernetes{\n\t\tEnv: env,\n\t\tctl: ctl,\n\t\tdiffers: map[string]Differ{\n\t\t\t\"native\": ctl.DiffClientSide,\n\t\t\t\"validate\": ctl.DiffServerSide,\n\t\t\t\"subset\": SubsetDiffer(ctl),\n\t\t},\n\t}\n\n\treturn &k, nil\n}", "func New(executor *mesos.ExecutorInfo, scheduleFunc PodScheduleFunc, client *client.Client, helper tools.EtcdHelper, sr service.Registry) *KubernetesScheduler {\n\treturn &KubernetesScheduler{\n\t\tnew(sync.RWMutex),\n\t\thelper,\n\t\texecutor,\n\t\tnil,\n\t\tnil,\n\t\tnil,\n\t\tfalse,\n\t\tmake(map[string]*mesos.Offer),\n\t\tmake(map[string]*Slave),\n\t\tmake(map[string]string),\n\t\tmake(map[string]*PodTask),\n\t\tmake(map[string]*PodTask),\n\t\tring.New(defaultFinishedTasksSize),\n\t\tmake(map[string]string),\n\t\tscheduleFunc,\n\t\tclient,\n\t\tcache.NewFIFO(),\n\t\tsr,\n\t}\n}", "func New(s *Setup) (Engine, error) {\n\t// validate the setup being provided\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Validate\n\terr := s.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Debug(\"creating executor engine from setup\")\n\t// process the executor driver being provided\n\tswitch s.Driver {\n\tcase constants.DriverDarwin:\n\t\t// handle the Darwin executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Darwin\n\t\treturn s.Darwin()\n\tcase constants.DriverLinux:\n\t\t// handle the Linux executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Linux\n\t\treturn s.Linux()\n\tcase constants.DriverLocal:\n\t\t// handle the Local executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Local\n\t\treturn s.Local()\n\tcase constants.DriverWindows:\n\t\t// handle the Windows executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Windows\n\t\treturn s.Windows()\n\tdefault:\n\t\t// handle an invalid executor driver being provided\n\t\treturn nil, fmt.Errorf(\"invalid executor driver provided: %s\", s.Driver)\n\t}\n}", "func New() *Kitops {\n\turl := os.Getenv(\"KITOPS_DEPLOYMENTS_URL\")\n\tif len(url) == 0 {\n\t\t// set default URL\n\t\turl = \"https://github.com/300481/kitops-test.git\"\n\t}\n\n\trepo, err := sourcerepo.New(url, \"/tmp/repo\")\n\n\tif err != nil {\n\t\tlog.Printf(\"unable to get repository: %s\\n%v\", url, err)\n\t\treturn nil\n\t}\n\n\tqp := &QueueProcessor{\n\t\tClusterConfigs: make(map[string]*ClusterConfig),\n\t\trepository: repo,\n\t}\n\n\tq := queue.New(qp)\n\n\treturn &Kitops{\n\t\trouter: mux.NewRouter(),\n\t\tqueue: q,\n\t\tqueueProcessor: qp,\n\t}\n}", "func New(zones []string) *Kubernetes {\n\tk := new(Kubernetes)\n\tk.Zones = zones\n\tk.Namespaces = make(map[string]struct{})\n\tk.podMode = podModeDisabled\n\tk.ttl = defaultTTL\n\n\treturn k\n}", "func New() *Executor {\n\treturn NewSandboxingExecutor(false, NamespaceNever, \"\")\n}", "func New() (*K8S, error) {\n\t// create the Kubernetes API client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk8s := &K8S{Client: client.CoreV1()}\n\tk8s.Services = &Services{\n\t\tclient: k8s.Client.Services(\"\"),\n\t\tinterrupt: make(chan bool),\n\t\tsvcMap: make(chan map[string]apiv1.Service),\n\t}\n\n\treturn k8s, nil\n}", "func NewRuntime(opts ...runtime.Option) runtime.Runtime {\n\t// get default options\n\toptions := runtime.Options{\n\t\t// Create labels with type \"micro\": \"service\"\n\t\tType: \"service\",\n\t}\n\n\t// apply requested options\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\t// kubernetes client\n\tclient := client.NewClientInCluster()\n\n\treturn &kubernetes{\n\t\toptions: options,\n\t\tclosed: make(chan bool),\n\t\tqueue: make(chan *task, 128),\n\t\tclient: client,\n\t}\n}", "func (m *ExecutorServiceFactory) New(name string, c core.Config, ch chan core.ServiceCommand) (core.Service, error) {\n\t// check mongo db configuration\n\thosts, err := c.String(\"conductor\", \"mongo\")\n\tif err != nil || hosts == \"\" {\n\t\treturn nil, errors.New(\"Invalid mongo configuration\")\n\t}\n\t// try connect with mongo db\n\tif session, err := mgo.Dial(hosts); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tsession.Close()\n\t}\n\texecutorService = &ExecutorService{\n\t\tconfig: c,\n\t\twg: sync.WaitGroup{},\n\t\tchn: ch,\n\t\truleChan: make(chan *Rule),\n\t\tengines: make(map[string]*ruleEngine),\n\t\tmutex: sync.Mutex{},\n\t}\n\treturn executorService, nil\n}", "func New() *KubeCross {\n\treturn &KubeCross{&defaultImpl{}}\n}", "func New() venom.Executor {\n\treturn &Executor{}\n}", "func New(cfg Config, ccCli cassandracli.Interface, k8sService k8s.Services, crdCli crd.Interface, kubeCli kubernetes.Interface, logger log.Logger) (operator.Operator, error) {\n\n\t// Create our CRD\n\tccCRD := newCassandraClusterCRD(ccCli, crdCli, kubeCli)\n\n\tccSvc := ccsvc.NewCassandraClusterClient(k8sService, logger)\n\n\t// Create the handler\n\thandler := newHandler(kubeCli, ccSvc, logger)\n\n\t// Create our controller.\n\tctrl := controller.NewSequential(cfg.ResyncPeriod, handler, ccCRD, nil, logger)\n\n\t// Assemble CRD and controller to create the operator.\n\treturn operator.NewOperator(ccCRD, ctrl, logger), nil\n}", "func NewExecutor(helmClient helm.Interface, chartLoader ChartLoader, kubeSecrets SecretsWriteDeleter, dryRun bool) Executor {\n\treturn &executor{\n\t\thelmClient: helmClient,\n\t\tchartLoader: chartLoader,\n\t\tkubeSecrets: kubeSecrets,\n\t\tdryRun: dryRun,\n\t}\n}", "func New(t time.Duration, inCluster bool) (*KubeAPI, error) {\n\tvar api KubeAPI\n\tapi.Timeout = t\n\tapi.InCluster = inCluster\n\tvar err error\n\n\tif api.InCluster {\n\t\tapi.Config, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn &api, err\n\t\t}\n\t} else {\n\t\tkubeconfig := filepath.Join(homeDir(), \".kube\", \"config\")\n\t\tapi.Config, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\n\tapi.Client, err = kubernetes.NewForConfig(api.Config)\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\treturn &api, nil\n}", "func New(agent string) (*Operator, error) {\n\tcli, err := client.New(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Operator{cli: cli}, nil\n}", "func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}", "func New(ctx resource.Context, cfg echo.Config) (i echo.Instance, err error) {\n\terr = resource.UnsupportedEnvironment(ctx.Environment())\n\n\tctx.Environment().Case(environment.Native, func() {\n\t\ti, err = native.New(ctx, cfg)\n\t})\n\n\tctx.Environment().Case(environment.Kube, func() {\n\t\ti, err = kube.New(ctx, cfg)\n\t})\n\treturn\n}", "func New(c Config, storageFuns ...qmstorage.StorageTypeNewFunc) (*Operator, error) {\n\tcfg, err := newClusterConfig(c.Host, c.Kubeconfig, c.TLSInsecure, &c.TLSConfig)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\tclient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\trclient, err := NewQuartermasterRESTClient(*cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\t// Initialize storage plugins\n\tstorageSystems := make(map[spec.StorageTypeIdentifier]qmstorage.StorageType)\n\tfor _, newStorage := range storageFuns {\n\n\t\t// New\n\t\tst, err := newStorage(client, rclient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Save object\n\t\tstorageSystems[st.Type()] = st\n\n\t\tlogger.Info(\"storage driver %v loaded\", st.Type())\n\t}\n\n\treturn &Operator{\n\t\tkclient: client,\n\t\trclient: rclient,\n\t\tqueue: newQueue(200),\n\t\thost: cfg.Host,\n\t\tstorageSystems: storageSystems,\n\t}, nil\n}", "func New(config *rest.Config) (*Cluster, error) {\n\tclientSet, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kubernetes.NewForConfig: %w\", err)\n\t}\n\treturn &Cluster{clientSet}, nil\n}", "func New(image, name, workdir string, cmd []string) (c *Container, err error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tc = &Container{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\timage: image,\n\t\tname: name,\n\t}\n\tc.cli, err = client.NewEnvClient()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = c.removeExisting(name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar output io.ReadCloser\n\toutput, err = c.cli.ImagePull(ctx, image, types.ImagePullOptions{})\n\tif err != nil {\n\t\treturn\n\t}\n\tio.Copy(os.Stdout, output)\n\n\tresp, err := c.cli.ContainerCreate(ctx, &container.Config{\n\t\tImage: image,\n\t\tWorkingDir: workdir,\n\t\tEntrypoint: cmd,\n\t}, &container.HostConfig{\n\t\tNetworkMode: \"host\",\n\t\tMounts: []mount.Mount{{\n\t\t\tType: mount.TypeBind,\n\t\t\tSource: workdir,\n\t\t\tTarget: workdir,\n\t\t}},\n\t}, nil, name)\n\tif err != nil {\n\t\treturn\n\t}\n\tc.id = resp.ID\n\treturn\n}", "func New(etype SSHType, sudo bool, c SSHConfig) (ctxt.Executor, error) {\n\tif etype == \"\" {\n\t\tetype = SSHTypeBuiltin\n\t}\n\n\t// Used in integration testing, to check if native ssh client is really used when it need to be.\n\tfailpoint.Inject(\"assertNativeSSH\", func() {\n\t\t// XXX: We call system executor 'native' by mistake in commit f1142b1\n\t\t// this should be fixed after we remove --native-ssh flag\n\t\tif etype != SSHTypeSystem {\n\t\t\tmsg := fmt.Sprintf(\n\t\t\t\t\"native ssh client should be used in this case, os.Args: %s, %s = %s\",\n\t\t\t\tos.Args, localdata.EnvNameNativeSSHClient, os.Getenv(localdata.EnvNameNativeSSHClient),\n\t\t\t)\n\t\t\tpanic(msg)\n\t\t}\n\t})\n\n\t// set default values\n\tif c.Port <= 0 {\n\t\tc.Port = 22\n\t}\n\n\tif c.Timeout == 0 {\n\t\tc.Timeout = time.Second * 5 // default timeout is 5 sec\n\t}\n\n\tvar executor ctxt.Executor\n\tswitch etype {\n\tcase SSHTypeBuiltin:\n\t\te := &EasySSHExecutor{\n\t\t\tLocale: \"C\",\n\t\t\tSudo: sudo,\n\t\t}\n\t\te.initialize(c)\n\t\texecutor = e\n\tcase SSHTypeSystem:\n\t\te := &NativeSSHExecutor{\n\t\t\tConfig: &c,\n\t\t\tLocale: \"C\",\n\t\t\tSudo: sudo,\n\t\t}\n\t\tif c.Password != \"\" || (c.KeyFile != \"\" && c.Passphrase != \"\") {\n\t\t\t_, _, e.ConnectionTestResult = e.Execute(context.Background(), connectionTestCommand, false, executeDefaultTimeout)\n\t\t}\n\t\texecutor = e\n\tcase SSHTypeNone:\n\t\tif err := checkLocalIP(c.Host); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\te := &Local{\n\t\t\tConfig: &c,\n\t\t\tSudo: sudo,\n\t\t\tLocale: \"C\",\n\t\t}\n\t\texecutor = e\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unregistered executor: %s\", etype)\n\t}\n\n\treturn &CheckPointExecutor{executor, &c}, nil\n}", "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func NewExecutor() *Executor {\n\treturn &Executor{\n\t\texit: make(chan struct{}),\n\t\tstop: make(chan struct{}),\n\t\ttasks: make([]*task, 0, 64),\n\t}\n}", "func New(createCRD bool, namespace string) *Cluster {\n\t\n\tclientset := utils.MustNewKubeClient(); \n\treturn &Cluster{\n\t\tlogger: logrus.WithField(\"pkg\", \"controller\"),\n\t\tnamespace: namespace,\n\t\tkubeClientset: clientset,\n\t\tcreateCustomResource: createCRD,\n\t}\n}", "func New(ctx context.Context, tenantClusterKubernetesClient tenantcluster.Client) (Client, error) {\n\treturnedSecret, err := tenantClusterKubernetesClient.GetSecret(ctx, defaultCredentialsSecretSecretName, defaultCredentialsSecretSecretNamespace)\n\tif err != nil {\n\t\tif apimachineryerrors.IsNotFound(err) {\n\t\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %s/%s: %v not found\", defaultCredentialsSecretSecretNamespace, defaultCredentialsSecretSecretName, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\tplatformCredentials, ok := returnedSecret.Data[platformCredentialsKey]\n\tif !ok {\n\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %v did not contain key %v\",\n\t\t\tdefaultCredentialsSecretSecretName, platformCredentials)\n\t}\n\n\tclientConfig, err := clientcmd.NewClientConfigFromBytes(platformCredentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClientConfig, err := clientConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubernetesClient, err := kubernetes.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{\n\t\tkubernetesClient: kubernetesClient,\n\t\tdynamicClient: dynamicClient,\n\t}, nil\n}", "func (r *LocalRuntime) New(ctx context.Context, name, signaturePolicyPath, authfile string, writer io.Writer, dockeroptions *image.DockerRegistryOptions, signingoptions image.SigningOptions, forcePull bool, label *string) (*ContainerImage, error) {\n\timg, err := r.Runtime.ImageRuntime().New(ctx, name, signaturePolicyPath, authfile, writer, dockeroptions, signingoptions, forcePull, label)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContainerImage{img}, nil\n}", "func New(kubeconfig string) (*Instance, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\n\tif len(kubeconfig) > 0 {\n\t\tlogrus.Debugf(\"using kubeconfig: %s to create k8s client\", kubeconfig)\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tlogrus.Debugf(\"will use in-cluster config to create k8s client\")\n\t\tcfg, err = rest.InClusterConfig()\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Instance{\n\t\tkubeClient: kubeClient,\n\t\tk8sOps: core.Instance(),\n\t}, nil\n}", "func New() (Container, error) {\n\tspec, err := generate.New(\"linux\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &container{\n\t\tspec: spec,\n\t}, nil\n}", "func NewExec() *ExecKubectl {\n\treturn &ExecKubectl{cmdSite: &console{}}\n}", "func New(config Config) (*Controller, error) {\n\tif reflect.DeepEqual(config.Cluster, v1alpha1.KVMConfig{}) {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Cluster must not be empty\", config)\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Logger must not be empty\", config)\n\t}\n\tif config.ManagementK8sClient == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.ManagementK8sClient must not be empty\", config)\n\t}\n\tif config.Name == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Name must not be empty\", config)\n\t}\n\tif config.Selector == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Selector must not be empty\", config)\n\t}\n\tif config.WorkloadK8sClient == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.WorkloadK8sClient must not be empty\", config)\n\t}\n\n\tc := &Controller{\n\t\tmanagementK8sClient: config.ManagementK8sClient,\n\t\tworkloadK8sClient: config.WorkloadK8sClient,\n\t\tlogger: config.Logger,\n\n\t\tstopped: make(chan struct{}),\n\t\tlastReconciled: time.Time{},\n\t\tname: config.Name,\n\t\tselector: config.Selector,\n\t\tcluster: config.Cluster,\n\t}\n\n\treturn c, nil\n}", "func New(config *Config) (*Operation, error) {\n\top := &Operation{\n\t\tauthService: config.AuthService,\n\t\tkmsService: config.KMSService,\n\t\tcryptoBoxCreator: config.CryptoBoxCreator,\n\t\tjsonLDLoader: config.JSONLDLoader,\n\t\tlogger: config.Logger,\n\t\ttracer: config.Tracer,\n\t\tbaseURL: config.BaseURL,\n\t\tvdrResolver: config.VDRResolver,\n\t}\n\n\treturn op, nil\n}", "func newPod(ctx context.Context, cl client.Client, ns, name, image string, cmd []string) (*corev1.Pod, error) {\n\tc := corev1.Container{\n\t\tName: name,\n\t\tImage: image,\n\t\tCommand: cmd,\n\t}\n\tp := &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{c},\n\t\t\t// Kill the pod immediately so it exits quickly on deletion.\n\t\t\tTerminationGracePeriodSeconds: pointer.Int64Ptr(0),\n\t\t},\n\t}\n\tif err := cl.Create(ctx, p); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create pod %s/%s: %v\", p.Namespace, p.Name, err)\n\t}\n\treturn p, nil\n}", "func New(data []byte, filename string) (*Exec, error) {\n\tlog.Tracef(\"Creating new at %v\", filename)\n\treturn loadExecutable(filename, data)\n}", "func (k *Kubelet) New() (container.ResourceInstance, error) {\n\t// TODO: When creating kubelet, also pull pause image using configured Container Runtime\n\t// to speed up later start of pods?\n\tif err := k.Validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"validating kubelet configuration: %w\", err)\n\t}\n\n\tnewKubelet := &kubelet{\n\t\tconfig: *k,\n\t}\n\n\tif newKubelet.config.Image == \"\" {\n\t\tnewKubelet.config.Image = defaults.KubeletImage\n\t}\n\n\treturn newKubelet, nil\n}", "func New() (kubernetes.Interface, error) {\n\tcs, err := getClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func Create(namespace string, resourceAndArgs ...string) (err error) {\n\tcreate := []string{\"create\", \"-n\", namespace}\n\t_, err = kubectl(append(create, resourceAndArgs...)...)\n\treturn\n}", "func New(opts ...OptionFunc) corev1.Container {\n\tc := &container{}\n\tfor _, o := range opts {\n\t\to(c)\n\t}\n\treturn c.asContainer()\n}", "func NewExecutor(store storage.Store, options BuildOptions) (*Executor, error) {\n\texec := Executor{\n\t\tstore: store,\n\t\tcontextDir: options.ContextDirectory,\n\t\tpullPolicy: options.PullPolicy,\n\t\tregistry: options.Registry,\n\t\tignoreUnrecognizedInstructions: options.IgnoreUnrecognizedInstructions,\n\t\tquiet: options.Quiet,\n\t\truntime: options.Runtime,\n\t\truntimeArgs: options.RuntimeArgs,\n\t\ttransientMounts: options.TransientMounts,\n\t\tcompression: options.Compression,\n\t\toutput: options.Output,\n\t\toutputFormat: options.OutputFormat,\n\t\tadditionalTags: options.AdditionalTags,\n\t\tsignaturePolicyPath: options.SignaturePolicyPath,\n\t\tsystemContext: options.SystemContext,\n\t\tvolumeCache: make(map[string]string),\n\t\tvolumeCacheInfo: make(map[string]os.FileInfo),\n\t\tlog: options.Log,\n\t\tin: options.In,\n\t\tout: options.Out,\n\t\terr: options.Err,\n\t\treportWriter: options.ReportWriter,\n\t\tisolation: options.Isolation,\n\t\tnamespaceOptions: options.NamespaceOptions,\n\t\tconfigureNetwork: options.ConfigureNetwork,\n\t\tcniPluginPath: options.CNIPluginPath,\n\t\tcniConfigDir: options.CNIConfigDir,\n\t\tidmappingOptions: options.IDMappingOptions,\n\t\tcommonBuildOptions: options.CommonBuildOpts,\n\t\tdefaultMountsFilePath: options.DefaultMountsFilePath,\n\t\tiidfile: options.IIDFile,\n\t\tsquash: options.Squash,\n\t\tlabels: append([]string{}, options.Labels...),\n\t\tannotations: append([]string{}, options.Annotations...),\n\t\tlayers: options.Layers,\n\t\tnoCache: options.NoCache,\n\t\tremoveIntermediateCtrs: options.RemoveIntermediateCtrs,\n\t\tforceRmIntermediateCtrs: options.ForceRmIntermediateCtrs,\n\t\tblobDirectory: options.BlobDirectory,\n\t}\n\tif exec.err == nil {\n\t\texec.err = os.Stderr\n\t}\n\tif exec.out == nil {\n\t\texec.out = os.Stdout\n\t}\n\tif exec.log == nil {\n\t\tstepCounter := 0\n\t\texec.log = func(format string, args ...interface{}) {\n\t\t\tstepCounter++\n\t\t\tprefix := fmt.Sprintf(\"STEP %d: \", stepCounter)\n\t\t\tsuffix := \"\\n\"\n\t\t\tfmt.Fprintf(exec.err, prefix+format+suffix, args...)\n\t\t}\n\t}\n\treturn &exec, nil\n}", "func New(serviceIDs []string, logger lager.Logger) (*Crossplane, error) {\n\tif err := SetupScheme(scheme.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk, err := k8sclient.New(config, k8sclient.Options{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp := Crossplane{\n\t\tClient: k,\n\t\tlogger: logger,\n\t\tDownstreamClients: make(map[string]k8sclient.Client, 0),\n\t\tServiceIDs: serviceIDs,\n\t}\n\n\treturn &cp, nil\n}", "func New(config *aws.Config) *IoT {\n\tservice := &service.Service{\n\t\tServiceInfo: serviceinfo.ServiceInfo{\n\t\t\tConfig: defaults.DefaultConfig.Merge(config),\n\t\t\tServiceName: \"iot\",\n\t\t\tSigningName: \"execute-api\",\n\t\t\tAPIVersion: \"2015-05-28\",\n\t\t},\n\t}\n\tservice.Initialize()\n\n\t// Handlers\n\tservice.Handlers.Sign.PushBack(v4.Sign)\n\tservice.Handlers.Build.PushBack(restjson.Build)\n\tservice.Handlers.Unmarshal.PushBack(restjson.Unmarshal)\n\tservice.Handlers.UnmarshalMeta.PushBack(restjson.UnmarshalMeta)\n\tservice.Handlers.UnmarshalError.PushBack(restjson.UnmarshalError)\n\n\t// Run custom service initialization if present\n\tif initService != nil {\n\t\tinitService(service)\n\t}\n\n\treturn &IoT{service}\n}", "func (fgsc *FakeGKESDKClient) newOp() *container.Operation {\n\topName := strconv.Itoa(fgsc.opNumber)\n\top := &container.Operation{\n\t\tName: opName,\n\t\tStatus: \"DONE\",\n\t}\n\tif status, ok := fgsc.opStatus[opName]; ok {\n\t\top.Status = status\n\t}\n\tfgsc.opNumber++\n\tfgsc.ops[opName] = op\n\treturn op\n}", "func New() *Operation {\n\treturn &Operation{}\n}", "func newK8SCloud(opts Options) (CloudProvider, error) {\n\n\tif opts.Name == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud name\")\n\t}\n\tif opts.Host == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud host\")\n\t}\n\tif opts.K8SNamespace == \"\" {\n\t\topts.K8SNamespace = apiv1.NamespaceDefault\n\t}\n\n\tcloud := &K8SCloud{\n\t\tname: opts.Name,\n\t\thost: opts.Host,\n\t\tbearerToken: opts.K8SBearerToken,\n\t\tnamespace: opts.K8SNamespace,\n\t\tinsecure: opts.Insecure,\n\t}\n\tconfig := &rest.Config{\n\t\tHost: opts.Host,\n\t\tBearerToken: opts.K8SBearerToken,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloud.client = clientset\n\treturn cloud, nil\n}", "func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}", "func New(\n\tnamespace, name, imagesFile string,\n\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\n\tmcInformer mcfginformersv1.MachineConfigInformer,\n\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\n\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\n\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\n\tdeployInformer appsinformersv1.DeploymentInformer,\n\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\n\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\n\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\n\tmcoCmInformer,\n\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\n\tinfraInformer configinformersv1.InfrastructureInformer,\n\tnetworkInformer configinformersv1.NetworkInformer,\n\tproxyInformer configinformersv1.ProxyInformer,\n\tdnsInformer configinformersv1.DNSInformer,\n\tclient mcfgclientset.Interface,\n\tkubeClient kubernetes.Interface,\n\tapiExtClient apiextclientset.Interface,\n\tconfigClient configclientset.Interface,\n\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\n\tnodeInformer coreinformersv1.NodeInformer,\n\tmaoSecretInformer coreinformersv1.SecretInformer,\n\timgInformer configinformersv1.ImageInformer,\n) *Operator {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\n\toptr := &Operator{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\timagesFile: imagesFile,\n\t\tvStore: newVersionStore(),\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tapiExtClient: apiExtClient,\n\t\tconfigClient: configClient,\n\t\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"machineconfigoperator\"})),\n\t\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \"machine-config-operator\", &corev1.ObjectReference{\n\t\t\tKind: \"Deployment\",\n\t\t\tName: \"machine-config-operator\",\n\t\t\tNamespace: ctrlcommon.MCONamespace,\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"machineconfigoperator\"),\n\t}\n\n\tfor _, i := range []cache.SharedIndexInformer{\n\t\tcontrollerConfigInformer.Informer(),\n\t\tserviceAccountInfomer.Informer(),\n\t\tcrdInformer.Informer(),\n\t\tdeployInformer.Informer(),\n\t\tdaemonsetInformer.Informer(),\n\t\tclusterRoleInformer.Informer(),\n\t\tclusterRoleBindingInformer.Informer(),\n\t\tmcoCmInformer.Informer(),\n\t\tclusterCmInfomer.Informer(),\n\t\tinfraInformer.Informer(),\n\t\tnetworkInformer.Informer(),\n\t\tmcpInformer.Informer(),\n\t\tproxyInformer.Informer(),\n\t\toseKubeAPIInformer.Informer(),\n\t\tnodeInformer.Informer(),\n\t\tdnsInformer.Informer(),\n\t\tmaoSecretInformer.Informer(),\n\t} {\n\t\ti.AddEventHandler(optr.eventHandler())\n\t}\n\n\toptr.syncHandler = optr.sync\n\n\toptr.imgLister = imgInformer.Lister()\n\toptr.clusterCmLister = clusterCmInfomer.Lister()\n\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\n\toptr.mcpLister = mcpInformer.Lister()\n\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\n\toptr.ccLister = controllerConfigInformer.Lister()\n\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\n\toptr.mcLister = mcInformer.Lister()\n\toptr.mcListerSynced = mcInformer.Informer().HasSynced\n\toptr.proxyLister = proxyInformer.Lister()\n\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\n\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\n\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\n\toptr.nodeLister = nodeInformer.Lister()\n\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\n\n\toptr.imgListerSynced = imgInformer.Informer().HasSynced\n\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\n\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\n\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\n\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\n\toptr.mcoCmLister = mcoCmInformer.Lister()\n\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\n\toptr.crdLister = crdInformer.Lister()\n\toptr.crdListerSynced = crdInformer.Informer().HasSynced\n\toptr.deployLister = deployInformer.Lister()\n\toptr.deployListerSynced = deployInformer.Informer().HasSynced\n\toptr.daemonsetLister = daemonsetInformer.Lister()\n\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\n\toptr.infraLister = infraInformer.Lister()\n\toptr.infraListerSynced = infraInformer.Informer().HasSynced\n\toptr.networkLister = networkInformer.Lister()\n\toptr.networkListerSynced = networkInformer.Informer().HasSynced\n\toptr.dnsLister = dnsInformer.Lister()\n\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\n\n\toptr.vStore.Set(\"operator\", version.ReleaseVersion)\n\n\treturn optr\n}", "func New(apiVersion, maestroVersion string) (*Driver, error) {\n\tdClient, dockerErr := dockerEngine.NewEnvClient()\n\tif dockerErr != nil {\n\t\treturn nil, dockerErr\n\t}\n\treturn &Driver{\n\t\tclient: dClient,\n\t\timage: fmt.Sprintf(\"cpg1111/maestro:%s\", maestroVersion),\n\t}, nil\n}", "func New(logger logrus.FieldLogger, metadata *types.ClusterMetadata) (providers.Destroyer, error) {\n\treturn &ClusterUninstaller{\n\t\tLogger: logger,\n\t\tRegion: metadata.ClusterPlatformMetadata.GCP.Region,\n\t\tProjectID: metadata.ClusterPlatformMetadata.GCP.ProjectID,\n\t\tNetworkProjectID: metadata.ClusterPlatformMetadata.GCP.NetworkProjectID,\n\t\tPrivateZoneDomain: metadata.ClusterPlatformMetadata.GCP.PrivateZoneDomain,\n\t\tClusterID: metadata.InfraID,\n\t\tcloudControllerUID: gcptypes.CloudControllerUID(metadata.InfraID),\n\t\trequestIDTracker: newRequestIDTracker(),\n\t\tpendingItemTracker: newPendingItemTracker(),\n\t}, nil\n}", "func New(op *installations.Operation) *ExecutionOperation {\n\treturn &ExecutionOperation{\n\t\tOperation: op,\n\t}\n}", "func (f *Factory) New(providerConf digitalocean.Config, clusterState *cluster.State) (provider.Activity, error) {\n\tk8s := &K8s{}\n\tk8s.moduleDir = filepath.Join(config.Global.ProjectRoot, \"terraform/digitalocean/\"+myName)\n\tk8s.backendKey = \"states/terraform-\" + myName + \".state\"\n\tk8s.backendConf = digitalocean.BackendSpec{\n\t\tBucket: providerConf.ClusterName,\n\t\tKey: k8s.backendKey,\n\t\tEndpoint: providerConf.Region + \".digitaloceanspaces.com\",\n\t}\n\trawProvisionerData, err := yaml.Marshal(providerConf.Provisioner)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurret while marshal provisioner config: %s\", err.Error())\n\t}\n\tif err = yaml.Unmarshal(rawProvisionerData, &k8s.config); err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurret while parsing provisioner config: %s\", err.Error())\n\t}\n\n\tk8s.config.ClusterName = providerConf.ClusterName\n\tk8s.config.Region = providerConf.Region\n\n\tk8s.terraform, err = executor.NewTerraformRunner(k8s.moduleDir, provisioner.GetAwsAuthEnv()...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk8s.terraform.LogLabels = append(k8s.terraform.LogLabels, fmt.Sprintf(\"cluster='%s'\", providerConf.ClusterName))\n\treturn k8s, nil\n}", "func New(\n\tnodes node.ServiceNodes,\n\topts Options,\n) (Cluster, error) {\n\tif err := opts.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcluster := &svcCluster{\n\t\tlogger: opts.InstrumentOptions().Logger(),\n\t\topts: opts,\n\t\tknownNodes: nodes,\n\t\tusedNodes: make(idToNodeMap, len(nodes)),\n\t\tspares: make([]node.ServiceNode, 0, len(nodes)),\n\t\tsparesByID: make(map[string]node.ServiceNode, len(nodes)),\n\t\tplacementSvc: opts.PlacementService(),\n\t\tstatus: ClusterStatusUninitialized,\n\t}\n\tcluster.addSparesWithLock(nodes)\n\n\treturn cluster, nil\n}", "func New(\n\tclient client.Client,\n\ttaskQueue string,\n\toptions Options,\n) Worker {\n\treturn internal.NewWorker(client, taskQueue, options)\n}", "func New(client k8s.CoreV1Client, configQueue workqueue.RateLimitingInterface, meshNamespace string) *Deployer {\n\td := &Deployer{\n\t\tclient: client,\n\t\tconfigQueue: configQueue,\n\t\tmeshNamespace: meshNamespace,\n\t}\n\n\tif err := d.Init(); err != nil {\n\t\tlog.Errorln(\"Could not initialize Deployer\")\n\t}\n\n\treturn d\n}", "func New(namespace, name string, conf fixture.DMConfig) *Ops {\n\treturn &Ops{\n\t\tcli: tests.TestClient.Cli,\n\t\tdm: newDM(namespace, name, conf),\n\t}\n}", "func New(kclient *k8sutil.K8sutil, baseImage string) (*Processor, error) {\n\tp := &Processor{\n\t\tk8sclient: kclient,\n\t\tbaseImage: baseImage,\n\t\tclusters: make(map[string]Cluster),\n\t}\n\n\treturn p, nil\n}", "func Create(rw *RequestWrapper) (*clm.GKECluster, error) {\n\tgkeOps, err := rw.acquire()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rw.Request.SaveMetaData {\n\t\t// At this point we should have a cluster ready to run test. Need to save\n\t\t// metadata so that following flow can understand the context of cluster, as\n\t\t// well as for Prow usage later\n\t\twriteMetaData(gkeOps.Cluster, gkeOps.Project)\n\t}\n\n\t// set up kube config points to cluster\n\tclusterAuthCmd := fmt.Sprintf(\n\t\t\"gcloud beta container clusters get-credentials %s --region %s --project %s\",\n\t\tgkeOps.Cluster.Name, gkeOps.Cluster.Location, gkeOps.Project)\n\tif out, err := cmd.RunCommand(clusterAuthCmd); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed connecting to cluster: %q, %w\", out, err)\n\t}\n\tif out, err := cmd.RunCommand(\"gcloud config set project \" + gkeOps.Project); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed setting project: %q, %w\", out, err)\n\t}\n\n\treturn gkeOps, nil\n}", "func New(options ...Option) *Deployment {\n\tns := &Deployment{}\n\n\tfor _, op := range options {\n\t\top(ns)\n\t}\n\n\treturn ns\n}", "func New() *pool {\n\treturn &pool{\n\t\tmetrics: newMetrics(),\n\t}\n}", "func newExecutor(logger *logrus.Logger, logPrefix string, store storage.Store, options define.BuildOptions, mainNode *parser.Node, containerFiles []string) (*Executor, error) {\n\tdefaultContainerConfig, err := config.Default()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get container config: %w\", err)\n\t}\n\n\texcludes := options.Excludes\n\tif len(excludes) == 0 {\n\t\texcludes, options.IgnoreFile, err = parse.ContainerIgnoreFile(options.ContextDirectory, options.IgnoreFile, containerFiles)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcapabilities, err := defaultContainerConfig.Capabilities(\"\", options.AddCapabilities, options.DropCapabilities)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevices := define.ContainerDevices{}\n\tfor _, device := range append(defaultContainerConfig.Containers.Devices, options.Devices...) {\n\t\tdev, err := parse.DeviceFromPath(device)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdevices = append(dev, devices...)\n\t}\n\n\ttransientMounts := []Mount{}\n\tfor _, volume := range append(defaultContainerConfig.Containers.Volumes, options.TransientMounts...) {\n\t\tmount, err := parse.Volume(volume)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttransientMounts = append([]Mount{mount}, transientMounts...)\n\t}\n\n\tsecrets, err := parse.Secrets(options.CommonBuildOpts.Secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsshsources, err := parse.SSH(options.CommonBuildOpts.SSHSources)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twriter := options.ReportWriter\n\tif options.Quiet {\n\t\twriter = io.Discard\n\t}\n\n\tvar rusageLogFile io.Writer\n\n\tif options.LogRusage && !options.Quiet {\n\t\tif options.RusageLogFile == \"\" {\n\t\t\trusageLogFile = options.Out\n\t\t} else {\n\t\t\trusageLogFile, err = os.OpenFile(options.RusageLogFile, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\texec := Executor{\n\t\targs: options.Args,\n\t\tcacheFrom: options.CacheFrom,\n\t\tcacheTo: options.CacheTo,\n\t\tcacheTTL: options.CacheTTL,\n\t\tcontainerSuffix: options.ContainerSuffix,\n\t\tlogger: logger,\n\t\tstages: make(map[string]*StageExecutor),\n\t\tstore: store,\n\t\tcontextDir: options.ContextDirectory,\n\t\texcludes: excludes,\n\t\tgroupAdd: options.GroupAdd,\n\t\tignoreFile: options.IgnoreFile,\n\t\tpullPolicy: options.PullPolicy,\n\t\tregistry: options.Registry,\n\t\tignoreUnrecognizedInstructions: options.IgnoreUnrecognizedInstructions,\n\t\tquiet: options.Quiet,\n\t\truntime: options.Runtime,\n\t\truntimeArgs: options.RuntimeArgs,\n\t\ttransientMounts: transientMounts,\n\t\tcompression: options.Compression,\n\t\toutput: options.Output,\n\t\toutputFormat: options.OutputFormat,\n\t\tadditionalTags: options.AdditionalTags,\n\t\tsignaturePolicyPath: options.SignaturePolicyPath,\n\t\tskipUnusedStages: options.SkipUnusedStages,\n\t\tsystemContext: options.SystemContext,\n\t\tlog: options.Log,\n\t\tin: options.In,\n\t\tout: options.Out,\n\t\terr: options.Err,\n\t\treportWriter: writer,\n\t\tisolation: options.Isolation,\n\t\tnamespaceOptions: options.NamespaceOptions,\n\t\tconfigureNetwork: options.ConfigureNetwork,\n\t\tcniPluginPath: options.CNIPluginPath,\n\t\tcniConfigDir: options.CNIConfigDir,\n\t\tnetworkInterface: options.NetworkInterface,\n\t\tidmappingOptions: options.IDMappingOptions,\n\t\tcommonBuildOptions: options.CommonBuildOpts,\n\t\tdefaultMountsFilePath: options.DefaultMountsFilePath,\n\t\tiidfile: options.IIDFile,\n\t\tsquash: options.Squash,\n\t\tlabels: append([]string{}, options.Labels...),\n\t\tannotations: append([]string{}, options.Annotations...),\n\t\tlayers: options.Layers,\n\t\tnoHosts: options.CommonBuildOpts.NoHosts,\n\t\tuseCache: !options.NoCache,\n\t\tremoveIntermediateCtrs: options.RemoveIntermediateCtrs,\n\t\tforceRmIntermediateCtrs: options.ForceRmIntermediateCtrs,\n\t\timageMap: make(map[string]string),\n\t\tcontainerMap: make(map[string]*buildah.Builder),\n\t\tbaseMap: make(map[string]bool),\n\t\trootfsMap: make(map[string]bool),\n\t\tblobDirectory: options.BlobDirectory,\n\t\tunusedArgs: make(map[string]struct{}),\n\t\tcapabilities: capabilities,\n\t\tdevices: devices,\n\t\tsignBy: options.SignBy,\n\t\tarchitecture: options.Architecture,\n\t\ttimestamp: options.Timestamp,\n\t\tos: options.OS,\n\t\tmaxPullPushRetries: options.MaxPullPushRetries,\n\t\tretryPullPushDelay: options.PullPushRetryDelay,\n\t\tociDecryptConfig: options.OciDecryptConfig,\n\t\tterminatedStage: make(map[string]error),\n\t\tstagesSemaphore: options.JobSemaphore,\n\t\tlogRusage: options.LogRusage,\n\t\trusageLogFile: rusageLogFile,\n\t\timageInfoCache: make(map[string]imageTypeAndHistoryAndDiffIDs),\n\t\tfromOverride: options.From,\n\t\tadditionalBuildContexts: options.AdditionalBuildContexts,\n\t\tmanifest: options.Manifest,\n\t\tsecrets: secrets,\n\t\tsshsources: sshsources,\n\t\tlogPrefix: logPrefix,\n\t\tunsetEnvs: append([]string{}, options.UnsetEnvs...),\n\t\tbuildOutput: options.BuildOutput,\n\t\tosVersion: options.OSVersion,\n\t\tosFeatures: append([]string{}, options.OSFeatures...),\n\t\tenvs: append([]string{}, options.Envs...),\n\t}\n\tif exec.err == nil {\n\t\texec.err = os.Stderr\n\t}\n\tif exec.out == nil {\n\t\texec.out = os.Stdout\n\t}\n\n\tfor arg := range options.Args {\n\t\tif _, isBuiltIn := builtinAllowedBuildArgs[arg]; !isBuiltIn {\n\t\t\texec.unusedArgs[arg] = struct{}{}\n\t\t}\n\t}\n\tfor _, line := range mainNode.Children {\n\t\tnode := line\n\t\tfor node != nil { // tokens on this line, though we only care about the first\n\t\t\tswitch strings.ToUpper(node.Value) { // first token - instruction\n\t\t\tcase \"ARG\":\n\t\t\t\targ := node.Next\n\t\t\t\tif arg != nil {\n\t\t\t\t\t// We have to be careful here - it's either an argument\n\t\t\t\t\t// and value, or just an argument, since they can be\n\t\t\t\t\t// separated by either \"=\" or whitespace.\n\t\t\t\t\tlist := strings.SplitN(arg.Value, \"=\", 2)\n\t\t\t\t\tdelete(exec.unusedArgs, list[0])\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn &exec, nil\n}", "func NewEtcd(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\n\tlogger := &fsm.Logger{\n\t\tFieldLogger: logrus.WithField(constants.FieldPhase, p.Phase.ID),\n\t\tKey: p.Key(),\n\t\tOperator: operator,\n\t\tServer: p.Phase.Data.Server,\n\t}\n\t// Connect to the local etcd server.\n\tstateDir, err := state.GetStateDir()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tetcdClient, err := clients.EtcdMembers(&clients.EtcdConfig{\n\t\tSecretsDir: state.SecretDir(stateDir),\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &etcdExecutor{\n\t\tFieldLogger: logger,\n\t\tEtcd: etcdClient,\n\t\tExecutorParams: p,\n\t}, nil\n}", "func NewExecutor(clientProvider ClientProvider, apiAddress, userAgent string) *Executor {\n\treturn &Executor{\n\t\tuserAgent: userAgent,\n\t\tapiAddress: apiAddress,\n\t\tclientProvider: clientProvider,\n\t}\n}", "func NewExecutor(b executorpkg.Backend, p plugin.Backend) exec.Executor {\n\treturn &executor{\n\t\tbackend: b,\n\t\tpluginBackend: p,\n\t\tdependencies: agent.NewDependencyManager(),\n\t}\n}", "func newExecute(name string) *Instruction {\n\treturn &Instruction{\n\t\tType: ExecuteInst,\n\t\tName: name,\n\t}\n}", "func New(ctx provider) (*Operation, error) {\n\tcmd, err := vdr.New(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new vdr : %w\", err)\n\t}\n\n\to := &Operation{command: cmd}\n\to.registerHandler()\n\n\treturn o, nil\n}", "func New(\n\tc string,\n\tv string,\n\tr numeral.Repository,\n\ts numeral.Storage,\n) Controller {\n\treturn &controller{\n\t\tcommit: c,\n\t\tversion: v,\n\t\trepository: r,\n\t\tstorage: s,\n\t}\n}", "func New() Go { return Go{} }", "func newFromName(clusterClient kubernetes.Interface, client k8s.Interface, wfr, namespace string) (Operator, error) {\n\tw, err := client.CycloneV1alpha1().WorkflowRuns(namespace).Get(context.TODO(), wfr, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &operator{\n\t\tclusterClient: clusterClient,\n\t\tclient: client,\n\t\trecorder: common.GetEventRecorder(client, common.EventSourceWfrController),\n\t\twfr: w,\n\t}, nil\n}", "func New(t *testing.T) (*Terraform, error) {\n\tt.Helper()\n\n\tlogging := *logTF\n\n\texecPath, err := findExecutable(logging)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempDir, err := createTempDir(logging)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Terraform{\n\t\tt: t,\n\t\texecPath: execPath,\n\t\ttempDir: tempDir,\n\t\tlogging: logging,\n\t}, nil\n}", "func New(endpoint string) (e *Etcd, err error) {\n\tvar u *url.URL\n\tu, err = url.Parse(endpoint)\n\tif err != nil {\n\t\treturn\n\t}\n\tpwd, _ := u.User.Password()\n\n\te = &Etcd{}\n\te.cfg = cli.Config{\n\t\tEndpoints: []string{fmt.Sprintf(\"%s://%s/\", u.Scheme, u.Host)},\n\t\tTransport: cli.DefaultTransport,\n\t\tUsername: u.User.Username(),\n\t\tPassword: pwd,\n\t\t// set timeout per request to fail fast when the target endpoint is unavailable\n\t\tHeaderTimeoutPerRequest: time.Second * 2,\n\t}\n\te.cli, err = cli.New(e.cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\te.kapi = cli.NewKeysAPI(e.cli)\n\treturn\n}", "func New(cfg *Config) (*Operator, error) {\n\toperator := &Operator{config: cfg}\n\n\t// Get a config to talk to the apiserver.\n\tclientConfig, err := config.GetConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the controller-manager.\n\tmanagerOptions := manager.Options{\n\t\tNamespace: cfg.WatchNamespace,\n\t}\n\n\toperator.manager, err = manager.New(clientConfig, managerOptions)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create manager: %v\", err)\n\t}\n\n\t// Setup Scheme for all resources.\n\tif err := apis.AddToScheme(operator.manager.GetScheme()); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to register types: %v\", err)\n\t}\n\n\t// Setup our controllers and add them to the manager.\n\tif err := operator.AddControllers(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to add controllers: %v\", err)\n\t}\n\n\tstatusConfig := &StatusReporterConfig{\n\t\tVerticalPodAutoscalerName: cfg.VerticalPodAutoscalerName,\n\t\tVerticalPodAutoscalerNamespace: cfg.VerticalPodAutoscalerNamespace,\n\t\tReleaseVersion: cfg.ReleaseVersion,\n\t\tRelatedObjects: operator.RelatedObjects(),\n\t}\n\n\tstatusReporter, err := NewStatusReporter(operator.manager, statusConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create status reporter: %v\", err)\n\t}\n\n\tif err := operator.manager.Add(statusReporter); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to add status reporter to manager: %v\", err)\n\t}\n\n\treturn operator, nil\n}", "func New(name, platformName, path, format string, parentUI *ui.UI, envConfig map[string]string) (*Kluster, error) {\n\tif len(format) == 0 {\n\t\tformat = DefaultFormat\n\t}\n\tif !validFormat(format) {\n\t\treturn nil, fmt.Errorf(\"invalid format %q for the kubernetes cluster config file\", format)\n\t}\n\tpath = filepath.Join(path, DefaultConfigFilename+\".\"+format)\n\n\tif _, err := os.Stat(path); os.IsExist(err) {\n\t\treturn nil, fmt.Errorf(\"the Kluster config file %q already exists\", path)\n\t}\n\n\tnewUI := parentUI.Copy()\n\n\tcluster := Kluster{\n\t\tVersion: Version,\n\t\tKind: \"cluster\",\n\t\tName: name,\n\t\tpath: path,\n\t\tui: newUI,\n\t}\n\n\t// // TODO: Improve this, all platforms are not needed\n\t// allPlatforms := provisioner.SupportedPlatforms(name, envConfig)\n\t// platform, ok := allPlatforms[platformName]\n\t// if !ok {\n\t// \treturn nil, fmt.Errorf(\"platform %q is not supported\", platformName)\n\t// }\n\n\tplatform, err := provisioner.New(name, platformName, envConfig, newUI, Version)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"platform %q is not supported. %s\", platformName, err)\n\t}\n\n\tlogPrefix := fmt.Sprintf(\"KubeKit [ %s@%s ]\", cluster.Name, platformName)\n\tcluster.ui.SetLogPrefix(logPrefix)\n\n\tcluster.Platforms = make(map[string]interface{}, 1)\n\tcluster.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tcluster.State = make(map[string]*State, 1)\n\n\tcluster.Platforms[platformName] = platform.Config()\n\tcluster.provisioner[platformName] = platform\n\tcluster.State[platformName] = &State{\n\t\tStatus: AbsentStatus.String(),\n\t}\n\n\tcluster.Resources = resources.DefaultResourcesFor(platformName)\n\n\t// return if this is a platform with no configuration, such as EKS or AKS\n\tswitch platformName {\n\tcase \"eks\", \"aks\":\n\t\treturn &cluster, nil\n\t}\n\n\tcluster.Config, err = configurator.DefaultConfig(envConfig)\n\n\treturn &cluster, err\n}", "func New(mcpName string, nodeSelector map[string]string) *machineconfigv1.MachineConfigPool {\n\treturn &machineconfigv1.MachineConfigPool{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: mcpName,\n\t\t\tNamespace: metav1.NamespaceNone,\n\t\t\tLabels: map[string]string{components.MachineConfigRoleLabelKey: mcpName},\n\t\t},\n\t\tSpec: machineconfigv1.MachineConfigPoolSpec{\n\t\t\tMachineConfigSelector: &metav1.LabelSelector{\n\t\t\t\tMatchExpressions: []metav1.LabelSelectorRequirement{\n\t\t\t\t\t{\n\t\t\t\t\t\tKey: components.MachineConfigRoleLabelKey,\n\t\t\t\t\t\tOperator: \"In\",\n\t\t\t\t\t\tValues: []string{\"worker\", mcpName},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tNodeSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: nodeSelector,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewOperator(clusterClient kubernetes.Interface, client k8s.Interface, wfr interface{}, namespace string) (Operator, error) {\n\tif w, ok := wfr.(string); ok {\n\t\treturn newFromName(clusterClient, client, w, namespace)\n\t}\n\n\tif w, ok := wfr.(*v1alpha1.WorkflowRun); ok {\n\t\treturn newFromValue(clusterClient, client, w, namespace)\n\t}\n\n\treturn nil, fmt.Errorf(\"invalid parameter 'wfr' provided: %v\", wfr)\n}", "func New(ip string, user string, name string) *Cloud {\n\treturn &Cloud{\n\t\tIP: ip,\n\t\tUser: user,\n\t\tName: name,\n\t\tType: types.CloudTypeDocker,\n\t}\n}", "func New(ctx context.Context, d *dut.DUT, altHostname, outDir string, chartPaths []string) (*Chart, []NamePath, error) {\n\tvar conn *ssh.Conn\n\n\t// Connect to chart tablet.\n\tif len(altHostname) > 0 {\n\t\tc, err := connectChart(ctx, d, altHostname)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrapf(err, \"failed to connect to chart with hostname %v\", altHostname)\n\t\t}\n\t\tconn = c\n\t} else {\n\t\tc, err := d.DefaultCameraboxChart(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"failed to connect to chart with default '-tablet' suffix hostname\")\n\t\t}\n\t\tconn = c\n\t}\n\n\treturn SetUp(ctx, conn, outDir, chartPaths)\n}", "func newService(kogitoApp *v1alpha1.KogitoApp, deploymentConfig *appsv1.DeploymentConfig) (service *corev1.Service) {\n\tif deploymentConfig == nil {\n\t\t// we can't create a service without a DC\n\t\treturn nil\n\t}\n\n\tports := buildServicePorts(deploymentConfig)\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tservice = &corev1.Service{\n\t\tObjectMeta: *deploymentConfig.ObjectMeta.DeepCopy(),\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: deploymentConfig.Spec.Selector,\n\t\t\tType: corev1.ServiceTypeClusterIP,\n\t\t\tPorts: ports,\n\t\t},\n\t}\n\n\tmeta.SetGroupVersionKind(&service.TypeMeta, meta.KindService)\n\taddDefaultMeta(&service.ObjectMeta, kogitoApp)\n\taddServiceLabels(&service.ObjectMeta, kogitoApp)\n\timportPrometheusAnnotations(deploymentConfig, service)\n\tservice.ResourceVersion = \"\"\n\treturn service\n}", "func New(c string, args ...string) *Cmd {\n\tcmd := &Cmd{\n\t\tCmd: exec.Command(c, args...),\n\t}\n\tcmd.Run = func() error {\n\t\treturn cmd.Cmd.Run()\n\t}\n\treturn cmd\n}", "func New(cfg *Config) (*Cmd, error) {\n\t_, err := signatureAndHashAlgorithmByKeyType(cfg.Key.Type)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"key type %v is not supported\", cfg.Key.Type)\n\t}\n\n\tkh, err := cfg.KMS.Get(cfg.Key.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kms get kh: %w\", err)\n\t}\n\n\tpubBytes, err := cfg.KMS.ExportPubKeyBytes(cfg.Key.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"export pub key bytes: %w\", err)\n\t}\n\n\tsetOfIssuers := map[string]struct{}{}\n\tfor _, issuer := range cfg.Issuers {\n\t\tsetOfIssuers[issuer] = struct{}{}\n\t}\n\n\tcfg.Key.kh = kh\n\n\treturn &Cmd{\n\t\tclient: cfg.Trillian,\n\t\tvdr: cfg.VDR,\n\t\tVCLogID: sha256.Sum256(pubBytes),\n\t\tlogID: cfg.LogID,\n\t\tkms: cfg.KMS,\n\t\tkey: cfg.Key,\n\t\tcrypto: cfg.Crypto,\n\t\tissuers: setOfIssuers,\n\t}, nil\n}", "func New(ctx resource.Context, ns namespace.Instance) (Server, error) {\n\treturn newKubeServer(ctx, ns)\n}", "func (s *Scavenger) newTask(info *p.TaskListInfo) executor.Task {\n\treturn &executorTask{\n\t\ttaskListInfo: *info,\n\t\tscvg: s,\n\t}\n}", "func NewOperator(ctx *pulumi.Context,\n\tname string, args *OperatorArgs, opts ...pulumi.ResourceOption) (*Operator, error) {\n\tif args == nil {\n\t\targs = &OperatorArgs{}\n\t}\n\targs.ApiVersion = pulumi.StringPtr(\"deploy.hybridapp.io/v1alpha1\")\n\targs.Kind = pulumi.StringPtr(\"Operator\")\n\tvar resource Operator\n\terr := ctx.RegisterResource(\"kubernetes:deploy.hybridapp.io/v1alpha1:Operator\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(mgr manager.Manager, operatorNamespace, operandNamespace string) (runtimecontroller.Controller, error) {\n\toperatorCache := mgr.GetCache()\n\treconciler := &reconciler{\n\t\tclient: mgr.GetClient(),\n\t\tcache: operatorCache,\n\t\trecorder: mgr.GetEventRecorderFor(controllerName),\n\t\toperatorNamespace: operatorNamespace,\n\t\toperandNamespace: operandNamespace,\n\t}\n\tc, err := runtimecontroller.New(controllerName, mgr, runtimecontroller.Options{Reconciler: reconciler})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Index ingresscontrollers over the default certificate name so that\n\t// secretToIngressController can look up ingresscontrollers that\n\t// reference the secret.\n\tif err := operatorCache.IndexField(context.Background(), &operatorv1.IngressController{}, \"defaultCertificateName\", client.IndexerFunc(func(o client.Object) []string {\n\t\tsecret := controller.RouterEffectiveDefaultCertificateSecretName(o.(*operatorv1.IngressController), operandNamespace)\n\t\treturn []string{secret.Name}\n\t})); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create index for ingresscontroller: %v\", err)\n\t}\n\n\tsecretsInformer, err := operatorCache.GetInformer(context.Background(), &corev1.Secret{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create informer for secrets: %v\", err)\n\t}\n\tif err := c.Watch(&source.Informer{Informer: secretsInformer}, handler.EnqueueRequestsFromMapFunc(reconciler.secretToIngressController)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Watch(source.Kind(operatorCache, &operatorv1.IngressController{}), &handler.EnqueueRequestForObject{}, predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t\tDeleteFunc: func(e event.DeleteEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t\tUpdateFunc: func(e event.UpdateEvent) bool { return reconciler.secretChanged(e.ObjectOld, e.ObjectNew) },\n\t\tGenericFunc: func(e event.GenericEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t}, predicate.NewPredicateFuncs(func(o client.Object) bool {\n\t\treturn reconciler.hasClusterIngressDomain(o) || isDefaultIngressController(o)\n\t})); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func New(clientset *kubernetes.Clientset, config *restclient.Config, namespace, deploymentName string, remotePort, localPort int) (*k8s.Tunnel, error) {\n\tpodName, err := getServerPodName(clientset, namespace, deploymentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"found pod: %s\", podName)\n\n\tt := k8s.NewTunnel(clientset.CoreV1().RESTClient(), config, namespace, podName, remotePort)\n\treturn t, t.ForwardPort(localPort)\n}", "func NewHdfsOperator(cfg OperatorConfig) (*HdfsController, error) {\n // Create an empty context\n //ctx := context.Background()\n clientConfig, err := newConfig()\n if err != nil {\n return nil, errors.Wrap(err, \"Failed to retrieve kubernetes client config\")\n }\n\n clientSet, err := kubernetes.NewForConfig(clientConfig)\n if err != nil {\n return nil, errors.Wrap(err, \"Failed to create Kubernetes client\")\n }\n\n/*\n restClient, err := NewClientForConfig(clientConfig)\n if err != nil {\n return nil, errors.Wrap(err, \"Failed to create REST client\")\n }\n*/\n\n controller := &HdfsController{\n ClientSet: clientSet,\n //restClient: restClient,\n cfg: &cfg,\n }\n\n\treturn controller, nil\n}", "func New(auth aws.Auth, region aws.Region) *ECS {\n\treturn &ECS{auth, region}\n}", "func New(b []byte) (*Exec, error) {\n\tf, err := open(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Exec{f: f}, nil\n}", "func New(file string) ComposeFile {\n\tresult := ComposeFile{\n\t\tFile: []string{file},\n\t\tData: DockerCompose{\n\t\t\tVersion: \"3.7\",\n\t\t\tServices: make(map[string]*Service),\n\t\t},\n\t}\n\treturn result\n}", "func NewHyperpilotOperator(kclient *kubernetes.Clientset, controllers []EventProcessor, config *viper.Viper) (*HyperpilotOperator, error) {\n\tbaseControllers := []BaseController{}\n\tresourceEnums := []ResourceEnum{}\n\tfor _, controller := range controllers {\n\t\tbaseController, ok := controller.(BaseController)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Unable to cast controller to BaseController\")\n\t\t}\n\t\tbaseControllers = append(baseControllers, baseController)\n\t\tresourceEnums = append(resourceEnums, baseController.GetResourceEnum())\n\t}\n\n\thpc := &HyperpilotOperator{\n\t\tpodRegisters: make([]*EventReceiver, 0),\n\t\tnodeRegisters: make([]*EventReceiver, 0),\n\t\tdaemonSetRegisters: make([]*EventReceiver, 0),\n\t\tdeployRegisters: make([]*EventReceiver, 0),\n\t\trsRegisters: make([]*EventReceiver, 0),\n\t\tcontrollers: baseControllers,\n\t\tkclient: kclient,\n\t\tclusterState: common.NewClusterState(),\n\t\tstate: operatorNotRunning,\n\t\tconfig: config,\n\t}\n\n\treturn hpc, nil\n}", "func New(executor GetExecutor, lc logger.LoggingClient) *get {\n\treturn &get{\n\t\texecutor: executor,\n\t\tloggingClient: lc,\n\t}\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 New(config *Config) (*Operation, error) {\n\top := &Operation{\n\t\tstore: &stores{\n\t\t\tcookies: cookie.NewStore(config.Cookie),\n\t\t},\n\t\ttlsConfig: config.TLSConfig,\n\t\thttpClient: &http.Client{Transport: &http.Transport{TLSClientConfig: config.TLSConfig}},\n\t\twebauthn: config.Webauthn,\n\t\twalletDashboard: config.WalletDashboard,\n\t\thubAuthURL: config.HubAuthURL,\n\t}\n\n\tvar err error\n\n\tprotocol.RegisterAttestationFormat(\"apple\", ValidateAppleAttestation)\n\n\top.store.storage, err = store.Open(config.Storage.Storage, deviceStoreName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open store: %w\", err)\n\t}\n\n\top.store.session, err = session.NewStore()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create web auth protocol session store: %w\", err)\n\t}\n\n\top.store.users, err = user.NewStore(config.Storage.Storage)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open users store: %w\", err)\n\t}\n\n\treturn op, nil\n}", "func NewRegistry(\n\tparams libfsm.ExecutorParams,\n\tclusterApp loc.Locator,\n\tclusterApps app.Applications,\n\tclusterPackages pack.PackageService,\n\tsilent localenv.Silent,\n\tlogger log.FieldLogger,\n) (libfsm.PhaseExecutor, error) {\n\tstateDir, err := state.GetStateDir()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\timageService, err := docker.NewImageService(docker.RegistryConnectionRequest{\n\t\tRegistryAddress: defaults.LocalRegistryAddr,\n\t\tCertName: defaults.DockerRegistry,\n\t\tCACertPath: state.Secret(stateDir, defaults.RootCertFilename),\n\t\tClientCertPath: state.Secret(stateDir, \"kubelet.cert\"),\n\t\tClientKeyPath: state.Secret(stateDir, \"kubelet.key\"),\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tpruner, err := registry.New(registry.Config{\n\t\tApp: &clusterApp,\n\t\tApps: clusterApps,\n\t\tPackages: clusterPackages,\n\t\tImageService: imageService,\n\t\tConfig: prune.Config{\n\t\t\tSilent: silent,\n\t\t\tFieldLogger: logger,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &registryExecutor{\n\t\tFieldLogger: logger,\n\t\tPruner: pruner,\n\t\tsilent: silent,\n\t}, nil\n}", "func Create(input CreateInput) *corev1.Pod {\n\tExpect(input.Creator).NotTo(BeNil(), \"input.Creator is required for Pod.Create\")\n\tExpect(input.Config).NotTo(BeNil(), \"input.Config is required for Pod.Create\")\n\tExpect(input.Name).NotTo(BeEmpty(), \"input.Name is required for Pod.Create\")\n\tExpect(input.Namespace).NotTo(BeEmpty(), \"input.Namespace is required for Pod.Create\")\n\tExpect(input.SecretProviderClassName).NotTo(BeEmpty(), \"input.SecretProviderClassName is required for Pod.Create\")\n\n\tBy(fmt.Sprintf(\"Creating Pod \\\"%s\\\"\", input.Name))\n\n\treadOnly := true\n\tpod := &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: input.Name,\n\t\t\tNamespace: input.Namespace,\n\t\t\tLabels: input.Labels,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tTerminationGracePeriodSeconds: to.Int64Ptr(int64(0)),\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"tester\",\n\t\t\t\t\tImage: \"registry.k8s.io/e2e-test-images/busybox:1.29-4\",\n\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\tCommand: []string{\"/bin/sleep\", \"10000\"},\n\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"secrets-store-inline\",\n\t\t\t\t\t\t\tMountPath: \"/mnt/secrets-store\",\n\t\t\t\t\t\t\tReadOnly: true,\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\tVolumes: []corev1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: \"secrets-store-inline\",\n\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\tCSI: &corev1.CSIVolumeSource{\n\t\t\t\t\t\t\tDriver: \"secrets-store.csi.k8s.io\",\n\t\t\t\t\t\t\tReadOnly: &readOnly,\n\t\t\t\t\t\t\tVolumeAttributes: map[string]string{\"secretProviderClass\": input.SecretProviderClassName},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif input.NodePublishSecretRefName != \"\" {\n\t\tfor idx := range pod.Spec.Volumes {\n\t\t\tpod.Spec.Volumes[idx].CSI.NodePublishSecretRef = &corev1.LocalObjectReference{Name: input.NodePublishSecretRefName}\n\t\t}\n\t}\n\n\tif input.Config.IsWindowsTest {\n\t\tpod.Spec.NodeSelector = map[string]string{\"kubernetes.io/os\": \"windows\"}\n\t} else if input.Config.IsGPUTest {\n\t\tpod.Spec.NodeSelector = map[string]string{\n\t\t\t\"kubernetes.io/os\": \"linux\",\n\t\t\t\"accelerator\": \"nvidia\",\n\t\t}\n\t} else {\n\t\tpod.Spec.NodeSelector = map[string]string{\"kubernetes.io/os\": \"linux\"}\n\t}\n\n\tif input.ServiceAccountName != \"\" {\n\t\tpod.Spec.ServiceAccountName = input.ServiceAccountName\n\t}\n\n\tExpect(input.Creator.Create(context.TODO(), pod)).Should(Succeed())\n\treturn pod\n}", "func NewCompute(client *http.Client) (*Compute, error) {\n\tservice, err := compute.New(client)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create compute service: %v\", err)\n\t}\n\treturn &Compute{\n\t\tservice,\n\t\t*project,\n\t\t*zone,\n\t\t*api + \"/projects/\" + *project,\n\t}, nil\n}", "func New(n int, ctor func() Worker) *Pool {\n\tp := &Pool{\n\t\tctor: ctor,\n\t\treqChan: make(chan workRequest),\n\t}\n\tp.SetSize(n)\n\n\treturn p\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}" ]
[ "0.7574625", "0.67831236", "0.66792846", "0.66372824", "0.64599377", "0.630048", "0.621054", "0.61618245", "0.6161271", "0.6128888", "0.6096378", "0.6083967", "0.5987379", "0.5985418", "0.5979721", "0.59648883", "0.5938002", "0.59062034", "0.5869973", "0.5864622", "0.5853556", "0.58115023", "0.5810263", "0.5788569", "0.5774484", "0.5732613", "0.57084024", "0.5694307", "0.56930304", "0.5682746", "0.56733644", "0.5646148", "0.5637345", "0.55570334", "0.5552882", "0.5543006", "0.5539428", "0.54956216", "0.54920286", "0.54770863", "0.5463868", "0.54624224", "0.5432966", "0.5429519", "0.5426829", "0.5422231", "0.5398469", "0.538681", "0.5384493", "0.53844815", "0.5380348", "0.53736615", "0.53669393", "0.53667223", "0.5363028", "0.5355403", "0.5350907", "0.5346024", "0.5343065", "0.53381205", "0.5335663", "0.53280765", "0.5328028", "0.53255606", "0.5321473", "0.53129715", "0.5312798", "0.52815384", "0.52684695", "0.52596813", "0.52591276", "0.5247047", "0.5236215", "0.52330315", "0.5210867", "0.52098894", "0.52055436", "0.51964176", "0.5193379", "0.51879793", "0.51867026", "0.5181911", "0.5180709", "0.5175906", "0.5174307", "0.5169339", "0.5158364", "0.5157756", "0.5155431", "0.51451844", "0.51448053", "0.5139616", "0.5137327", "0.5132496", "0.5129298", "0.5126943", "0.51255697", "0.51225364", "0.51171815", "0.51165617" ]
0.729702
1
Registered is called when the executor is successfully registered with the slave.
func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver, executorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) { if k.isDone() { return } log.Infof("Executor %v of framework %v registered with slave %v\n", executorInfo, frameworkInfo, slaveInfo) if !(&k.state).transition(disconnectedState, connectedState) { log.Errorf("failed to register/transition to a connected state") } if executorInfo != nil && executorInfo.Data != nil { k.staticPodsConfig = executorInfo.Data } if slaveInfo != nil { _, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes)) if err != nil { log.Errorf("cannot update node labels: %v", err) } } k.initialRegistration.Do(k.onInitialRegistration) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver,\n\texecutorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Executor %v of framework %v registered with slave %v\\n\",\n\t\texecutorInfo, frameworkInfo, slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}", "func (s *eremeticScheduler) Registered(driver sched.SchedulerDriver, frameworkID *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {\n\tlog.Debugf(\"Framework %s registered with master %s\", frameworkID.GetValue(), masterInfo.GetHostname())\n\tif !s.initialised {\n\t\tdriver.ReconcileTasks([]*mesos.TaskStatus{})\n\t\ts.initialised = true\n\t} else {\n\t\ts.Reconcile(driver)\n\t}\n}", "func (master *Master) Register(args *RegisterArgs, reply *RegisterReply) error {\n\tvar (\n\t\tnewWorker *RemoteWorker\n\t)\n\tlog.Printf(\"Registering worker '%v' with hostname '%v'\", master.totalWorkers, args.WorkerHostname)\n\n\tmaster.workersMutex.Lock()\n\n\tnewWorker = &RemoteWorker{master.totalWorkers, args.WorkerHostname, WORKER_IDLE}\n\tmaster.workers[newWorker.id] = newWorker\n\tmaster.totalWorkers++\n\n\tmaster.workersMutex.Unlock()\n\n\tmaster.idleWorkerChan <- newWorker\n\n\t*reply = RegisterReply{newWorker.id, master.task.NumReduceJobs}\n\treturn nil\n}", "func (k *KubernetesScheduler) Registered(driver mesos.SchedulerDriver,\n\tframeworkId *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {\n\tk.frameworkId = frameworkId\n\tk.masterInfo = masterInfo\n\tk.registered = true\n\tlog.Infof(\"Scheduler registered with the master: %v with frameworkId: %v\\n\", masterInfo, frameworkId)\n}", "func (sched *Scheduler) Registered(driver sched.SchedulerDriver, frameworkId *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {\n\tsched.master = MasterConnStr(masterInfo)\n\tlog.Println(\"Taurus Framework Registered with Master\", sched.master)\n\t// Start the scheduler worker\n\tgo func() {\n\t\tlog.Printf(\"Starting %s framework scheduler worker\", FrameworkName)\n\t\tsched.errChan <- sched.Worker.Start(driver, masterInfo)\n\t}()\n}", "func (s *Server) Register(ctx context.Context, registration *proto.SlaveRegistration) (*proto.SlaveRegistrationResponse, error) {\n\tfor i := 0; i < int(registration.Threads); i++ {\n\t\tclient, err := createCellInteractionClient(registration.Address)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.cisClientPool.AddClient(client)\n\t\tmetrics.CISClientCount.Inc()\n\t}\n\treturn &proto.SlaveRegistrationResponse{}, nil\n}", "func (zk *ZookeeperMaster) Register() error {\n\tif err := zk.createSelfNode(); err != nil {\n\t\treturn err\n\t}\n\t//create event loop for master flag\n\tgo zk.masterLoop()\n\tgo zk.healthLoop()\n\treturn nil\n\n}", "func (s *serverRegistry) Register(*FContext, FAsyncCallback) error {\n\treturn nil\n}", "func (s *ParallelMaster) Register(workerAddress string) {\n\tatomic.AddInt32(&s.totalWorkers, 1)\n\tgo func() {\n\t\tfmt.Printf(\"Worker at %s has registered.\\n\", workerAddress)\n\t\ts.freeWorkers <- workerAddress\n\t}()\n}", "func (s *Server) Register() {\n\tdefer base.CheckPanic()\n\tfor {\n\t\tif _, err := s.MasterClient.RegisterServer(context.Background(), &protocol.Void{}); err != nil {\n\t\t\tbase.Logger().Error(\"failed to register\", zap.Error(err))\n\t\t}\n\t\ttime.Sleep(time.Duration(s.Config.Master.ClusterMetaTimeout/2) * time.Second)\n\t}\n}", "func (m *FPGADevicePluginServer) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := grpc.Dial(kubeletEndpoint, grpc.WithInsecure(),\n\t\tgrpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {\n\t\t\treturn net.DialTimeout(\"unix\", addr, timeout)\n\t\t}))\n\n\tif err != nil {\n\t\tlog.Debugf(\"Cann't connect to kubelet service\")\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\tlog.Debugf(\"Cann't register to kubelet service\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *supernodeRegister) Register(peerPort int) (*RegisterResult, *errortypes.DfError) {\n\tvar (\n\t\tresp *types.RegisterResponse\n\t\te error\n\t\ti int\n\t\tretryTimes = 0\n\t\tstart = time.Now()\n\t)\n\n\tlogrus.Infof(\"do register to one of %v\", s.cfg.Nodes)\n\tnodes, nLen := s.cfg.Nodes, len(s.cfg.Nodes)\n\treq := s.constructRegisterRequest(peerPort)\n\tfor i = 0; i < nLen; i++ {\n\t\tif s.lastRegisteredNode == nodes[i] {\n\t\t\tlogrus.Warnf(\"the last registered node is the same(%s)\", nodes[i])\n\t\t\tcontinue\n\t\t}\n\t\treq.SupernodeIP = netutils.ExtractHost(nodes[i])\n\t\tresp, e = s.api.Register(nodes[i], req)\n\t\tlogrus.Infof(\"do register to %s, res:%s error:%v\", nodes[i], resp, e)\n\t\tif e != nil {\n\t\t\tlogrus.Errorf(\"register to node:%s error:%v\", nodes[i], e)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.Code == constants.Success || resp.Code == constants.CodeNeedAuth ||\n\t\t\tresp.Code == constants.CodeURLNotReachable {\n\t\t\tbreak\n\t\t}\n\t\tif resp.Code == constants.CodeWaitAuth && retryTimes < 3 {\n\t\t\ti--\n\t\t\tretryTimes++\n\t\t\tlogrus.Infof(\"sleep 2.5s to wait auth(%d/3)...\", retryTimes)\n\t\t\ttime.Sleep(2500 * time.Millisecond)\n\t\t}\n\t}\n\ts.setLastRegisteredNode(i)\n\ts.setRemainderNodes(i)\n\tif err := s.checkResponse(resp, e); err != nil {\n\t\tlogrus.Errorf(\"register fail:%v\", err)\n\t\treturn nil, err\n\t}\n\n\tresult := NewRegisterResult(nodes[i], s.cfg.Nodes, s.cfg.URL,\n\t\tresp.Data.TaskID, resp.Data.FileLength, resp.Data.PieceSize)\n\n\tlogrus.Infof(\"do register result:%s and cost:%.3fs\", resp,\n\t\ttime.Since(start).Seconds())\n\treturn result, nil\n}", "func (s *SequentialMaster) Register(workerAddress string) {\n\tpanic(\"Registration should not occur in sequential master!\")\n}", "func (r *Registrator) Register(port int, reg quantum.Registry) error {\n\tfor _, t := range reg.Types() {\n\t\tr.Jobs[t] = \"0.0.0.0:\" + strconv.Itoa(port)\n\t}\n\n\treturn nil\n}", "func registeredCB(\n ptr unsafe.Pointer,\n frameworkMessage *C.ProtobufObj,\n masterMessage *C.ProtobufObj) {\n if (ptr != nil) {\n var driver *SchedulerDriver = (*SchedulerDriver)(ptr)\n\n if (driver.Scheduler.Registered == nil) {\n return\n }\n\n frameworkData := C.GoBytes(\n frameworkMessage.data,\n C.int(frameworkMessage.size))\n\n var frameworkId FrameworkID\n err := proto.Unmarshal(frameworkData, &frameworkId); if err != nil {\n return\n }\n\n masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))\n var masterInfo MasterInfo\n err = proto.Unmarshal(masterData, &masterInfo); if err != nil {\n return\n }\n\n driver.Scheduler.Registered(driver, frameworkId, masterInfo)\n }\n}", "func registerSlave(addr, username, password string, serverID uint32) (*client.Conn, error) {\n\tconn, err := client.Connect(addr, username, password, \"\", func(c *client.Conn) {\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"connect to the master\")\n\t}\n\n\t// takes as an indication that the client is checksum-aware.\n\t// ref https://dev.mysql.com/doc/refman/8.0/en/c-api-binary-log-functions.html.\n\t_, err = conn.Execute(`SET @master_binlog_checksum='NONE'`)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, `SET @master_binlog_checksum='NONE'`)\n\t}\n\n\tconn.ResetSequence()\n\tpacket := registerSlaveCommand(username, password, serverID)\n\terr = conn.WritePacket(packet)\n\tif err != nil {\n\t\treturn nil, errors.Annotatef(err, \"write COM_REGISTER_SLAVE packet %v\", packet)\n\t}\n\n\t_, err = conn.ReadOKPacket()\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"read OK packet\")\n\t}\n\n\treturn conn, nil\n}", "func (m *CambriconDevicePlugin) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t\tOptions: &pluginapi.DevicePluginOptions{\n\t\t\tGetPreferredAllocationAvailable: m.options.Mode == topologyAware,\n\t\t},\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Server) Register(rcvr interface{}, metadata string) error {\n\tsname, err := s.register(rcvr, \"\", false)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.Plugins.DoRegister(sname, rcvr, metadata)\n}", "func (rs *RegistryService) Register(ctx context.Context, in *proto.RegisterType) (*proto.EmptyResponse, error) {\n\trs.mu.RLock()\n\tdefer rs.mu.RUnlock()\n\n\trs.hosts[in.GetName()] = in.GetHost()\n\n\treturn &proto.EmptyResponse{}, nil\n}", "func (c *Client) Register(idx int) {\n\tvar id int\n\terr := c.rpcServers[idx].Call(\"Server.Register\", c.myServer, &id)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't register: \", err)\n\t}\n\tc.id = id\n}", "func (s *Server) Register(srv pb.Proxy_RegisterServer) error {\n\tctx := srv.Context()\n\tname, err := getMetadata(ctx, \"provider\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tp := provider{\n\t\trequest: make(chan *pb.FileRequest),\n\t\tcallbacks: make(map[string]callbackFunc),\n\t}\n\ts.Lock()\n\ts.providers[name] = p\n\ts.Unlock()\n\tlog.Printf(\"registered: %s\\n\", name)\n\tlog.Printf(\"starting provider %s\\n\", name)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase r, ok := <-p.request:\n\t\t\t\tlog.Printf(\"request for %s@%s received\\n\", r.Path, r.Provider)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Printf(\"request channel of provider %s closed\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := srv.Send(r); err != nil {\n\t\t\t\t\tlog.Printf(\"send failed: %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tfor {\n\t\tm, err := srv.Recv()\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\treturn fmt.Errorf(\"provider %s closed\", name)\n\t\tcase nil:\n\t\t\tp.callbacks[m.Line.Key](m.Line)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"failed to receive from provider %s: %v\", name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (w *worker) register() {\n\targs := &RegisterArgs{}\n\treply := &RegisterArgs{}\n\n\tif ok := call(\"Master.RegisterWorker\", args, reply); !ok {\n\t\tlog.Fatal(\"Register of worker failed\")\n\t}\n\tw.id = reply.WorkerId\n}", "func (s *GRPCServer) Register(ctx context.Context, registerRequest *dashboard.RegisterRequest) (*dashboard.RegisterResponse, error) {\n\tm, err := s.Impl.Register(ctx, registerRequest.DashboardAPIAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcapabilities := convertFromCapabilities(m.Capabilities)\n\n\treturn &dashboard.RegisterResponse{\n\t\tPluginName: m.Name,\n\t\tDescription: m.Description,\n\t\tCapabilities: &capabilities,\n\t}, nil\n}", "func (node *DataNode) Register() error {\n\tnode.session.Register()\n\n\tmetrics.NumNodes.WithLabelValues(fmt.Sprint(paramtable.GetNodeID()), typeutil.DataNodeRole).Inc()\n\tlog.Info(\"DataNode Register Finished\")\n\t// Start liveness check\n\tnode.session.LivenessCheck(node.ctx, func() {\n\t\tlog.Error(\"Data Node disconnected from etcd, process will exit\", zap.Int64(\"Server Id\", node.GetSession().ServerID))\n\t\tif err := node.Stop(); err != nil {\n\t\t\tlog.Fatal(\"failed to stop server\", zap.Error(err))\n\t\t}\n\t\tmetrics.NumNodes.WithLabelValues(fmt.Sprint(paramtable.GetNodeID()), typeutil.DataNodeRole).Dec()\n\t\t// manually send signal to starter goroutine\n\t\tif node.session.TriggerKill {\n\t\t\tif p, err := os.FindProcess(os.Getpid()); err == nil {\n\t\t\t\tp.Signal(syscall.SIGINT)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn nil\n}", "func (h *RpcHandler) RegisterNode(nodeInfo *core.NodeInfo, reply *packet.RpcReply) error {\n\tlogTitle := \"RpcServer.RegisterNode[\" + nodeInfo.EndPoint() + \"] \"\n\tif !h.getNode().IsLeader() {\n\t\tlogger.Rpc().Warn(logTitle + \"can not register to not leader node\")\n\t\t*reply = packet.FailedReply(-1001, \"can not register to not leader node\")\n\t\treturn nil\n\t}\n\n\tresult := h.getNode().Cluster.AddNodeInfo(nodeInfo)\n\tif result.Error != nil {\n\t\tlogger.Rpc().DebugS(logTitle+\"error:\", result.Error.Error())\n\t\t*reply = packet.FailedReply(-2001, result.Message())\n\t} else {\n\t\tif !result.IsSuccess() {\n\t\t\tlogger.Rpc().DebugS(logTitle+\"failed, \", result.Message())\n\t\t\t*reply = packet.FailedReply(-2002, result.Message())\n\t\t} else {\n\t\t\tlogger.Rpc().DebugS(logTitle+\"success,\", nodeInfo.Json())\n\t\t\t*reply = packet.SuccessRpcReply(len(h.getNode().Runtime.Executors))\n\t\t}\n\t}\n\treturn nil\n}", "func (t *targetrunner) register() error {\n\tjsbytes, err := json.Marshal(t.si)\n\tif err != nil {\n\t\tglog.Errorf(\"Unexpected failure to json-marshal %+v, err: %v\", t.si, err)\n\t\treturn err\n\t}\n\turl := ctx.config.Proxy.URL + \"/\" + Rversion + \"/\" + Rcluster\n\t_, err = t.call(url, http.MethodPost, jsbytes)\n\treturn err\n}", "func (e *Extension) Registered(extensionName string, client *bayeux.BayeuxClient) {\n}", "func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to reregister/transition to a connected state\")\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes))\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tk.initialRegistration.Do(k.onInitialRegistration)\n}", "func (s SwxProxy) Register(_ context.Context, _ *protos.RegistrationRequest) (*protos.RegistrationAnswer, error) {\n\treturn &protos.RegistrationAnswer{}, nil\n}", "func (s *serverRegistry) Execute(frame []byte) error {\n\ttr := &thrift.TMemoryBuffer{Buffer: bytes.NewBuffer(frame)}\n\treturn s.processor.Process(s.inputProtocolFactory.GetProtocol(tr), s.outputProtocol)\n}", "func serverRegister() {\n\t// set the parameters to register\n\tbytePublicKey, _ := anonServer.PublicKey.MarshalBinary()\n\tparams := map[string]interface{}{\n\t\t\"public_key\": bytePublicKey,\n\t}\n\tevent := &proto.Event{EventType:proto.SERVER_REGISTER, Params:params}\n\n\tutil.SendEvent(anonServer.LocalAddr, anonServer.CoordinatorAddr, event)\n}", "func (m *WidgetDevicePlugin) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Parallel) Register(f interface{}, args ...interface{}) *Handler {\n\treturn p.NewPipeline().Register(f, args...)\n}", "func (r *Registrar) RegisterPlugin(info Info, cookie *string) error {\n\tregLog.Info(\"Received registration request. Signalling registrar.\")\n\n\treplyCh := make(chan regReply, 1)\n\tdefer close(replyCh)\n\tr.ch <- regRequest{Info: info, replyCh: replyCh}\n\n\tregLog.Info(\"Waiting for response from registrar...\")\n\treply := <-replyCh\n\n\tregLog.Info(\"Plugin \\\"%s\\\" registered with cookie \\\"%s\\\"\",\n\t\tinfo.Name, reply.cookie)\n\t(*cookie) = reply.cookie\n\treturn reply.err\n}", "func (w *Wrapper) registrationComplete() (bool, error) {\n\tpath := filepath.Join(w.cfg.RootDir, shardRegMarker)\n\t_, err := os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (a *Client) Register(params *RegisterParams) (*RegisterOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRegisterParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"register\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/subjects/{subject}/versions\",\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: &RegisterReader{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.(*RegisterOK)\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 register: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *clientRegistry) Register(ctx *FContext, callback FAsyncCallback) error {\n\topID := ctx.opID()\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\t_, ok := c.handlers[opID]\n\tif ok {\n\t\treturn errors.New(\"frugal: context already registered\")\n\t}\n\topID = atomic.AddUint64(&nextOpID, 1)\n\tctx.setOpID(opID)\n\tc.handlers[opID] = callback\n\treturn nil\n}", "func register(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :https://anex.us/register/\"\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func (follower *Follower) Register(leaderHost string) (err error) {\n\tlog.Printf(\"Registring with Leader...\\n\")\n\tconn, err := net.Dial(\"tcp\", leaderHost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmessage := &Message{\n\t\tAction: Message_REGISTER.Enum(),\n\n\t\tId: follower.id[:],\n\t\tHost: proto.String(follower.host),\n\t}\n\n\tdata, err := proto.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := conn.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Resolver) Register(name string, e Extension) bool {\n\tr.Execers[name] = e\n\treturn true\n}", "func (rbc *RegisterBrokerCmd) Run() error {\n\tresultBroker, location, err := rbc.Client.RegisterBroker(&rbc.broker, &rbc.Parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(location) != 0 {\n\t\tcmd.CommonHandleAsyncExecution(rbc.Context, location, fmt.Sprintf(\"Service Broker %s successfully scheduled for registration. To see status of the operation use:\\n\", rbc.broker.Name))\n\t\treturn nil\n\t}\n\toutput.PrintServiceManagerObject(rbc.Output, rbc.outputFormat, resultBroker)\n\toutput.Println(rbc.Output)\n\treturn nil\n}", "func (t *targetrunner) register(timeout time.Duration) (int, error) {\n\tvar newbucketmd bucketMD\n\tjsbytes, err := json.Marshal(t.si)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Unexpected failure to json-marshal %+v, err: %v\", t.si, err)\n\t}\n\n\turl, si := t.getPrimaryURLAndSI()\n\turl += \"/\" + Rversion + \"/\" + Rcluster\n\n\tvar res callResult\n\tif timeout > 0 { // keepalive\n\t\turl += \"/\" + Rkeepalive\n\t\tres = t.call(nil, si, url, http.MethodPost, jsbytes, timeout)\n\t} else {\n\t\tres = t.call(nil, si, url, http.MethodPost, jsbytes)\n\t}\n\tif res.err != nil {\n\t\treturn res.status, res.err\n\t}\n\t// not being sent at cluster startup and keepalive..\n\tif len(res.outjson) > 0 {\n\t\terr := json.Unmarshal(res.outjson, &newbucketmd)\n\t\tassert(err == nil, err)\n\t\tt.bmdowner.Lock()\n\t\tv := t.bmdowner.get().version()\n\t\tif v > newbucketmd.version() {\n\t\t\tglog.Errorf(\"register target - got bucket-metadata: local version %d > %d\", v, newbucketmd.version())\n\t\t} else {\n\t\t\tglog.Infof(\"register target - got bucket-metadata: upgrading local version %d to %d\", v, newbucketmd.version())\n\t\t}\n\t\tt.bmdowner.put(&newbucketmd)\n\t\tt.bmdowner.Unlock()\n\t}\n\treturn res.status, res.err\n}", "func Register() map[string]string {\n\treturn map[string]string{\n\t\t\"name\": \"Beubo gRPC\",\n\t\t// identifier should be a unique identifier used to differentiate this plugin from other plugins\n\t\t\"identifier\": \"beubo_grpc\",\n\t}\n}", "func (c *Cluster) Register(node *NodeInfo) error {\n\tc.sessionManager.AddSession(node)\n\treturn c.channelManager.AddNode(node.NodeID)\n}", "func (p *NacosRegisterPlugin) Register(name string, rcvr interface{}, metadata string) (err error) {\r\n\tif strings.TrimSpace(name) == \"\" {\r\n\t\treturn errors.New(\"Register service `name` can't be empty\")\r\n\t}\r\n\r\n\tnetwork, ip, port, err := util.ParseRpcxAddress(p.ServiceAddress)\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"failed to parse rpcx addr in Register: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\r\n\tmeta := util.ConvertMeta2Map(metadata)\r\n\tmeta[\"network\"] = network\r\n\r\n\tinst := vo.RegisterInstanceParam{\r\n\t\tIp: ip,\r\n\t\tPort: uint64(port),\r\n\t\tServiceName: name,\r\n\t\tMetadata: meta,\r\n\t\tClusterName: p.Cluster,\r\n\t\tGroupName: p.Group,\r\n\t\tWeight: p.Weight,\r\n\t\tEnable: true,\r\n\t\tHealthy: true,\r\n\t\tEphemeral: true,\r\n\t}\r\n\r\n\t_, err = p.namingClient.RegisterInstance(inst)\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"failed to register %s: %v\", name, err)\r\n\t\treturn err\r\n\t}\r\n\r\n\tp.Services = append(p.Services, name)\r\n\r\n\treturn\r\n}", "func (local *Node) Register(key string, replica RemoteNode) (isRoot bool) {\n\t// TODO: students should implement this\n\treturn\n}", "func (c *GRPCClient) Register(ctx context.Context, dashboardAPIAddress string) (Metadata, error) {\n\tvar m Metadata\n\n\terr := c.run(func() error {\n\t\tregisterRequest := &dashboard.RegisterRequest{\n\t\t\tDashboardAPIAddress: dashboardAPIAddress,\n\t\t}\n\n\t\tresp, err := c.client.Register(ctx, registerRequest)\n\t\tif err != nil {\n\t\t\tspew.Dump(err)\n\t\t\treturn errors.WithMessage(err, \"unable to call register function\")\n\t\t}\n\n\t\tcapabilities := convertToCapabilities(resp.Capabilities)\n\n\t\tm = Metadata{\n\t\t\tName: resp.PluginName,\n\t\t\tDescription: resp.Description,\n\t\t\tCapabilities: capabilities,\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\treturn m, nil\n}", "func (c *SubChannel) Register(h Handler, methodName string) {\n\tr, ok := c.handler.(registrar)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"handler for SubChannel(%v) configured with alternate root handler without Register method\",\n\t\t\tc.ServiceName(),\n\t\t))\n\t}\n\n\tr.Register(h, methodName)\n}", "func (reg *registrar) Register(example interface{}) error {\n\treg.lock.Lock()\n\tdefer reg.lock.Unlock()\n\treturn reg.Registry.Register(example)\n}", "func (rc *RedisComponent) Register(conn redis.Conn, msgStream *chan string) {\n\trc.conn = conn\n\trc.msgStream = msgStream\n\trc.dataStream = make(chan Event)\n}", "func (v *Bridge) RegisterExecutor(name string, exec Executor) VirtualMachine {\n\twraper := &vmImpl{\n\t\tstate: v.state,\n\t\tname: name,\n\t\texec: exec,\n\t}\n\texec.RegisterSyscallService(v.syscall)\n\tv.vms[name] = wraper\n\treturn wraper\n}", "func Register(srv *grpc.Server) {\n\tglobal.Register(srv)\n}", "func (server *Server) Register(retrySvr interface{}) (err error) {\n\t// Find all the methods associated with retrySvr and put into serviceMap\n\tserver.receiver = reflect.ValueOf(retrySvr)\n\treturn server.register(retrySvr)\n}", "func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}", "func (server *Server) Register(action INetworkAction) {\n\n}", "func (dscMgr *DSCMgrRc) CompleteRegistration() {\n\tif featureflags.IsOVerlayRoutingEnabled() == false {\n\t\treturn\n\t}\n\n\tdscMgr.sm.SetDistributedServiceCardReactor(dscMgr)\n\tdscMgr.sm.EnableSelectivePushForKind(\"DSCConfig\")\n}", "func (a *Client) Register(params *RegisterParams) (*RegisterOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRegisterParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"register\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/subjects/{subject}/versions\",\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: &RegisterReader{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.(*RegisterOK), nil\n\n}", "func (ss *storageServer) RegisterServer(args *storagerpc.RegisterArgs, reply *storagerpc.RegisterReply) error {\n\n\tss.registerLock.Lock()\n\tdefer ss.registerLock.Unlock()\n\n\tok := ss.initializer.Register(args.ServerInfo)\n\n\tif ok {\n\t\tss.nodes = ss.initializer.Flush()\n\t\tss.rangeChecker = nodes.NewNodeCollection(ss.nodes).RangeChecker(ss.selfNode.NodeID)\n\n\t\t*reply = storagerpc.RegisterReply{\n\t\t\tStatus: storagerpc.OK,\n\t\t\tServers: ss.nodes,\n\t\t}\n\t\tif !ss.ready {\n\t\t\tss.initConfChan <- nil\n\t\t}\n\t} else {\n\t\t*reply = storagerpc.RegisterReply{\n\t\t\tStatus: storagerpc.NotReady,\n\t\t\tServers: nil,\n\t\t}\n\t}\n\n\t// CAUTION! might have to return error\n\treturn nil\n\n}", "func (e *EnterpriseEndpoints) Register(s *rpc.Server) {}", "func (e *Client) Register(ctx context.Context, filename string) (*RegisterResponse, error) {\n\tconst action = \"/register\"\n\turl := e.baseURL + action\n\n\treqBody, err := json.Marshal(map[string]interface{}{\n\t\t\"events\": []EventType{Invoke, Shutdown},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpReq, err := http.NewRequestWithContext(ctx, \"POST\", url, bytes.NewBuffer(reqBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpReq.Header.Set(extensionNameHeader, filename)\n\thttpRes, err := e.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif httpRes.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"request failed with status %s\", httpRes.Status)\n\t}\n\tdefer httpRes.Body.Close()\n\tbody, err := ioutil.ReadAll(httpRes.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := RegisterResponse{}\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\te.ExtensionID = httpRes.Header.Get(extensionIdentiferHeader)\n\tfmt.Println(\"Extension id:\", e.ExtensionID)\n\treturn &res, nil\n}", "func (tqsc *Controller) Register() {\n}", "func NewRegistration(env environment.Env, queueExecutorServer scpb.QueueExecutorServer, executorID string, options *Options) (*Registration, error) {\n\tnode, err := makeExecutionNode(executorID, options)\n\tif err != nil {\n\t\treturn nil, status.InternalErrorf(\"Error determining node properties: %s\", err)\n\t}\n\tapiKey := env.GetConfigurator().GetExecutorConfig().APIKey\n\tif options.APIKeyOverride != \"\" {\n\t\tapiKey = options.APIKeyOverride\n\t}\n\n\tshutdownSignal := make(chan struct{})\n\tenv.GetHealthChecker().RegisterShutdownFunction(func(ctx context.Context) error {\n\t\tclose(shutdownSignal)\n\t\treturn nil\n\t})\n\n\tregistration := &Registration{\n\t\tschedulerClient: env.GetSchedulerClient(),\n\t\tqueueExecutorServer: queueExecutorServer,\n\t\tnode: node,\n\t\tapiKey: apiKey,\n\t\tshutdownSignal: shutdownSignal,\n\t}\n\tenv.GetHealthChecker().AddHealthCheck(\"registered_to_scheduler\", registration)\n\treturn registration, nil\n}", "func (g *GrpcClient) Register(request *protofiles.RegisterRequest) (*protofiles.RegisterResponse, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), g.connectionTimeoutSecs)\n\tdefer cancel()\n\n\treturn g.client.Register(ctx, request)\n}", "func (m *Monocular) Register(echoContext echo.Context) error {\n\tlog.Debug(\"Helm Repository Register...\")\n\treturn m.portalProxy.RegisterEndpoint(echoContext, m.Info)\n}", "func (s *Server) DoRegister(server *grpc.Server) {\n\tpb.RegisterMonitorServiceServer(server, s)\n}", "func (server *rpcServer) Register(rcvr interface{}) {\n\tname := reflect.Indirect(reflect.ValueOf(rcvr)).Type().Name()\n\tserver.RegisterName(name, rcvr)\n}", "func (communication *Wrapper) Register() common.SyncServiceError {\n\tcomm, err := communication.selectCommunicator(common.Configuration.CommunicationProtocol, \"\", \"\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn comm.Register()\n}", "func (s NoUseSwxProxy) Register(\n\tctx context.Context,\n\treq *protos.RegistrationRequest,\n) (*protos.RegistrationAnswer, error) {\n\treturn &protos.RegistrationAnswer{}, fmt.Errorf(\"Register is NOT IMPLEMENTED\")\n}", "func (s *Subscription) Register(ctx context.Context) <-chan struct{} {\n\treturn s.c\n}", "func (s *AuthServer) Register(ctx context.Context, r *pb.RegisterRequest) (*pb.RegisterResponse, error) {\n\tusername := r.GetUsername()\n\temail := r.GetEmail()\n\tpassword := r.GetPassword()\n\tregisterResponse := actions.Register(username, email, password)\n\treturn &pb.RegisterResponse{Ok: registerResponse}, nil\n}", "func Register(cb func(string)) {\n\tcallbacks = append(callbacks, cb)\n}", "func (r *RouteInfo) RegisterServer(clusterName, serverAddr, serverName, haServerAddr string, serverId int, conn gnet.Conn) *namesrv.RegisterResponse {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tresult := &namesrv.RegisterResponse{}\n\n\tserverNames := r.clusterAddrTable[clusterName]\n\tif serverNames == nil {\n\t\tserverNames = hashset.New()\n\t\tr.clusterAddrTable[clusterName] = serverNames\n\t}\n\tserverNames.Add(serverName)\n\tregisterFirst := false\n\tserverData := r.serverAddrTable[serverName]\n\tif serverData == nil {\n\t\tregisterFirst = true\n\t\tserverData = protocol.NewServer(clusterName, serverName, make(map[int]string))\n\t\tr.serverAddrTable[serverName] = serverData\n\t}\n\tserverAddrsMap := serverData.GetServerAddrs()\n\t//Switch slave to master: first remove <1, IP:PORT> in namesrv, then add <0, IP:PORT>\n\t//The same IP:PORT must only have one record in serverAddrTable\n\tfor k, v := range serverAddrsMap {\n\t\tif serverAddr != \"\" && serverAddr == v && serverId != k {\n\t\t\tdelete(serverAddrsMap, k)\n\t\t}\n\t}\n\n\toldAddr := serverData.GetServerAddrs()[serverId]\n\tserverData.GetServerAddrs()[serverId] = serverAddr\n\tregisterFirst = registerFirst || \"\" == oldAddr\n\n\tprevServerLiveInfo := r.serverLiveTable[serverAddr]\n\tls := protocol.NewLiveServer(time.Now().Unix(), haServerAddr, nil, conn)\n\tr.serverLiveTable[serverAddr] = ls\n\tif prevServerLiveInfo == nil {\n\t\tlogger.Logger.WithFields(logrus.Fields{\n\t\t\t\"serverLiveTable\": r.serverLiveTable,\n\t\t\t\"serverAddr\": serverAddr,\n\t\t\t\"clusterAddrTable\": r.clusterAddrTable,\n\t\t}).Warn(\"prevServerLiveInfo is nil\")\n\t}\n\tif MasterId != serverId {\n\t\tmasterAddr := serverData.GetServerAddrs()[MasterId]\n\t\tif masterAddr != \"\" {\n\t\t\tserverLiveInfo := r.serverLiveTable[masterAddr]\n\t\t\tif serverLiveInfo != nil {\n\t\t\t\tresult.HaServerAddr = serverLiveInfo.HaServerAddr\n\t\t\t\tresult.MasterAddr = masterAddr\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func (_DelegateProfile *DelegateProfileCaller) Registered(opts *bind.CallOpts, _addr common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _DelegateProfile.contract.Call(opts, out, \"registered\", _addr)\n\treturn *ret0, err\n}", "func Register(ch chan ExecutionEvent, topics ...Topic) {\n\tfor _, t := range topics {\n\t\tsubscriberRegistry[t] = append(subscriberRegistry[t], ch)\n\t}\n}", "func (p *Pupil) register(_sock *mangos.Socket) {\n\tsock := *_sock\n\tvar err error\n\tlog.Printf(\"Registering with master at %s\\n\", p.MasterCommandURL)\n\tif err = sock.Dial(p.MasterCommandURL); err != nil {\n\t\tlog.Fatalf(\"Wasn't able to reach the monk master at %s - %s\", p.MasterCommandURL, err.Error())\n\t}\n\t// We need to receive this only once\n\tvar regMessage []byte\n\tregMessage, err = messages.MarshalCommand(\"register\", p)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't prepare registation command\")\n\t}\n\terr = messages.SendCommand(&sock, regMessage)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't send registration request\\n\")\n\t}\n\tvar msg []byte\n\tmsg, err = sock.Recv()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error on registering with the monk master - %s\\n\", err.Error())\n\t}\n\tresp := unpackResponse(msg)\n\tif !resp.Success() {\n\t\tlog.Fatalf(\"Couldn't register with the master - %s\\n\", resp.Message())\n\t}\n}", "func Register(\n\tc *gin.Context,\n\tuserService service.UserCommander,\n\tdispatcher queue.Publisher,\n) {\n\tvar req ar.RegisterRequest\n\tif isValid, errors := validation.ValidateRequest(c, &req); !isValid {\n\t\thttp.BadRequest(c, http.Errors(errors))\n\t\treturn\n\t}\n\n\tuser, err := userService.Create(c.Request.Context(), request.UserCreateRequest{\n\t\tFirstName: req.FirstName,\n\t\tLastName: req.LastName,\n\t\tEmail: req.Email,\n\t\tPassword: req.Password,\n\t\tRole: identityEntity.RoleConsumer,\n\t})\n\n\tif err != nil {\n\t\thttp.BadRequest(c, http.Errors{err.Error()})\n\t\treturn\n\t}\n\n\traiseSuccessfulRegistration(user.GetID(), dispatcher)\n\n\thttp.Created(c, http.Data{\n\t\t\"User\": user,\n\t}, nil)\n}", "func (c *Component) Register() {}", "func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error {\n\tbody, err := GenerateNodeReqBody(UID, nodeselector)\n\tif err != nil {\n\t\tFatalf(\"Unmarshal body failed: %v\", err)\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\n\tt := time.Now()\n\tnodebody, err := json.Marshal(body)\n\tif err != nil {\n\t\tFatalf(\"Marshal body failed: %v\", err)\n\t\treturn err\n\t}\n\tBodyBuf := bytes.NewReader(nodebody)\n\treq, err := http.NewRequest(http.MethodPost, nodehandler, BodyBuf)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tFatalf(\"Frame HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tFatalf(\"Sending HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tInfof(\"%s %s %v in %v\", req.Method, req.URL, resp.Status, time.Since(t))\n\tdefer resp.Body.Close()\n\n\tgomega.Expect(resp.StatusCode).Should(gomega.Equal(http.StatusCreated))\n\treturn nil\n}", "func (c *Client) Register(serviceName, host, port string) error {\n\tkapi := client.NewKeysAPI(c.etcdClient)\n\ts := fmt.Sprintf(\"/%s/%s/%s:%s\", rootPath, serviceName, host, port)\n\n\tresp, err := kapi.Set(context.Background(), s, \"\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"serviceName is registered on etcd, resp is %q\\n\", resp)\n\treturn nil\n}", "func (b *GithubBridge) DoRegister(server *grpc.Server) {\n\tpbgh.RegisterGithubServer(server, b)\n}", "func Register(ctx context.Context, s *Server) {\n\tgo func() {\n\t\ts.logger.Info(\"Starting collector\")\n\t\tif err := s.Manager.Start(ctx); err != nil {\n\t\t\ts.logger.Error(err, \"could not start collector\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n}", "func (a SetNodePoolStatusActivity) Register(worker worker.Registry) {\n\tworker.RegisterActivityWithOptions(a.Execute, activity.RegisterOptions{Name: SetNodePoolStatusActivityName})\n}", "func (runner *runnerImpl) Register(g process.GetPID) error {\n\treturn runner.manager.Register(func() (int, error) {\n\t\tpid, err := g()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tfor _, hook := range runner.hooks {\n\t\t\tgo hook.PID(pid)\n\t\t}\n\n\t\treturn pid, err\n\t})\n}", "func (_e *MockDataCoord_Expecter) Register() *MockDataCoord_Register_Call {\n\treturn &MockDataCoord_Register_Call{Call: _e.mock.On(\"Register\")}\n}", "func (driver *MesosExecutorDriver) Start() (mesosproto.Status, error) {\n\tlog.Infoln(\"Start mesos executor driver\")\n\n\tdriver.mutex.Lock()\n\tdefer driver.mutex.Unlock()\n\n\tif driver.status != mesosproto.Status_DRIVER_NOT_STARTED {\n\t\treturn driver.status, nil\n\t}\n\tif err := driver.parseEnviroments(); err != nil {\n\t\tlog.Errorf(\"Failed to parse environments: %v\\n\", err)\n\t\treturn mesosproto.Status_DRIVER_NOT_STARTED, err\n\t}\n\tif err := driver.init(); err != nil {\n\t\tlog.Errorf(\"Failed to initialize the driver: %v\\n\", err)\n\t\treturn mesosproto.Status_DRIVER_NOT_STARTED, err\n\t}\n\n\t// Start monitoring the slave.\n\tgo driver.monitorSlave()\n\n\t// Start the messenger.\n\tif err := driver.messenger.Start(); err != nil {\n\t\tlog.Errorf(\"Failed to start the messenger: %v\\n\", err)\n\t\treturn mesosproto.Status_DRIVER_NOT_STARTED, err\n\t}\n\n\tdriver.self = driver.messenger.UPID()\n\n\t// Register with slave.\n\tmessage := &mesosproto.RegisterExecutorMessage{\n\t\tFrameworkId: driver.frameworkID,\n\t\tExecutorId: driver.executorID,\n\t}\n\tif err := driver.messenger.Send(driver.slaveUPID, message); err != nil {\n\t\tlog.Errorf(\"Failed to send %v: %v\\n\", message, err)\n\t\treturn mesosproto.Status_DRIVER_NOT_STARTED, err\n\t}\n\n\t// Set status.\n\tdriver.status = mesosproto.Status_DRIVER_RUNNING\n\tlog.Infoln(\"Mesos executor is running\")\n\treturn driver.status, nil\n}", "func Register(parentCmd *cobra.Command) {\n\tbyzantineCmd.AddCommand(executorHonestCmd)\n\tbyzantineCmd.AddCommand(executorWrongCmd)\n\tbyzantineCmd.AddCommand(executorStragglerCmd)\n\tparentCmd.AddCommand(byzantineCmd)\n}", "func (s *Server) Register(rcvr Receiver) {\n\trvalue := reflect.ValueOf(rcvr)\n\trtype := reflect.TypeOf(rcvr)\n\n\tfor i := 0; i < rvalue.NumMethod(); i++ {\n\t\tmethod := rvalue.Method(i)\n\t\tname := rtype.Method(i).Name\n\t\tif name == \"Name\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !validHandler(method, name) {\n\t\t\tcontinue\n\t\t}\n\n\t\ts.handlersLock.Lock()\n\t\ts.handlers[rcvr.Name(name)] = &regMethod{method, method.Type().In(1)}\n\t\ts.handlersLock.Unlock()\n\t}\n}", "func (s *DataNode) register(cfg *config.Config) {\n\tvar (\n\t\terr error\n\t)\n\n\ttimer := time.NewTimer(0)\n\n\t// get the IsIPV4 address, cluster ID and node ID from the master\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tvar ci *proto.ClusterInfo\n\t\t\tif ci, err = MasterClient.AdminAPI().GetClusterInfo(); err != nil {\n\t\t\t\tlog.LogErrorf(\"action[registerToMaster] cannot get ip from master(%v) err(%v).\",\n\t\t\t\t\tMasterClient.Leader(), err)\n\t\t\t\ttimer.Reset(2 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmasterAddr := MasterClient.Leader()\n\t\t\ts.clusterID = ci.Cluster\n\t\t\tif LocalIP == \"\" {\n\t\t\t\tLocalIP = string(ci.Ip)\n\t\t\t}\n\t\t\ts.localServerAddr = fmt.Sprintf(\"%s:%v\", LocalIP, s.port)\n\t\t\tif !util.IsIPV4(LocalIP) {\n\t\t\t\tlog.LogErrorf(\"action[registerToMaster] got an invalid local ip(%v) from master(%v).\",\n\t\t\t\t\tLocalIP, masterAddr)\n\t\t\t\ttimer.Reset(2 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// register this data node on the master\n\t\t\tvar nodeID uint64\n\t\t\tif nodeID, err = MasterClient.NodeAPI().AddDataNode(fmt.Sprintf(\"%s:%v\", LocalIP, s.port), s.zoneName); err != nil {\n\t\t\t\tlog.LogErrorf(\"action[registerToMaster] cannot register this node to master[%v] err(%v).\",\n\t\t\t\t\tmasterAddr, err)\n\t\t\t\ttimer.Reset(2 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texporter.RegistConsul(s.clusterID, ModuleName, cfg)\n\t\t\ts.nodeID = nodeID\n\t\t\tlog.LogDebugf(\"register: register DataNode: nodeID(%v)\", s.nodeID)\n\t\t\treturn\n\t\tcase <-s.stopC:\n\t\t\ttimer.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (_e *MockQueryCoord_Expecter) Register() *MockQueryCoord_Register_Call {\n\treturn &MockQueryCoord_Register_Call{Call: _e.mock.On(\"Register\")}\n}", "func (c *mockMediatorClient) Register(connectionID string) error {\n\tif c.RegisterErr != nil {\n\t\treturn c.RegisterErr\n\t}\n\n\treturn nil\n}", "func (s Server) DoRegister(server *grpc.Server) {\n\tpb.RegisterSonosServiceServer(server, &s)\n}", "func (driver *MesosExecutorDriver) slaveExited() {\n\tif driver.status == mesosproto.Status_DRIVER_ABORTED {\n\t\tlog.Infof(\"Ignoring slave exited event because the driver is aborted!\\n\")\n\t\treturn\n\t}\n\n\tif driver.checkpoint && driver.connected {\n\t\tdriver.connected = false\n\n\t\tlog.Infof(\"Slave exited, but framework has checkpointing enabled. Waiting %v to reconnect with slave %v\",\n\t\t\tdriver.recoveryTimeout, driver.slaveID)\n\t\ttime.AfterFunc(driver.recoveryTimeout, func() { driver.recoveryTimeouts(driver.connection) })\n\t\treturn\n\t}\n\n\tlog.Infof(\"Slave exited ... shutting down\\n\")\n\tdriver.connected = false\n\t// Clean up\n\tdriver.Executor.Shutdown(driver)\n\tdriver.status = mesosproto.Status_DRIVER_ABORTED\n\tdriver.Stop()\n}", "func (server *Server) NotifyTaskCompleted() {\n\tserver.totalCompleted++\n\tif server.totalCompleted >= server.totalSlaves {\n\t\tlog.Printf(\"All slaves completed their task\")\n\t\tserver.executor.generateSummary()\n\t}\n}", "func (m *RdmaDevPlugin) register() error {\n\tkubeletEndpoint := filepath.Join(deprecatedSockDir, kubeEndPoint)\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: m.socketName,\n\t\tResourceName: m.resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (e *Client) Register(ctx context.Context, filename string) error {\n\tconst action = \"/register\"\n\turl := e.baseURL + action\n\n\treqBody, err := json.Marshal(map[string]interface{}{\n\t\t\"events\": []EventType{Shutdown},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq, err := http.NewRequestWithContext(ctx, \"POST\", url, bytes.NewBuffer(reqBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.Header.Set(extensionNameHeader, filename)\n\thttpRes, err := e.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif httpRes.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"request failed with status %s\", httpRes.Status)\n\t}\n\tdefer httpRes.Body.Close()\n\te.extensionID = httpRes.Header.Get(extensionIdentiferHeader)\n\treturn nil\n}", "func (o *Group) Register() int {\n\to.wait_lock.Lock()\n\tdefer o.wait_lock.Unlock()\n\to.wg().Add(1)\n\to.wait_index++\n\to.wait_register[o.wait_index] = true\n\treturn o.wait_index\n}", "func(peers *PeerList) Register(id int32) {\n\tpeers.mux.Lock()\n\tdefer peers.mux.Unlock()\n\tpeers.selfId = id\n\tfmt.Printf(\"SelfId=%v\\n\", id)\n}", "func (cb *CommandBus) Register(k string, h cqrs.CommandHandler) {\n\tcb.RegisterFunc(k, h.Handle)\n}", "func (bft *ProtocolBFTCoSi) RegisterOnDone(fn func()) {\n\tbft.onDone = fn\n}", "func (a *agent) RegisterAgent(ctx context.Context, reg *api.Registration) (*api.Empty, error) {\n\tid := reg.GetAgentID()\n\n\ta.work[id] = make(chan *api.Task)\n\ta.output[id] = make(chan *api.Response)\n\tregisteredAgents[id] = reg\n\tlog.WithFields(log.Fields{\n\t\t\"agent\": reg.GetAgentID(),\n\t\t\"ip\": reg.GetIP(),\n\t\t\"hostname\": reg.GetHostname(),\n\t\t\"os\": reg.GetOS(),\n\t}).Info(\"registered new agent\")\n\treturn api.EmptyMessage, nil\n}" ]
[ "0.7745206", "0.66256315", "0.65590346", "0.64209473", "0.6302684", "0.60886437", "0.60206133", "0.58198136", "0.577303", "0.5616237", "0.56074566", "0.55823475", "0.54899216", "0.5482696", "0.54519665", "0.54454345", "0.5441375", "0.5412779", "0.5340733", "0.5335579", "0.5288551", "0.52704394", "0.5248618", "0.5237884", "0.5217694", "0.51891965", "0.5186479", "0.5174232", "0.51364166", "0.51357114", "0.5112867", "0.51086754", "0.5108645", "0.51046187", "0.5104252", "0.5094063", "0.50889015", "0.5077121", "0.5075665", "0.50730103", "0.50724393", "0.5045812", "0.50441444", "0.5034751", "0.5025216", "0.49884382", "0.49799705", "0.49752706", "0.49745554", "0.49731472", "0.49643478", "0.49544978", "0.49539346", "0.4953175", "0.49529648", "0.4950888", "0.4950257", "0.49399826", "0.49396807", "0.49336022", "0.49273902", "0.49261135", "0.49218217", "0.4921015", "0.49178332", "0.48895553", "0.48862037", "0.48809418", "0.48794556", "0.48683733", "0.48667243", "0.4865995", "0.48648468", "0.48597336", "0.4847089", "0.48469895", "0.4844607", "0.48377672", "0.48335364", "0.48332667", "0.48216146", "0.48211932", "0.48177645", "0.48135987", "0.4813424", "0.48104903", "0.48099703", "0.48083058", "0.480337", "0.47979403", "0.4793187", "0.47896478", "0.47802576", "0.47779617", "0.4774419", "0.47709098", "0.475566", "0.47546008", "0.4752794", "0.47464624" ]
0.7792358
0
Reregistered is called when the executor is successfully reregistered with the slave. This can happen when the slave fails over.
func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) { if k.isDone() { return } log.Infof("Reregistered with slave %v\n", slaveInfo) if !(&k.state).transition(disconnectedState, connectedState) { log.Errorf("failed to reregister/transition to a connected state") } if slaveInfo != nil { _, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes)) if err != nil { log.Errorf("cannot update node labels: %v", err) } } k.initialRegistration.Do(k.onInitialRegistration) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}", "func (s *eremeticScheduler) Reregistered(driver sched.SchedulerDriver, masterInfo *mesos.MasterInfo) {\n\tlog.Debugf(\"Framework re-registered with master %s\", masterInfo)\n\tif !s.initialised {\n\t\tdriver.ReconcileTasks([]*mesos.TaskStatus{})\n\t\ts.initialised = true\n\t} else {\n\t\ts.Reconcile(driver)\n\t}\n}", "func (k *KubernetesScheduler) Reregistered(driver mesos.SchedulerDriver, masterInfo *mesos.MasterInfo) {\n\tlog.Infof(\"Scheduler reregistered with the master: %v\\n\", masterInfo)\n\tk.registered = true\n}", "func (k *KubernetesScheduler) ExecutorLost(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, status int) {\n\tlog.Infof(\"Executor %v of slave %v is lost, status: %v\\n\", executorId, slaveId, status)\n\t// TODO(yifan): Restart any unfinished tasks of the executor.\n}", "func (e *LifecycleEvent) SetDeregisterCompleted(val bool) { e.deregisterCompleted = val }", "func (r *Registrator) Deregister() error {\n\tr.Jobs = nil\n\treturn nil\n}", "func (r *RegisterMonitor) deregister() {\n\t// Basic retry loop, no backoff for now. But we want to retry a few\n\t// times just in case there are basic ephemeral issues.\n\tfor i := 0; i < 3; i++ {\n\t\terr := r.Client.Agent().ServiceDeregister(r.serviceID())\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tr.Logger.Printf(\"[WARN] proxy: service deregister failed: %s\", err)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}", "func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !k.swapState(connectedState, disconnectedState) {\n\t\t//programming error?\n\t\tpanic(\"already disconnected?!\")\n\t}\n}", "func (e *EurekaConnection) ReregisterInstance(ins *Instance) error {\n\tslug := fmt.Sprintf(\"%s/%s\", EurekaURLSlugs[\"Apps\"], ins.App)\n\treqURL := e.generateURL(slug)\n\n\tvar out []byte\n\tvar err error\n\tif e.UseJson {\n\t\tins.PortJ.Number = strconv.Itoa(ins.Port)\n\t\tins.SecurePortJ.Number = strconv.Itoa(ins.SecurePort)\n\t\tout, err = e.marshal(&RegisterInstanceJson{ins})\n\t} else {\n\t\tout, err = e.marshal(ins)\n\t}\n\n\tbody, rcode, err := postBody(reqURL, out, e.UseJson)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not complete registration, error: %s\", err.Error())\n\t\treturn err\n\t}\n\tif rcode != 204 {\n\t\tlog.Warningf(\"HTTP returned %d registering Instance=%s App=%s Body=\\\"%s\\\"\", rcode,\n\t\t\tins.Id(), ins.App, string(body))\n\t\treturn &unsuccessfulHTTPResponse{rcode, \"possible failure registering instance\"}\n\t}\n\n\t// read back our registration to pick up eureka-supplied values\n\te.readInstanceInto(ins)\n\n\treturn nil\n}", "func (k *KubernetesScheduler) SlaveLost(driver mesos.SchedulerDriver, slaveId *mesos.SlaveID) {\n\tlog.Infof(\"Slave %v is lost\\n\", slaveId)\n\t// TODO(yifan): Restart any unfinished tasks on that slave.\n}", "func (driver *MesosExecutorDriver) slaveExited() {\n\tif driver.status == mesosproto.Status_DRIVER_ABORTED {\n\t\tlog.Infof(\"Ignoring slave exited event because the driver is aborted!\\n\")\n\t\treturn\n\t}\n\n\tif driver.checkpoint && driver.connected {\n\t\tdriver.connected = false\n\n\t\tlog.Infof(\"Slave exited, but framework has checkpointing enabled. Waiting %v to reconnect with slave %v\",\n\t\t\tdriver.recoveryTimeout, driver.slaveID)\n\t\ttime.AfterFunc(driver.recoveryTimeout, func() { driver.recoveryTimeouts(driver.connection) })\n\t\treturn\n\t}\n\n\tlog.Infof(\"Slave exited ... shutting down\\n\")\n\tdriver.connected = false\n\t// Clean up\n\tdriver.Executor.Shutdown(driver)\n\tdriver.status = mesosproto.Status_DRIVER_ABORTED\n\tdriver.Stop()\n}", "func (es *EventStream) Deregister(handle int64) error {\n\tes.mux.Lock()\n\tcount, err := es.deregister(handle)\n\tes.mux.Unlock()\n\t// Really wait should be for my specific one, but ...\n\t// Multi-threaded apps will have issues.\n\tfor i := 0; i < count; i++ {\n\t\t<-es.rchan\n\t}\n\treturn err\n}", "func (c *crdWatcher) restoreFinished() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.finishedRestore {\n\t\treturn\n\t}\n\n\t// creating a new controller will execute DoFunc immediately\n\tc.controller.UpdateController(clusterPoolStatusControllerName,\n\t\tcontroller.ControllerParams{\n\t\t\tGroup: clusterPoolStatusControllerGroup,\n\t\t\tDoFunc: c.updateCiliumNodeStatus,\n\t\t})\n\tc.finishedRestore = true\n}", "func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !(&k.state).transition(connectedState, disconnectedState) {\n\t\tlog.Errorf(\"failed to disconnect/transition to a disconnected state\")\n\t}\n}", "func Deregister() error {\r\n\treturn DefaultServer.Deregister()\r\n}", "func (s SwxProxy) Deregister(_ context.Context, _ *protos.RegistrationRequest) (*protos.RegistrationAnswer, error) {\n\treturn &protos.RegistrationAnswer{}, nil\n}", "func (innerExecutorImpl) unregister(w http.ResponseWriter, req *http.Request) {\n\tlogger.Logging(logger.DEBUG)\n\tdefer logger.Logging(logger.DEBUG, \"OUT\")\n\n\tif !common.CheckSupportedMethod(w, req.Method, POST) {\n\t\treturn\n\t}\n\n\te := healthExecutor.Unregister()\n\tif e != nil {\n\t\tcommon.MakeErrorResponse(w, e)\n\t\treturn\n\t}\n\n\tresponse := make(map[string]interface{})\n\tresponse[\"result\"] = \"success\"\n\tcommon.MakeResponse(w, common.ChangeToJson(response))\n}", "func (s *eremeticScheduler) Disconnected(sched.SchedulerDriver) {\n\tlog.Debugf(\"Framework disconnected with master\")\n}", "func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver,\n\texecutorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Executor %v of framework %v registered with slave %v\\n\",\n\t\texecutorInfo, frameworkInfo, slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}", "func (x *Register) Shutdown() error {\n\tc := make(chan struct{})\n\tx.runQueue.Stop(func() { close(c) })\n\t<-c\n\treturn nil\n}", "func (m *manager) shutdownBlockedDriver(name string, reattach *pstructs.ReattachConfig) {\n\tc, err := pstructs.ReattachConfigToGoPlugin(reattach)\n\tif err != nil {\n\t\tm.logger.Warn(\"failed to reattach and kill blocked driver plugin\",\n\t\t\t\"driver\", name, \"error\", err)\n\t\treturn\n\n\t}\n\tpluginInstance, err := m.loader.Reattach(name, base.PluginTypeDriver, c)\n\tif err != nil {\n\t\tm.logger.Warn(\"failed to reattach and kill blocked driver plugin\",\n\t\t\t\"driver\", name, \"error\", err)\n\t\treturn\n\t}\n\n\tif !pluginInstance.Exited() {\n\t\tpluginInstance.Kill()\n\t}\n}", "func (k *KubernetesScheduler) Disconnected(driver mesos.SchedulerDriver) {\n\tlog.Infof(\"Master disconnected!\\n\")\n\tk.registered = false\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// discard all cached offers to avoid unnecessary TASK_LOST updates\n\tfor offerId := range k.offers {\n\t\tk.deleteOffer(offerId)\n\t}\n\n\t// TODO(jdef): it's possible that a task is pending, in between Schedule() and\n\t// Bind(), such that it's offer is now invalid. We should check for that and\n\t// clearing the offer from the task (along with a related check in Bind())\n}", "func (k *KubernetesExecutor) Shutdown(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tclose(k.done)\n\n\tlog.Infoln(\"Shutdown the executor\")\n\tdefer func() {\n\t\tfor !k.swapState(k.getState(), doneState) {\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tk.tasks = map[string]*kuberTask{}\n\t}()\n\n\t// according to docs, mesos will generate TASK_LOST updates for us\n\t// if needed, so don't take extra time to do that here.\n\n\t// also, clear the pod configuration so that after we issue our Kill\n\t// kubernetes doesn't start spinning things up before we exit.\n\tk.updateChan <- kubelet.PodUpdate{Op: kubelet.SET}\n\n\tKillKubeletContainers(k.dockerClient)\n}", "func deregister(machinePath string) {\n\tif isActive(VBoxName) {\n\t\tm, err := virtualbox.GetMachine(VBoxName)\n\t\tif err != nil {\n\t\t\thelp.ExitOnError(err)\n\t\t}\n\t\tif m.State == virtualbox.Running {\n\t\t\terr = m.Poweroff()\n\t\t\tif err != nil {\n\t\t\t\thelp.ExitOnError(err)\n\t\t\t}\n\t\t}\n\t\thelp.ExecCmd(\"VBoxManage\",\n\t\t\t[]string{\n\t\t\t\t\"unregistervm\",\n\t\t\t\tfmt.Sprintf(\"%s\", machinePath),\n\t\t\t})\n\t\tfmt.Println(\"[+] Done\")\n\t}\n}", "func (agent *ActionAgent) SlaveWasRestarted(ctx context.Context, parent *topodatapb.TabletAlias) error {\n\tif err := agent.lock(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer agent.unlock()\n\n\ttypeChanged := false\n\n\t// Once this action completes, update authoritative tablet node first.\n\tif _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error {\n\t\tif tablet.Type == topodatapb.TabletType_MASTER {\n\t\t\ttablet.Type = topodatapb.TabletType_REPLICA\n\t\t\ttypeChanged = true\n\t\t\treturn nil\n\t\t}\n\t\treturn topo.NewError(topo.NoUpdateNeeded, agent.TabletAlias.String())\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif typeChanged {\n\t\tif err := agent.refreshTablet(ctx, \"SlaveWasRestarted\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tagent.runHealthCheckLocked()\n\t}\n\treturn nil\n}", "func (s NoUseSwxProxy) Deregister(\n\tctx context.Context,\n\treq *protos.RegistrationRequest,\n) (*protos.RegistrationAnswer, error) {\n\treturn &protos.RegistrationAnswer{}, fmt.Errorf(\"Deregister is NOT IMPLEMENTED\")\n}", "func (e *Engine) deregister() error {\n\t// remove rule associated with engine\n\terr := e.Rule.Remove()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't remove rule %s of engine %s: %v\", e.Rule.Name, e.Name, err)\n\t}\n\n\t// remove engine as export client\n\texportClient := ExportClient{}\n\terr = exportClient.Remove(*e)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't remove export client registration for engine %s: %v\", e.Name, err)\n\t}\n\n\t// instruct engine to deregister value descriptors\n\t//deregister := \"deregister\"\n\t//communication.Publish(\n\t//\tnaming.Topic(e.Index, naming.Command),\n\t//\tnaming.Publisher(e.Index, naming.Command),\n\t//\tderegister)\n\n\t// wait until value descriptors are deregistered\n\n\treturn nil\n}", "func (w *worker) deregister() {\n\tw.Lock()\n\tid := w.id\n\teid := w.eid\n\tw.active = false\n\tw.Unlock()\n\tactivePipelines.Lock()\n\tdelete(activePipelines.i, id)\n\tdelete(activePipelines.eids, eid)\n\tactivePipelines.Unlock()\n}", "func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver,\n\texecutorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Executor %v of framework %v registered with slave %v\\n\",\n\t\texecutorInfo, frameworkInfo, slaveInfo)\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to register/transition to a connected state\")\n\t}\n\n\tif executorInfo != nil && executorInfo.Data != nil {\n\t\tk.staticPodsConfig = executorInfo.Data\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes))\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tk.initialRegistration.Do(k.onInitialRegistration)\n}", "func (c *ConsulClient) Deregister(ctx context.Context, sessionID string) error {\n\tregistryOperationCount.WithLabelValues(env, \"Deregister\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"Deregister\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\t_, err := c.client.Session().Destroy(sessionID, nil)\n\tif err != nil {\n\t\tlogger.Ctx(ctx).Errorw(\"failed to destroy consul session\", \"ID\", sessionID, \"error\", err.Error())\n\t}\n\n\treturn err\n}", "func (x *Rest) eyewallCacheUnregister(r *msg.Result) {\n\tswitch r.Section {\n\tcase msg.SectionRegistration:\n\tdefault:\n\t\treturn\n\t}\n\n\tswitch r.Action {\n\tcase msg.ActionRemove:\n\tcase msg.ActionUpdate:\n\tdefault:\n\t\treturn\n\t}\n\n\tswitch r.Code {\n\tcase msg.ResultOK:\n\tdefault:\n\t\treturn\n\t}\n\n\treg := r.Registration[0]\n\tx.invl.Unregister(reg.ID)\n}", "func (k *KubernetesExecutor) doShutdown(driver bindings.ExecutorDriver) {\n\tdefer func() {\n\t\tlog.Errorf(\"exiting with unclean shutdown: %v\", recover())\n\t\tif k.exitFunc != nil {\n\t\t\tk.exitFunc(1)\n\t\t}\n\t}()\n\n\t(&k.state).transitionTo(terminalState)\n\n\t// signal to all listeners that this KubeletExecutor is done!\n\tclose(k.done)\n\n\tif k.shutdownAlert != nil {\n\t\tfunc() {\n\t\t\tutil.HandleCrash()\n\t\t\tk.shutdownAlert()\n\t\t}()\n\t}\n\n\tlog.Infoln(\"Stopping executor driver\")\n\t_, err := driver.Stop()\n\tif err != nil {\n\t\tlog.Warningf(\"failed to stop executor driver: %v\", err)\n\t}\n\n\tlog.Infoln(\"Shutdown the executor\")\n\n\t// according to docs, mesos will generate TASK_LOST updates for us\n\t// if needed, so don't take extra time to do that here.\n\tk.tasks = map[string]*kuberTask{}\n\n\tselect {\n\t// the main Run() func may still be running... wait for it to finish: it will\n\t// clear the pod configuration cleanly, telling k8s \"there are no pods\" and\n\t// clean up resources (pods, volumes, etc).\n\tcase <-k.kubeletFinished:\n\n\t//TODO(jdef) attempt to wait for events to propagate to API server?\n\n\t// TODO(jdef) extract constant, should be smaller than whatever the\n\t// slave graceful shutdown timeout period is.\n\tcase <-time.After(15 * time.Second):\n\t\tlog.Errorf(\"timed out waiting for kubelet Run() to die\")\n\t}\n\tlog.Infoln(\"exiting\")\n\tif k.exitFunc != nil {\n\t\tk.exitFunc(0)\n\t}\n}", "func (asr *sessionRegistry) deregister(clt *Client) {\n\tasr.lock.Lock()\n\tdelete(asr.registry, clt.Session.Key)\n\tasr.lock.Unlock()\n}", "func (tbm testbedMesh) Unsubscribe(emitterName, receptorName string) error {\n\treturn fmt.Errorf(\"emitter cell '%s' does not exist\", emitterName)\n}", "func (s *SlaveNode) doUnbootedState(monitor *SlaveMonitor) string { // -> {SBooting, SCrashed}\n\tif s.Parent == nil {\n\t\ts.L.Lock()\n\t\tparts := strings.Split(monitor.tree.ExecCommand, \" \")\n\t\tcmd := exec.Command(parts[0], parts[1:]...)\n\t\tfile := monitor.remoteMasterFile\n\t\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"ZEUS_MASTER_FD=%d\", file.Fd()))\n\t\tcmd.ExtraFiles = []*os.File{file}\n\t\tgo s.babysitRootProcess(cmd)\n\t\ts.L.Unlock()\n\t} else {\n\t\ts.Parent.RequestSlaveBoot(s)\n\t}\n\n\t<-s.event // sent by SlaveWasInitialized\n\n\ts.L.Lock()\n\tdefer s.L.Unlock()\n\tif s.Error != \"\" {\n\t\treturn SCrashed\n\t}\n\treturn SBooting\n}", "func Rejected(e error) *Task {\n\tdone := make(chan struct{}, 1)\n\tclose(done)\n\tresolver := make(chan interface{}, 1)\n\trejector := make(chan error, 1)\n\trejector <- e\n\treturn &Task{\n\t\tResolver: resolver,\n\t\tRejector: rejector,\n\t\tStopper: &done,\n\t\tDone: &done,\n\t}\n}", "func (s *ExternalAgentRunningState) ShutdownFailed() error {\n\ts.agent.setStateUnsafe(s.agent.ShutdownFailedState)\n\treturn nil\n}", "func (acnl *Channel) unregister() error {\n\tconst Attempts = 2\n\n\tmsg, err := json.Marshal(acnl.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tacnl.l.WithFields(log.Fields{\n\t\t\"tag\": \"channel-amqp-unregister\",\n\t\t\"max-attempts\": Attempts,\n\t\t\"endpoint\": string(msg),\n\t}).Debug(\"sending an unregistering request\")\n\n\tfor i := 0; i < Attempts; i++ {\n\t\t// Try to use the current connection the first time.\n\t\t// Recreate it otherwise\n\t\tif i > 0 {\n\t\t\tacnl.l.WithFields(log.Fields{\n\t\t\t\t\"tag\": \"channel-amqp-unregister\",\n\t\t\t\t\"try\": i,\n\t\t\t}).Warn(\"attempting to re-initialize the connection\")\n\n\t\t\tif _, err = acnl.setup(); err != nil {\n\t\t\t\tacnl.l.WithFields(log.Fields{\n\t\t\t\t\t\"tag\": \"channel-amqp-unregister\",\n\t\t\t\t\t\"try\": i,\n\t\t\t\t\t\"err\": err,\n\t\t\t\t}).Warn(\"setup failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif err = acnl.publish(QueueVNFMUnregister, msg); err == nil {\n\t\t\tacnl.l.WithFields(log.Fields{\n\t\t\t\t\"tag\": \"channel-amqp-unregister\",\n\t\t\t\t\"try\": i,\n\t\t\t\t\"success\": true,\n\t\t\t}).Info(\"endpoint unregister request successfully sent\")\n\t\t\treturn nil\n\t\t}\n\n\t\tacnl.l.WithFields(log.Fields{\n\t\t\t\"tag\": \"channel-amqp-unregister\",\n\t\t\t\"try\": i,\n\t\t\t\"success\": false,\n\t\t}).Info(\"endpoint unregister failed to send\")\n\t}\n\n\treturn err\n}", "func (o *ClusterProxyDeregisterV1Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\n\tresult := NewClusterProxyDeregisterV1Default(response.Code())\n\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\treturn nil, err\n\t}\n\tif response.Code()/100 == 2 {\n\t\treturn result, nil\n\t}\n\treturn nil, result\n\n}", "func pmRCoreEnd() {\n\t//\n\trsims = nil\n\n\t//\n\tlog.Println(\"Ending the experiment\")\n}", "func (mgmt *MonitoringManager) Resend() {\n\tfmt.Println(\"[MON] Resending unacknowledged messages\")\n\t// Iterate through all clients currently being monitored\n\tfor _,v := range mgmt.MonitorList {\n\t\t// Check if client address/port combo matches that in the last message list\n\t\t// Last message list contains all messages that are yet to be acknowledged as received\n\t\tif value, ok := mgmt.LastMessageList[v.Message.Addr.String()]; ok {\n\t\t\t// Check that there is a message being kept in the list\n\t\t\tif mgmt.LastMessageList[v.Message.Addr.String()] != nil {\n\t\t\t\tfmt.Printf(\"Broadcasting update to: %s\\n\", v.Message.Addr.String())\n\t\t\t\t// Resend message to client\n\t\t\t\tv.Message.Reply(*value)\n\t\t\t}\n\t\t}\n\t}\n}", "func (nd *NodeDiscover) Deregister(service *url.URL) {\n\tnd.registers.Lock()\n\tdelete(nd.registers.r, service.String())\n\tnd.registers.Unlock()\n\tlog.Infof(\"node-discovery: Service %v deregistered\", service.String())\n}", "func (t *target) disable(msg string) {\n\tt.regstate.mu.Lock()\n\n\tif t.regstate.disabled.Load() {\n\t\tt.regstate.mu.Unlock()\n\t\treturn // nothing to do\n\t}\n\tif err := t.unregisterSelf(false); err != nil {\n\t\tt.regstate.mu.Unlock()\n\t\tnlog.Errorf(\"%s but failed to remove self from Smap: %v\", msg, err)\n\t\treturn\n\t}\n\tt.regstate.disabled.Store(true)\n\tt.regstate.mu.Unlock()\n\tnlog.Errorf(\"Warning: %s => disabled and removed self from Smap\", msg)\n}", "func (qrs *queuedRetrySender) shutdown() {\n\t// Cleanup queue metrics reporting\n\tif qrs.cfg.Enabled {\n\t\t_ = globalInstruments.queueSize.UpsertEntry(func() int64 {\n\t\t\treturn int64(0)\n\t\t}, metricdata.NewLabelValue(qrs.fullName()))\n\t}\n\n\t// First Stop the retry goroutines, so that unblocks the queue numWorkers.\n\tclose(qrs.retryStopCh)\n\n\t// Stop the queued sender, this will drain the queue and will call the retry (which is stopped) that will only\n\t// try once every request.\n\tif qrs.queue != nil {\n\t\tqrs.queue.Stop()\n\t}\n}", "func (r *Registry) Deregister(ctx context.Context, service *registry.ServiceInstance) error {\n\treturn r.api.Deregister(ctx, r.Endpoints(service))\n}", "func (_m *clusterAssetSvc) Unsubscribe(listener resource.Listener) {\n\t_m.Called(listener)\n}", "func WorkerShutDown(workerID int){\n\tworkerMsg := WorkerMessage{}\n\tworkerMsg.ID = workerID\n\n\tcall(\"Master.WorkerShutDown\", &workerMsg, &workerMsg)\n}", "func (s *Worker) AfterRun() error {\n\treturn nil\n}", "func (m *Master) DeregisterNotify(ctx context.Context, request *pb.DeregisterNotifyRequest) (*pb.DeregisterNotifyResponse, error) {\n\tlog.Println(\"Data server\", request.Addr, \"deregistered\")\n\tm.Working[request.Addr] = false\n\treturn &pb.DeregisterNotifyResponse{\n\t}, nil\n}", "func (d StaticAgentDiscovery) Unsubscribe(chan<- []string) { return }", "func (s *supervisor) processDied(r *processorRequestDied) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\t// Okay, so a Runnable has quit. What now?\n\tn := s.nodeByDN(r.dn)\n\tctx := n.ctx\n\n\t// Simple case: it was marked as Done and quit with no error.\n\tif n.state == nodeStateDone && r.err == nil {\n\t\t// Do nothing. This was supposed to happen. Keep the process as DONE.\n\t\treturn\n\t}\n\n\t// Find innermost error to check if it's a context canceled error.\n\tperr := r.err\n\tfor {\n\t\tif inner := errors.Unwrap(perr); inner != nil {\n\t\t\tperr = inner\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\t// Simple case: the context was canceled and the returned error is the context error.\n\tif err := ctx.Err(); err != nil && perr == err {\n\t\t// Mark the node as canceled successfully.\n\t\tn.state = nodeStateCanceled\n\t\treturn\n\t}\n\n\t// Otherwise, the Runnable should not have died or quit. Handle accordingly.\n\terr := r.err\n\t// A lack of returned error is also an error.\n\tif err == nil {\n\t\terr = fmt.Errorf(\"returned when %s\", n.state)\n\t} else {\n\t\terr = fmt.Errorf(\"returned error when %s: %w\", n.state, err)\n\t}\n\n\ts.ilogger.Errorf(\"Runnable %s died: %v\", n.dn(), err)\n\t// Mark as dead.\n\tn.state = nodeStateDead\n\n\t// Cancel that node's context, just in case something still depends on it.\n\tn.ctxC()\n\n\t// Cancel all siblings.\n\tif n.parent != nil {\n\t\tfor name, _ := range n.parent.groupSiblings(n.name) {\n\t\t\tif name == n.name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsibling := n.parent.children[name]\n\t\t\t// TODO(q3k): does this need to run in a goroutine, ie. can a context cancel block?\n\t\t\tsibling.ctxC()\n\t\t}\n\t}\n}", "func (s *Consumer) AfterRun() error {\n\treturn nil\n}", "func (di *distLockInstance) RUnlock() {\n\tdi.rwMutex.RUnlock()\n}", "func (h *Hub) doUnregister(c *connection) {\n\th.Lock()\n\tdefer h.Unlock()\n\n\t// get the subscription\n\ts, ok := h.connections[c]\n\tif !ok {\n\t\th.log.Println(\n\t\t\t\"[WARN] cannot unregister connection, it is not registered.\",\n\t\t)\n\t\treturn\n\t}\n\n\tif s != nil {\n\t\th.log.Printf(\n\t\t\t\"[DEBUG] unregistering one of subscribers: %s connections\\n\",\n\t\t\ts.Topic,\n\t\t)\n\t\t// delete the connection from subscriber's connections\n\t\tdelete(s.connections, c)\n\t\tif len(s.connections) == 0 {\n\t\t\t// there are no more open connections for this subscriber\n\t\t\th.log.Printf(\n\t\t\t\t\"[DEBUG] unsub: %s, no more open connections\\n\",\n\t\t\t\ts.Topic,\n\t\t\t)\n\t\t\tdelete(h.subscribers, s.Topic)\n\t\t\t// unsubscribe from redis topic\n\t\t\terr := h.subconn.Unsubscribe(s.Topic)\n\t\t\tif err != nil {\n\t\t\t\th.log.Printf(\n\t\t\t\t\t\"[WARN] Unable to unsub topic: %s from redis\\n\",\n\t\t\t\t\ts.Topic,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\th.log.Printf(\n\t\t\t\t\t\"[DEBUG] Unsubscribed topic %s from redis\\n\",\n\t\t\t\t\ts.Topic,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\th.log.Println(\"[DEBUG] unregistering socket connection\")\n\tc.close()\n\tdelete(h.connections, c)\n}", "func TestReregisterAndExecuteCommand(t *testing.T) {\n\t// Fetch the controller, register the ControllerTestCommand2 to handle 'ControllerTest2' notes\n\tvar controller = controller.GetInstance(\"ControllerTestKey5\", func() interfaces.IController { return &controller.Controller{Key: \"ControllerTestKey5\"} })\n\tcontroller.RegisterCommand(\"ControllerTest2\", func() interfaces.ICommand { return &ControllerTestCommand2{} })\n\n\t// Remove the Command from the Controller\n\tcontroller.RemoveCommand(\"ControllerTest2\")\n\n\t// Re-register the Command with the Controller\n\tcontroller.RegisterCommand(\"ControllerTest2\", func() interfaces.ICommand { return &ControllerTestCommand2{} })\n\n\t// Create a 'ControllerTest2' note\n\tvar vo *ControllerTestVO = &ControllerTestVO{Input: 12}\n\tvar note interfaces.INotification = observer.NewNotification(\"ControllerTest2\", vo, \"\")\n\n\t// retrieve a reference to the View from the same core.\n\tvar view interfaces.IView = view.GetInstance(\"ControllerTestKey5\", func() interfaces.IView { return &view.View{Key: \"ControllerTestKey5\"} })\n\n\t// send the notification\n\tview.NotifyObservers(note)\n\n\t// test assertions\n\t// if the command is executed once the value will be 24\n\tif vo.Result != 24 {\n\t\tt.Error(\"Expecting vo.result == 24\")\n\t}\n\n\t// Prove that accumulation works in the VO by sending the notification again\n\tview.NotifyObservers(note)\n\n\t// if the command is executed twice the value will be 48\n\tif vo.Result != 48 {\n\t\tt.Error(\"Expecting vo.result == 48\")\n\t}\n}", "func (r *rpcServerService) Unregister(name string) error {\n if _, found := r.serviceMap.Del(name); !found {\n return os.ErrNotExist\n }\n return nil\n}", "func TestDeregister(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.RegisterAll(rest.Registrations{\n\t\t{\"deregister\", \"single\", NewTestHandler(\"s1\", assert)},\n\t\t{\"deregister\", \"pair\", NewTestHandler(\"p1\", assert)},\n\t\t{\"deregister\", \"pair\", NewTestHandler(\"p2\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g1\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g2\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g3\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g4\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g5\", assert)},\n\t\t{\"deregister\", \"group\", NewTestHandler(\"g6\", assert)},\n\t})\n\tassert.Nil(err)\n\t// Perform tests.\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"single\"), []string{\"s1\"})\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"pair\"), []string{\"p1\", \"p2\"})\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"group\"), []string{\"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\"})\n\n\tmux.Deregister(\"deregister\", \"single\", \"s1\")\n\tassert.Nil(mux.RegisteredHandlers(\"deregister\", \"single\"))\n\tmux.Deregister(\"deregister\", \"single\")\n\tassert.Nil(mux.RegisteredHandlers(\"deregister\", \"single\"))\n\n\tmux.Deregister(\"deregister\", \"pair\")\n\tassert.Nil(mux.RegisteredHandlers(\"deregister\", \"pair\"))\n\n\tmux.Deregister(\"deregister\", \"group\", \"x99\")\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"group\"), []string{\"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\"})\n\tmux.Deregister(\"deregister\", \"group\", \"g5\")\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"group\"), []string{\"g1\", \"g2\", \"g3\", \"g4\", \"g6\"})\n\tmux.Deregister(\"deregister\", \"group\", \"g4\", \"g2\")\n\tassert.Equal(mux.RegisteredHandlers(\"deregister\", \"group\"), []string{\"g1\", \"g3\", \"g6\"})\n\tmux.Deregister(\"deregister\", \"group\")\n\tassert.Nil(mux.RegisteredHandlers(\"deregister\", \"group\"))\n}", "func (addon DockerregistryAddon) Uninstall() {\n\tnode := *addon.masterNode\n\t_, err := addon.communicator.RunCmd(node, \"helm delete --purge `helm list | grep docker-registry | awk '{print $1;}'`\")\n\tFatalOnError(err)\n\tlog.Println(\"docker-registry uninstalled\")\n}", "func (hs *HealthStatusInfo) ReconnectedToBroker() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.LastDisconnectFromBrokerDuration = hs.GetLastDisconnectFromBrokerDuration()\n\tMQTTHealth.DisconnectedFromMQTTBroker = false\n}", "func (device *IndustrialDigitalIn4V2Bricklet) DeregisterAllValueCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackAllValue), registrationId)\n}", "func (rt *RecoveryTracker) Shutdown() {\n}", "func (q *CommandQueue) Unsubscribe(listener *CommandQueueStatusListener) {\n\tlistener.Close()\n\n\tq.listenerMutex.Lock()\n\tdefer q.listenerMutex.Unlock()\n\tfor i, l := range q.listeners {\n\t\tif l == listener {\n\t\t\tq.listeners = append(q.listeners[:i], q.listeners[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n\n\tpanic(\"not subscribed\")\n}", "func (ra *RecoverableAction) Recover(r Recoverable, err interface{}) {\n\tif ra == r {\n\t\tlog.Printf(\"Recovering error '%v'!\", err)\n\n\t\tra.replyChan <- \"Recovered\"\n\n\t\tgo ra.backend()\n\t}\n}", "func (n *NotifyMail) ResendFailed() {\n\n\tvar mails []M.Mail\n\n\terr := n.store.GetFailed(&mails, 100)\n\n\tif err != nil {\n\t\tn.errChan.In() <- err\n\t\treturn\n\t}\n\n\tif len(mails) > 0 {\n\t\tn.notifChan.In() <- fmt.Sprintf(\"Resending %d failed mails\", len(mails))\n\t}\n\n\tfor _, mail := range mails {\n\t\tn.sendChan <- mail\n\t}\n\n}", "func runslave(c Connector) {\n attempts := INIT_ATTEMPTS\n sleep := INIT_SLEEP\n restart := c.Restart()\n\n for {\n // Setup the command to start Jenkins\n cmd := c.Command()\n if logger != nil {\n cmd.Stderr = logger\n }\n\n // Start a timer to determine how long it has run for.\n start := time.Now()\n printf(\"Executing %s\", strings.Join(cmd.Args, \" \"))\n if err := cmd.Start(); err != nil {\n print(err)\n }\n\n finished := make(chan bool)\n go func() {\n cmd.Wait()\n finished <- true\n }()\n\n select {\n case <-finished:\n // If we ran for a while and shut down unexpectedly, do not try to restart.\n if time.Since(start) > MIN_EXEC_TIME {\n print(\"Jenkins shut down unexpectedly, but ran for a decent time. Quitting.\")\n return\n }\n\n // While we have additional attempts left, sleep and attempt to start Jenkins again.\n if attempts > 0 {\n printf(\"Jenkins aborted rather quickly. Will try again in %d seconds.\", sleep/time.Second)\n printf(\"%d attempts remaining.\", attempts)\n attempts--\n\n time.Sleep(sleep)\n\n sleep *= 2\n if sleep > MAX_SLEEP {\n sleep = MAX_SLEEP\n }\n\n } else {\n printf(\"Failed to start Jenkins in %d attempts. Quitting.\", INIT_ATTEMPTS)\n return\n }\n case res, ok := <-restart:\n if !ok {\n // The monitor was closed, quit\n cmd.Process.Kill()\n break\n }\n if res {\n // Got a message to restart\n print(\"Restarting...\")\n cmd.Process.Kill()\n attempts = INIT_ATTEMPTS\n }\n }\n\n }\n}", "func (f *Failer) Reboot(host string) error {\n\tscript := \"sudo shutdown -r\"\n\tlog.V(1).Infof(\"Rebooting host %s\", host)\n\treturn f.runWithEvilTag(host, script)\n}", "func (t *transport) shutdown() {\n\tt.mux.Lock()\n\tfor _, cli := range t.remotes {\n\t\tcli.Close()\n\t}\n\tt.remotes = nil\n\tt.mux.Unlock()\n}", "func TestDroppingPrimaryRegionAsyncJobFailure(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tdefer log.Scope(t).Close(t)\n\n\t// Decrease the adopt loop interval so that retries happen quickly.\n\tdefer sqltestutils.SetTestJobsAdoptInterval()()\n\n\t// Protects expectedCleanupRuns\n\tvar mu syncutil.Mutex\n\t// We need to cleanup 2 times, once for the multi-region type descriptor and\n\t// once for the array alias of the multi-region type descriptor.\n\thaveWePerformedFirstRoundOfCleanup := false\n\tcleanupFinished := make(chan struct{})\n\tknobs := base.TestingKnobs{\n\t\tSQLTypeSchemaChanger: &sql.TypeSchemaChangerTestingKnobs{\n\t\t\tRunBeforeExec: func() error {\n\t\t\t\treturn errors.New(\"yikes\")\n\t\t\t},\n\t\t\tRunAfterOnFailOrCancel: func() error {\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\tif haveWePerformedFirstRoundOfCleanup {\n\t\t\t\t\tclose(cleanupFinished)\n\t\t\t\t}\n\t\t\t\thaveWePerformedFirstRoundOfCleanup = true\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\t_, sqlDB, cleanup := multiregionccltestutils.TestingCreateMultiRegionCluster(\n\t\tt, 1 /* numServers */, knobs, nil, /* baseDir */\n\t)\n\tdefer cleanup()\n\n\t// Setup the test.\n\t_, err := sqlDB.Exec(`\nCREATE DATABASE db WITH PRIMARY REGION \"us-east1\";\nCREATE TABLE db.t(k INT) LOCALITY REGIONAL BY TABLE IN PRIMARY REGION;\n`)\n\trequire.NoError(t, err)\n\n\t_, err = sqlDB.Exec(`ALTER DATABASE db DROP REGION \"us-east1\"`)\n\ttestutils.IsError(err, \"yikes\")\n\n\t<-cleanupFinished\n\n\trows := sqlDB.QueryRow(`SELECT count(*) FROM system.namespace WHERE name = 'crdb_internal_region'`)\n\tvar count int\n\terr = rows.Scan(&count)\n\trequire.NoError(t, err)\n\tif count != 0 {\n\t\tt.Fatal(\"expected crdb_internal_region not to be present in system.namespace\")\n\t}\n\n\t_, err = sqlDB.Exec(`ALTER DATABASE db PRIMARY REGION \"us-east1\"`)\n\trequire.NoError(t, err)\n\n\trows = sqlDB.QueryRow(`SELECT count(*) FROM system.namespace WHERE name = 'crdb_internal_region'`)\n\terr = rows.Scan(&count)\n\trequire.NoError(t, err)\n\tif count != 1 {\n\t\tt.Fatal(\"expected crdb_internal_region to be present in system.namespace\")\n\t}\n}", "func (e *bcsExecutor) Shutdown() {\n\te.isAskedShutdown = true\n\n\t//shutdown\n\te.innerShutdown()\n}", "func (fmd *FakeMysqlDaemon) StopSlave(hookExtraEnv map[string]string) error {\n\tfmd.Replicating = false\n\treturn nil\n}", "func (c *Client) Deregister(_ context.Context, serviceID string) error {\n\tdefer c.cancel()\n\treturn c.cli.Agent().ServiceDeregister(serviceID)\n}", "func (aio *AsyncIO) resubmit(re *runningEvent) error {\n\t// double check we are not about to roll outside our buffer\n\tif re.wrote >= uint(count(re.data)) {\n\t\treturn nil\n\t}\n\n\tnOffset := re.iocb.offset + int64(re.wrote)\n\tswitch re.iocb.OpCode() {\n\tcase IOCmdPread:\n\t\tnBuf := re.data[0][re.wrote:]\n\t\tre.iocb.PrepPread(nBuf, nOffset)\n\tcase IOCmdPwrite:\n\t\tnBuf := re.data[0][re.wrote:]\n\t\tre.iocb.PrepPwrite(nBuf, nOffset)\n\tcase IOCmdPreadv:\n\t\tconsume(&re.data, int64(re.wrote))\n\t\tre.iocb.PrepPreadv(re.data, nOffset)\n\tcase IOCmdPwritev:\n\t\tconsume(&re.data, int64(re.wrote))\n\t\tre.iocb.PrepPwritev(re.data, nOffset)\n\t}\n\n\t_, err := aio.ioctx.Submit([]*iocb{re.iocb})\n\treturn err\n}", "func (m *neighborEntryRWMutex) RUnlock() {\n\tm.mu.RUnlock()\n\tlocking.DelGLock(neighborEntryprefixIndex, -1)\n}", "func (nde NodeDownEvent) AsPartitionReconfigurationCompletedEvent() (*PartitionReconfigurationCompletedEvent, bool) {\n\treturn nil, false\n}", "func (device *DCV2Bricklet) DeregisterEmergencyShutdownCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackEmergencyShutdown), registrationId)\n}", "func (manager *Manager) unregister(msg interface{}) {\n\tmsgBytes, err := json.Marshal(msg)\n\tif err != nil {\n\t\tmanager.logger.Errorf(\"Error while marshalling unregister message: %v\", err)\n\t\treturn\n\t}\n\terr = SendMsg(nfvoManagerHandling, msgBytes, manager.Channel, manager.logger)\n\tif err != nil {\n\t\tmanager.logger.Errorf(\"Error unregistering: %v\", err)\n\t\treturn\n\t}\n}", "func (r *RegistrySyncJob) Ready(c client.Client, repl *regv1.ImageReplicate, patchRepl *regv1.ImageReplicate, _ bool) error {\n\tif repl.Status.Conditions.GetCondition(regv1.ConditionTypeImageReplicateSynchronized).Status == corev1.ConditionTrue {\n\t\treturn nil\n\t}\n\n\tvar err error = nil\n\tcondition := &status.Condition{\n\t\tStatus: corev1.ConditionFalse,\n\t\tType: regv1.ConditionTypeImageReplicateSynchronized,\n\t}\n\tdefer utils.SetCondition(err, patchRepl, condition)\n\n\tif err = r.get(c, repl); err != nil {\n\t\tr.logger.Error(err, \"get image replicate registry sync job error\")\n\t\treturn err\n\t}\n\n\tcondition.Status = corev1.ConditionTrue\n\n\treturn nil\n}", "func (s *Server) shutdown() error {\n\ts.shutdownLock.Lock()\n\tdefer s.shutdownLock.Unlock()\n\n\ts.unregister(s.initialEntry)\n\n\tif s.shouldShutdown {\n\t\treturn nil\n\t}\n\ts.shouldShutdown = true\n\n\ts.shutdownChan <- true\n\t//s.shutdownChanProbe <- true\n\n\tif s.ipv4conn != nil {\n\t\ts.ipv4conn.Close()\n\t}\n\tif s.ipv6conn != nil {\n\t\ts.ipv6conn.Close()\n\t}\n\n\tlog.Println(\"Waiting for goroutines to finish\")\n\ts.waitGroup.Wait()\n\n\treturn nil\n}", "func (mc *MonitorCore) Shutdown() {\n\tatomic.StoreInt32(&mc.shutdownCalled, 1)\n\n\tmc.cancel()\n}", "func (backend *Backend) Deregister(deviceID string) {\n\tif device, ok := backend.devices[deviceID]; ok {\n\t\tbackend.onDeviceUninit(deviceID)\n\t\tdelete(backend.devices, deviceID)\n\t\tbackend.DeregisterKeystore()\n\n\t\t// Old-school\n\t\tbackend.events <- backendEvent{Type: \"devices\", Data: \"registeredChanged\"}\n\t\t// New-school\n\t\tbackend.Notify(observable.Event{\n\t\t\tSubject: \"devices/registered\",\n\t\t\tAction: action.Reload,\n\t\t})\n\t\tswitch device.ProductName() {\n\t\tcase bitbox.ProductName:\n\t\t\tbackend.banners.Deactivate(banners.KeyBitBox01)\n\t\tcase bitbox02.ProductName:\n\t\t\tbackend.banners.Deactivate(banners.KeyBitBox02)\n\t\t}\n\n\t}\n}", "func (c *Cluster) UnRegister(node *NodeInfo) error {\n\tc.sessionManager.DeleteSession(node)\n\treturn c.channelManager.DeleteNode(node.NodeID)\n}", "func (s *Server) Shutdown() {\n\ts.Registry.Deregister(s.uuid)\n}", "func (s *Server) Shutdown() {\n\ts.Registry.Deregister(s.uuid)\n}", "func (s *RegistryServer) Stop() error {\n\treturn s.listener.Close()\n}", "func (cr *ConflictResolver) Shutdown() {\n\tcr.stopProcessing()\n}", "func (f *StarvingMutex) RUnlock() {\n\tf.mutex.Lock()\n\n\tif f.readersActive == 0 {\n\t\tpanic(\"RUnlock called without RLock\")\n\t}\n\n\tif f.writerActive {\n\t\tpanic(\"RUnlock called while writer active\")\n\t}\n\n\tf.readersActive--\n\n\tif f.readersActive == 0 && f.pendingWriters > 0 {\n\t\tf.mutex.Unlock()\n\t\tf.writerCond.Signal()\n\n\t\treturn\n\t}\n\tf.mutex.Unlock()\n}", "func (k *KubernetesExecutor) Shutdown(driver bindings.ExecutorDriver) {\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.doShutdown(driver)\n}", "func (d *DynamicSelect) shutDown() {\n\tif r := recover(); r != nil {\n\t\tlog.Printf(\"Recovered from panic in main DynamicSelect: %v\\n\", r)\n\t\tlog.Println(\"Attempting normal shutdown.\")\n\t}\n\n\t// just making sure.\n\td.killHeard = true\n\td.alive = false\n\td.running = false\n\tclose(d.done)\n\n\t// Tell the outside world we're done.\n\td.onKillAction()\n\n\t// Handle outstanding requests / a flood of closed messages.\n\tgo d.drainChannels()\n\n\t// Wait for internal listeners to halt.\n\td.listenerWG.Wait()\n\n\t// Make it painfully clear to the GC.\n\tclose(d.aggregator)\n\tclose(d.priorityAggregator)\n\tclose(d.onClose)\n}", "func (f *Sink) recoverFailed(endpoint *Endpoint) {\n\t// Ignore if we haven't failed\n\tif !endpoint.IsAlive() {\n\t\treturn\n\t}\n\n\tendpoint.mutex.Lock()\n\tendpoint.status = endpointStatusIdle\n\tendpoint.mutex.Unlock()\n\n\tf.failedList.Remove(&endpoint.failedElement)\n\tf.markReady(endpoint)\n}", "func (c *context) Reconnect() {\n\taclog.Debug(\"Invoking Run() on all the plugins registered for reconnection.\")\n\tc.reconnecting.Range(triggerAddReconnecting(aclog))\n}", "func (s *RC522Sensor) Unload() {\n\t// TODO: Need a PR to stop Wait cycle\n\terr := s.device.Halt()\n\tif err != nil {\n\t\ts.logger.Error(\"Failed to close SPI device\", err,\n\t\t\tlogBusIDToken, strconv.Itoa(s.Settings.BusID), logDeviceIDToken, strconv.Itoa(s.Settings.DeviceID))\n\t}\n\n\ts.closeBus()\n\ts.stop = true\n}", "func (crrfse ChaosRemoveReplicaFaultScheduledEvent) AsPartitionReconfigurationCompletedEvent() (*PartitionReconfigurationCompletedEvent, bool) {\n\treturn nil, false\n}", "func (device *ServoBrick) DeregisterPositionReachedCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackPositionReached), registrationId)\n}", "func (er *EventRelay) Disconnected(err error) {\n\tlogger.Warnf(\"Disconnected: %s. Attempting to reconnect...\\n\", err)\n\n\ter.ehmutex.Lock()\n\tdefer er.ehmutex.Unlock()\n\n\ter.eventHub = nil\n\n\tgo er.connectEventHub()\n}", "func (m *InMemManager) RUnlock(_ context.Context, token string) error {\n\tm.rw.RLock()\n\trw, ok := m.acqu[token]\n\tm.rw.RUnlock()\n\n\tif ok {\n\t\trw.RUnlock()\n\t}\n\n\treturn nil\n}", "func (s *EventService) Unregister(reg eventapi.Registration) {\n\ts.Submit(newUnregisterEvent(reg))\n}", "func (p *PRep) Deregister() {\n\tp.Cancel()\n\tpReps.Mutex.Lock()\n\tdelete(pReps.PReps, p.ID.String())\n\tpReps.Mutex.Unlock()\n\tif err := p.Websocket.Close(); err != nil {\n\t\tlog.Printf(\"Error closing prep: %s\", err.Error())\n\t}\n}", "func (device *DualButtonBricklet) DeregisterStateChangedCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackStateChanged), registrationId)\n}", "func (client InfraRoleInstancesClient) RebootResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusInternalServerError),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (e *errorMixin) resetError() {\n\te.once = &sync.Once{}\n\te.wg = &sync.WaitGroup{}\n\te.wg.Add(1)\n}" ]
[ "0.8607573", "0.7910841", "0.7796483", "0.599285", "0.56674284", "0.5653813", "0.5586281", "0.5373038", "0.5323152", "0.5305527", "0.52888405", "0.52545166", "0.5191827", "0.51574075", "0.5083771", "0.50417197", "0.49857327", "0.49296308", "0.49199247", "0.49157673", "0.4902719", "0.4881117", "0.48585606", "0.4856735", "0.4856028", "0.48492533", "0.47647884", "0.47316357", "0.46951753", "0.46760473", "0.46313575", "0.46284992", "0.4624299", "0.4606973", "0.4580125", "0.45705947", "0.45671248", "0.45643643", "0.45557287", "0.45544583", "0.45239103", "0.4514538", "0.45087448", "0.4489174", "0.4456876", "0.4456195", "0.44506207", "0.44474146", "0.44464383", "0.4444798", "0.44199568", "0.4417991", "0.4409398", "0.44050983", "0.44010448", "0.43945554", "0.43865848", "0.4369385", "0.43685478", "0.4356179", "0.43535742", "0.4350813", "0.43431798", "0.43179268", "0.43149364", "0.43144044", "0.43131775", "0.43048957", "0.429759", "0.4286946", "0.4274859", "0.42467263", "0.4246189", "0.42425188", "0.42363447", "0.42267677", "0.42208117", "0.42196938", "0.42145506", "0.4214176", "0.42132202", "0.42128584", "0.42128584", "0.42041072", "0.42009348", "0.41907692", "0.4188048", "0.41843668", "0.4178832", "0.41783646", "0.4175515", "0.41662645", "0.41618752", "0.4160489", "0.41596386", "0.41537246", "0.41445458", "0.41426176", "0.4141848", "0.41399306" ]
0.8559772
1
InitializeStaticPodsSource blocks until initial regstration is complete and then creates a static pod source using the given factory func.
func (k *KubernetesExecutor) InitializeStaticPodsSource(sourceFactory func()) { <-k.initialRegComplete if k.staticPodsConfig == nil { return } log.V(2).Infof("extracting static pods config to %s", k.staticPodsConfigPath) err := archive.UnzipDir(k.staticPodsConfig, k.staticPodsConfigPath) if err != nil { log.Errorf("Failed to extract static pod config: %v", err) return } log.V(2).Infof("initializing static pods source factory, configured at path %q", k.staticPodsConfigPath) sourceFactory() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewStaticSource(users ...string) *StaticSource {\n\tfor i, u := range users {\n\t\tusers[i] = strings.ToLower(u)\n\t}\n\tsort.Strings(users)\n\n\tss := &StaticSource{\n\t\tnextUser: ring.New(len(users)),\n\t\tusernames: make(map[string]bool, len(users)),\n\t}\n\tfor _, u := range users {\n\t\tss.usernames[u] = true\n\t\tss.nextUser.Value = u\n\t\tss.nextUser = ss.nextUser.Next()\n\t}\n\treturn ss\n}", "func NewStaticDiscovery(cfg config.DiscoveryConfig) interface{} {\n\n\td := Discovery{\n\t\topts: DiscoveryOpts{0},\n\t\tcfg: cfg,\n\t\tfetch: staticFetch,\n\t}\n\n\treturn &d\n}", "func PrebuiltStaticLibraryFactory() android.Module {\n\tmodule, _ := NewPrebuiltStaticLibrary(android.HostAndDeviceSupported)\n\treturn module.Init()\n}", "func NewStatic() filters.Spec { return &static{} }", "func NewStatic() filters.Spec { return &static{} }", "func Initialize(cfg Config) {\n\tvar err error\n\tif cfg.UseKms {\n\t\t// FIXME(xnum): set at cmd.\n\t\tif utils.FullnodeCluster != utils.Environment() {\n\t\t\tif err = initKmsClient(); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch cfg.Source {\n\tcase None:\n\t\tgetters = []Getter{noneGetter}\n\tcase K8S:\n\t\tgetters = []Getter{k8sGetter}\n\tcase File:\n\t\tgetters = []Getter{staticGetter}\n\t\tif err = initDataFromFile(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t// FIXME(xnum): not encourge to use. It depends on env.\n\tcase Auto:\n\t\tif utils.Environment() == utils.LocalDevelopment ||\n\t\t\tutils.Environment() == utils.CI {\n\t\t\tgetters = []Getter{staticGetter}\n\t\t\terr := initDataFromFile()\n\t\t\tif err != nil {\n\t\t\t\tlog.Panicln(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tgetters = []Getter{k8sGetter}\n\t}\n}", "func NewStaticPluginFactory(\n\tctx context.Context,\n\tft controller.Factory,\n\tbinaryID string,\n\tbus bus.Bus,\n) *StaticPluginFactory {\n\tnctx, nctxCancel := context.WithCancel(ctx)\n\treturn &StaticPluginFactory{\n\t\tFactory: ft,\n\t\tbinaryID: binaryID,\n\t\tbus: bus,\n\t\tctx: nctx,\n\t\tctxCancel: nctxCancel,\n\t}\n}", "func TestDynamicSource_Bootstrap(t *testing.T) {\n\tctx, cancel := context.WithTimeout(logr.NewContext(context.Background(), logtesting.NewTestLogger(t)), time.Second*40)\n\tdefer cancel()\n\n\tconfig, stop := framework.RunControlPlane(t, ctx)\n\tdefer stop()\n\n\tkubeClient, _, _, _ := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tsource := tls.DynamicSource{\n\t\tDNSNames: []string{\"example.com\"},\n\t\tAuthority: &authority.DynamicAuthority{\n\t\t\tSecretNamespace: namespace,\n\t\t\tSecretName: \"testsecret\",\n\t\t\tRESTConfig: config,\n\t\t},\n\t}\n\terrCh := make(chan error)\n\tdefer func() {\n\t\tcancel()\n\t\terr := <-errCh\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\t// run the dynamic authority controller in the background\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tif err := source.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {\n\t\t\terrCh <- fmt.Errorf(\"Unexpected error running source: %v\", err)\n\t\t}\n\t}()\n\n\t// allow the controller 5s to provision the Secret - this is far longer\n\t// than it should ever take.\n\tif err := wait.PollUntilContextCancel(ctx, time.Millisecond*500, true, func(ctx context.Context) (done bool, err error) {\n\t\tcert, err := source.GetCertificate(nil)\n\t\tif err == tls.ErrNotAvailable {\n\t\t\tt.Logf(\"GetCertificate has no certificate available, waiting...\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif cert == nil {\n\t\t\tt.Errorf(\"Returned certificate is nil\")\n\t\t}\n\t\tt.Logf(\"Got non-nil certificate from dynamic source\")\n\t\treturn true, nil\n\t}); err != nil {\n\t\tt.Errorf(\"Failed waiting for source to return a certificate: %v\", err)\n\t\treturn\n\t}\n}", "func Init(myIp string, namespace string, listOptions metav1.ListOptions, f NotifyFunc, client *kubernetes.Clientset, debugMode bool) ([]string, error) {\n\n\tlibConfig.debugMode = debugMode\n\n\t// Fetch initial pods from API\n\tinitialPods, err := getInitialPods(client, namespace, listOptions, myIp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"PodWatch: could not get initial pod list: %v\", err)\n\t}\n\n\tif len(initialPods) <= 0 {\n\t\treturn nil, errors.New(\"PodWatch: no pods detected, not even self\")\n\t}\n\tpodIps := initialPods.Keys()\n\n\t// Start monitoring for pod transitions, to keep pool up to date\n\tgo monitorPodState(client, namespace, listOptions, myIp, initialPods, f)\n\n\treturn podIps, nil\n}", "func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\tvar storageClient *storage.Client\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tglobal.assetsCollectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets\n\tglobal.ownerLabelKeyName = instanceDeployment.Core.SolutionSettings.Monitoring.LabelKeyNames.Owner\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tglobal.violationResolverLabelKeyName = instanceDeployment.Core.SolutionSettings.Monitoring.LabelKeyNames.ViolationResolver\n\tprojectID := instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\n\tstorageClient, err = storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"storage.NewClient(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\t// bucketHandle must be evaluated after storateClient init\n\tglobal.bucketHandle = storageClient.Bucket(instanceDeployment.Core.SolutionSettings.Hosting.GCS.Buckets.AssetsJSONFile.Name)\n\n\tglobal.cloudresourcemanagerService, err = cloudresourcemanager.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanager.NewService(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.cloudresourcemanagerServiceV2, err = cloudresourcemanagerv2.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanagerv2.NewService(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.firestoreClient, err = firestore.NewClient(ctx, projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient(ctx, projectID) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}", "func newStaticClients(cfg micro.CliConfig, protoFunc socket.ProtoFunc) *StaticClients {\n\treturn &StaticClients{\n\t\tclients: make(map[string]*micro.Client),\n\t\tcfg: cfg,\n\t\tprotoFunc: protoFunc,\n\t}\n}", "func createStaticPVC(ctx context.Context, f *framework.Framework,\n\tclient clientset.Interface, namespace string, defaultDatastore *object.Datastore,\n\tpandoraSyncWaitTime int) (string, *v1.PersistentVolumeClaim, *v1.PersistentVolume, *storagev1.StorageClass) {\n\tcurtime := time.Now().Unix()\n\n\tsc, err := createStorageClass(client, nil, nil, \"\", \"\", true, \"\")\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"Storage Class Name :%s\", sc.Name)\n\n\tginkgo.By(\"Creating FCD Disk\")\n\tcurtimeinstring := strconv.FormatInt(curtime, 10)\n\tfcdID, err := e2eVSphere.createFCD(ctx, \"BasicStaticFCD\"+curtimeinstring, diskSizeInMb, defaultDatastore.Reference())\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"FCD ID :\", fcdID)\n\n\tginkgo.By(fmt.Sprintf(\"Sleeping for %v seconds to allow newly created FCD:%s to sync with pandora\",\n\t\tpandoraSyncWaitTime, fcdID))\n\ttime.Sleep(time.Duration(pandoraSyncWaitTime) * time.Second)\n\n\t// Creating label for PV.\n\t// PVC will use this label as Selector to find PV\n\tstaticPVLabels := make(map[string]string)\n\tstaticPVLabels[\"fcd-id\"] = fcdID\n\n\tginkgo.By(\"Creating PV\")\n\tpv := getPersistentVolumeSpecWithStorageclass(fcdID, v1.PersistentVolumeReclaimDelete, sc.Name, nil, diskSize)\n\tpv, err = client.CoreV1().PersistentVolumes().Create(ctx, pv, metav1.CreateOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tpvName := pv.GetName()\n\n\tginkgo.By(\"Creating PVC\")\n\tpvc := getPVCSpecWithPVandStorageClass(\"static-pvc\", namespace, nil, pvName, sc.Name, diskSize)\n\tpvc, err = client.CoreV1().PersistentVolumeClaims(namespace).Create(ctx, pvc, metav1.CreateOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tginkgo.By(\"Waiting for claim to be in bound phase\")\n\terr = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client,\n\t\tnamespace, pvc.Name, framework.Poll, framework.ClaimProvisionTimeout)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tginkgo.By(\"Verifying CNS entry is present in cache\")\n\t_, err = e2eVSphere.queryCNSVolumeWithResult(pv.Spec.CSI.VolumeHandle)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tpvc, err = client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, pvc.Name, metav1.GetOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tpv = getPvFromClaim(client, namespace, pvc.Name)\n\tverifyBidirectionalReferenceOfPVandPVC(ctx, client, pvc, pv, fcdID)\n\n\tvolHandle := pv.Spec.CSI.VolumeHandle\n\n\t// Wait for PV and PVC to Bind\n\tframework.ExpectNoError(fpv.WaitOnPVandPVC(client, framework.NewTimeoutContextWithDefaults(), namespace, pv, pvc))\n\n\treturn volHandle, pvc, pv, sc\n}", "func InitServiceFactory(repo *repositories.Repository) *Service {\n\n\treturn &Service{\n\t\tAccountService: newAccountService(repo),\n\t\tUserService: newUserService(repo),\n\t\tTransactionService: newTransactionService(repo),\n\t}\n}", "func (c *transipDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {\n\tcl, err := kubernetes.NewForConfig(kubeClientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.client = cl\n\n\treturn nil\n}", "func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\tvar clientOption option.ClientOption\n\tvar ok bool\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tgciAdminUserToImpersonate := instanceDeployment.Settings.Instance.GCI.SuperAdminEmail\n\tglobal.collectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets\n\tglobal.GCIGroupMembersTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupMembers\n\tglobal.GCIGroupSettingsTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupSettings\n\tglobal.projectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\tglobal.retriesNumber = instanceDeployment.Settings.Service.RetriesNumber\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tkeyJSONFilePath := solution.PathToFunctionCode + instanceDeployment.Settings.Service.KeyJSONFileName\n\tserviceAccountEmail := fmt.Sprintf(\"%s@%s.iam.gserviceaccount.com\",\n\t\tinstanceDeployment.Core.ServiceName,\n\t\tinstanceDeployment.Core.SolutionSettings.Hosting.ProjectID)\n\n\tglobal.firestoreClient, err = firestore.NewClient(global.ctx, global.projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tserviceAccountKeyNames, err := gfs.ListKeyNames(ctx, global.firestoreClient, instanceDeployment.Core.ServiceName)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"gfs.ListKeyNames %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tif clientOption, ok = aut.GetClientOptionAndCleanKeys(ctx,\n\t\tserviceAccountEmail,\n\t\tkeyJSONFilePath,\n\t\tinstanceDeployment.Core.SolutionSettings.Hosting.ProjectID,\n\t\tgciAdminUserToImpersonate,\n\t\t[]string{\"https://www.googleapis.com/auth/apps.groups.settings\", \"https://www.googleapis.com/auth/admin.directory.group.readonly\"},\n\t\tserviceAccountKeyNames,\n\t\tinitID,\n\t\tglobal.microserviceName,\n\t\tglobal.instanceName,\n\t\tglobal.environment); !ok {\n\t\treturn fmt.Errorf(\"aut.GetClientOptionAndCleanKeys\")\n\t}\n\tglobal.dirAdminService, err = admin.NewService(ctx, clientOption)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"admin.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.groupsSettingsService, err = groupssettings.NewService(ctx, clientOption)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"groupssettings.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\tglobal.pubsubPublisherClient, err = pubsub.NewPublisherClient(global.ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"global.pubsubPublisherClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\tglobal.cloudresourcemanagerService, err = cloudresourcemanager.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanager.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\terr = gps.GetTopicList(global.ctx, global.pubsubPublisherClient, global.projectID, &global.topicList)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"gps.GetTopicList %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\treturn nil\n}", "func (p *Provisioner) createInitPod(pOpts *HelperPodOptions) error {\n\t//err := pOpts.validate()\n\tif err := pOpts.validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize HostPath builder and validate that\n\t// volume directory is not directly under root.\n\t// Extract the base path and the volume unique path.\n\tparentDir, volumeDir, vErr := hostpath.NewBuilder().WithPath(pOpts.path).\n\t\tWithCheckf(hostpath.IsNonRoot(), \"volume directory {%v} should not be under root directory\", pOpts.path).\n\t\tExtractSubPath()\n\tif vErr != nil {\n\t\treturn vErr\n\t}\n\n\tinitPod, _ := pod.NewBuilder().\n\t\tWithName(\"init-\" + pOpts.name).\n\t\tWithRestartPolicy(corev1.RestartPolicyNever).\n\t\tWithNodeName(pOpts.nodeName).\n\t\tWithContainerBuilder(\n\t\t\tcontainer.NewBuilder().\n\t\t\t\tWithName(\"local-path-init\").\n\t\t\t\tWithImage(p.helperImage).\n\t\t\t\tWithCommandNew(append(pOpts.cmdsForPath, filepath.Join(\"/data/\", volumeDir))).\n\t\t\t\tWithVolumeMountsNew([]corev1.VolumeMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"data\",\n\t\t\t\t\t\tReadOnly: false,\n\t\t\t\t\t\tMountPath: \"/data/\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t).\n\t\tWithVolumeBuilder(\n\t\t\tvolume.NewBuilder().\n\t\t\t\tWithName(\"data\").\n\t\t\t\tWithHostDirectory(parentDir),\n\t\t).\n\t\tBuild()\n\n\t//Launch the init pod.\n\tiPod, err := p.kubeClient.CoreV1().Pods(p.namespace).Create(initPod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\te := p.kubeClient.CoreV1().Pods(p.namespace).Delete(iPod.Name, &metav1.DeleteOptions{})\n\t\tif e != nil {\n\t\t\tglog.Errorf(\"unable to delete the helper pod: %v\", e)\n\t\t}\n\t}()\n\n\t//Wait for the cleanup pod to complete it job and exit\n\tcompleted := false\n\tfor i := 0; i < CmdTimeoutCounts; i++ {\n\t\tcheckPod, err := p.kubeClient.CoreV1().Pods(p.namespace).Get(iPod.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if checkPod.Status.Phase == corev1.PodSucceeded {\n\t\t\tcompleted = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\tif !completed {\n\t\treturn errors.Errorf(\"create process timeout after %v seconds\", CmdTimeoutCounts)\n\t}\n\n\treturn nil\n}", "func PrebuiltStubsSourcesFactory() android.Module {\n\tmodule := &PrebuiltStubsSources{}\n\n\tmodule.AddProperties(&module.properties)\n\n\tandroid.InitPrebuiltModule(module, &module.properties.Srcs)\n\tandroid.InitSdkAwareModule(module)\n\tInitDroiddocModule(module, android.HostAndDeviceSupported)\n\treturn module\n}", "func (c *customDNSProviderSolver) Initialize(kubeClientConfig *rest.Config, stopCh <-chan struct{}) error {\n\tcl, err := kubernetes.NewForConfig(kubeClientConfig)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to new kubernetes client: %v\", err)\n\t\treturn err\n\t}\n\tc.client = cl\n\n\tc.dnspod = make(map[int]*dnspod.Client)\n\n\treturn nil\n}", "func PrebuiltApisFactory() android.Module {\n\tmodule := &prebuiltApis{}\n\tmodule.AddProperties(&module.properties)\n\tandroid.InitAndroidModule(module)\n\tandroid.AddLoadHook(module, createPrebuiltApiModules)\n\treturn module\n}", "func PrebuiltApisFactory() android.Module {\n\tmodule := &prebuiltApis{}\n\tmodule.AddProperties(&module.properties)\n\tandroid.InitAndroidModule(module)\n\tandroid.AddLoadHook(module, createPrebuiltApiModules)\n\treturn module\n}", "func NewStaticProvider(groups []*targetgroup.Group) *StaticProvider {\n\tfor i, tg := range groups {\n\t\ttg.Source = fmt.Sprintf(\"%d\", i)\n\t}\n\treturn &StaticProvider{groups}\n}", "func New(name string, sourceType string, config *viper.Viper) (s SourceI, err error) {\n\t//setup agentHeader\n\tagentInfo := &AgentHeader{\n\t\tTenant: events.LookatchTenantInfo{\n\t\t\tID: config.GetString(\"agent.UUID\"),\n\t\t\tEnv: config.GetString(\"agent.env\"),\n\t\t},\n\t\tHostname: config.GetString(\"agent.Hostname\"),\n\t\tUUID: config.GetString(\"agent.UUID\"),\n\t}\n\n\tsourceCreatorFunc, found := Factory[sourceType]\n\tif !found {\n\t\treturn nil, errors.Errorf(\"Source type not found '%s'\", sourceType)\n\t}\n\n\tif !config.IsSet(\"sources.\" + name) {\n\t\treturn nil, errors.Errorf(\"no custom config found for source name '%s'\", name)\n\t}\n\tchannelSize := DefaultChannelSize\n\tif !config.IsSet(\"sources.\" + name + \".chan_size\") {\n\t\tchannelSize = config.GetInt(\"sources.\" + name + \".chan_size\")\n\t}\n\teventChan := make(chan events.LookatchEvent, channelSize)\n\tcommitChan := make(chan interface{}, channelSize)\n\n\tbaseSrc := &Source{\n\t\tName: name,\n\t\tOutputChannel: eventChan,\n\t\tCommitChannel: commitChan,\n\t\tAgentInfo: agentInfo,\n\t\tConf: config,\n\t\tOffset: 0,\n\t\tStatus: SourceStatusWaitingForMETA,\n\t}\n\n\ts, err = sourceCreatorFunc(baseSrc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Init()\n\treturn s, err\n}", "func InitDynamic() {\n\tvar plLoadWait sync.WaitGroup\n\tpls, err := loadPlugins(filepath.Join(buildcfg.LIBDIR, \"singularity/plugin/*\"))\n\tif err != nil {\n\t\tsylog.Fatalf(\"Unable to load plugins from dir: %s\", err)\n\t}\n\n\tfor _, pl := range pls {\n\t\tplLoadWait.Add(1)\n\t\tgo func(pl *plugin.Plugin) {\n\t\t\tdefer plLoadWait.Done()\n\t\t\tif err := initPlugin(pl); err != nil {\n\t\t\t\tsylog.Fatalf(\"Something went wrong: %s\", err)\n\t\t\t}\n\t\t}(pl)\n\t}\n\n\tplLoadWait.Wait()\n}", "func (f *factory) StaticClient() (*kubernetes.Clientset, error) {\n\tconf, err := f.RestConfig()\n\tif err != nil {\n\t\treturn &kubernetes.Clientset{}, err\n\t}\n\treturn kubernetes.NewForConfig(conf)\n}", "func (s *Schedule) StaticInit(n ir.Node) {\n\tif !s.tryStaticInit(n) {\n\t\tif base.Flag.Percent != 0 {\n\t\t\tir.Dump(\"StaticInit failed\", n)\n\t\t}\n\t\ts.append(n)\n\t}\n}", "func NewStaticRunner(path string) Run {\n\tif len(path) == 0 {\n\t\treturn nil\n\t}\n\t// TODO add more checks\n\treturn &staticRunner{configPath: path}\n}", "func initTestCase(f *framework.Framework, c clientset.Interface, pvConfig framework.PersistentVolumeConfig, pvcConfig framework.PersistentVolumeClaimConfig, ns, nodeName string) (*v1.Pod, *v1.PersistentVolume, *v1.PersistentVolumeClaim) {\n\tpv, pvc, err := framework.CreatePVPVC(c, pvConfig, pvcConfig, ns, false)\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePersistentVolumeClaim(c, pvc.Name, ns)\n\t\t\tframework.DeletePersistentVolume(c, pv.Name)\n\t\t}\n\t}()\n\tExpect(err).NotTo(HaveOccurred())\n\tpod := framework.MakePod(ns, []*v1.PersistentVolumeClaim{pvc}, true, \"\")\n\tpod.Spec.NodeName = nodeName\n\tframework.Logf(\"Creating NFS client pod.\")\n\tpod, err = c.CoreV1().Pods(ns).Create(pod)\n\tframework.Logf(\"NFS client Pod %q created on Node %q\", pod.Name, nodeName)\n\tExpect(err).NotTo(HaveOccurred())\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePodWithWait(f, c, pod)\n\t\t}\n\t}()\n\terr = framework.WaitForPodRunningInNamespace(c, pod)\n\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Pod %q timed out waiting for phase: Running\", pod.Name))\n\t// Return created api objects\n\tpod, err = c.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpvc, err = c.CoreV1().PersistentVolumeClaims(ns).Get(pvc.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpv, err = c.CoreV1().PersistentVolumes().Get(pv.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\treturn pod, pv, pvc\n}", "func New(userInput string, o Scope) (Source, func(), error) {\n\tfs := afero.NewOsFs()\n\tparsedScheme, location, err := detectScheme(fs, image.DetectSource, userInput)\n\tif err != nil {\n\t\treturn Source{}, func() {}, fmt.Errorf(\"unable to parse input=%q: %w\", userInput, err)\n\t}\n\n\tswitch parsedScheme {\n\tcase DirectoryScheme:\n\t\tfileMeta, err := fs.Stat(location)\n\t\tif err != nil {\n\t\t\treturn Source{}, func() {}, fmt.Errorf(\"unable to stat dir=%q: %w\", location, err)\n\t\t}\n\n\t\tif !fileMeta.IsDir() {\n\t\t\treturn Source{}, func() {}, fmt.Errorf(\"given path is not a directory (path=%q): %w\", location, err)\n\t\t}\n\n\t\ts, err := NewFromDirectory(location)\n\t\tif err != nil {\n\t\t\treturn Source{}, func() {}, fmt.Errorf(\"could not populate source from path=%q: %w\", location, err)\n\t\t}\n\t\treturn s, func() {}, nil\n\n\tcase ImageScheme:\n\t\timg, err := stereoscope.GetImage(location)\n\t\tcleanup := func() {\n\t\t\tstereoscope.Cleanup()\n\t\t}\n\n\t\tif err != nil || img == nil {\n\t\t\treturn Source{}, cleanup, fmt.Errorf(\"could not fetch image '%s': %w\", location, err)\n\t\t}\n\n\t\ts, err := NewFromImage(img, o, location)\n\t\tif err != nil {\n\t\t\treturn Source{}, cleanup, fmt.Errorf(\"could not populate source with image: %w\", err)\n\t\t}\n\t\treturn s, cleanup, nil\n\t}\n\n\treturn Source{}, func() {}, fmt.Errorf(\"unable to process input for scanning: '%s'\", userInput)\n}", "func buildInitData(source, target *expr.AttributeExpr, sourceVar, targetVar string, svcCtx *codegen.AttributeContext, proto, _, usesrc bool, sd *ServiceData) *InitData {\n\tvar (\n\t\tname string\n\t\tisStruct bool\n\t\tcode string\n\t\thelpers []*codegen.TransformFunctionData\n\t\targs []*InitArgData\n\t\terr error\n\t\tsrcCtx *codegen.AttributeContext\n\t\ttgtCtx *codegen.AttributeContext\n\n\t\t// pbCtx = protoBufTypeContext(sd.PkgName, sd.Scope, proto && svr || !proto && !svr)\n\t\tpbCtx = protoBufTypeContext(sd.PkgName, sd.Scope, false)\n\t)\n\t{\n\t\tname = \"New\"\n\t\tsrcCtx = pbCtx\n\t\ttgtCtx = svcCtx\n\t\tif proto {\n\t\t\tsrcCtx = svcCtx\n\t\t\ttgtCtx = pbCtx\n\t\t\tname += \"Proto\"\n\t\t}\n\t\tisStruct = expr.IsObject(target.Type) || expr.IsUnion(target.Type)\n\t\tif _, ok := source.Type.(expr.UserType); ok && usesrc {\n\t\t\tname += protoBufGoTypeName(source, sd.Scope)\n\t\t}\n\t\tn := protoBufGoTypeName(target, sd.Scope)\n\t\tif !isStruct {\n\t\t\t// If target is array, map, or primitive the name will be suffixed with\n\t\t\t// the definition (e.g int, []string, map[int]string) which is incorrect.\n\t\t\tn = protoBufGoTypeName(source, sd.Scope)\n\t\t}\n\t\tname += n\n\t\tcode, helpers, err = protoBufTransform(source, target, sourceVar, targetVar, srcCtx, tgtCtx, proto, true)\n\t\tif err != nil {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tsd.transformHelpers = codegen.AppendHelpers(sd.transformHelpers, helpers)\n\t\tif (!proto && !isEmpty(source.Type)) || (proto && !isEmpty(target.Type)) {\n\t\t\targs = []*InitArgData{{\n\t\t\t\tName: sourceVar,\n\t\t\t\tRef: sourceVar,\n\t\t\t\tTypeName: srcCtx.Scope.Name(source, srcCtx.Pkg(source), srcCtx.Pointer, srcCtx.UseDefault),\n\t\t\t\tTypeRef: srcCtx.Scope.Ref(source, srcCtx.Pkg(source)),\n\t\t\t\tExample: source.Example(expr.Root.API.ExampleGenerator),\n\t\t\t}}\n\t\t}\n\t}\n\treturn &InitData{\n\t\tName: name,\n\t\tReturnVarName: targetVar,\n\t\tReturnTypeRef: tgtCtx.Scope.Ref(target, tgtCtx.Pkg(target)),\n\t\tReturnIsStruct: isStruct,\n\t\tReturnTypePkg: tgtCtx.Pkg(target),\n\t\tCode: code,\n\t\tArgs: args,\n\t}\n}", "func staticClientGetter(cli snsclient.Client) snsclient.ClientGetterFunc {\n\treturn func(*v1alpha1.AWSSNSSource) (snsclient.Client, error) {\n\t\treturn cli, nil\n\t}\n}", "func staticClientGetter(cli snsclient.Client) snsclient.ClientGetterFunc {\n\treturn func(*v1alpha1.AWSSNSSource) (snsclient.Client, error) {\n\t\treturn cli, nil\n\t}\n}", "func (s *sdkAPIUpdater) setupDynamicClient(namespace string) error {\n\tscheme := runtime.NewScheme()\n\tcgoscheme.AddToScheme(scheme)\n\textscheme.AddToScheme(scheme)\n\terr := localv1.AddToScheme(scheme)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error adding localvolume to scheme: %v\", err)\n\t}\n\n\tcachedDiscoveryClient := cached.NewMemCacheClient(k8sclient.GetKubeClient().Discovery())\n\trestMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedDiscoveryClient)\n\trestMapper.Reset()\n\tdynClient, err := dynclient.New(k8sclient.GetKubeConfig(), dynclient.Options{Scheme: scheme, Mapper: restMapper})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error initializing dynamic client: %v\", err)\n\t}\n\tlocalVolumeList := &localv1.LocalVolumeList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"LocalVolume\",\n\t\t\tAPIVersion: localv1.SchemeGroupVersion.String(),\n\t\t},\n\t}\n\n\terr = wait.PollImmediate(time.Second, time.Second*10, func() (done bool, err error) {\n\t\terr = dynClient.List(goctx.TODO(), &dynclient.ListOptions{Namespace: namespace}, localVolumeList)\n\t\tif err != nil {\n\t\t\trestMapper.Reset()\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to build dynamic client: %v\", err)\n\t}\n\ts.dynClient = dynClient\n\treturn nil\n}", "func startInitializingWithIndividualPodIP() {\n\tfirstPodName, firstPodIP := getFirstResponsivePod()\n\tlog.Infof(\"entering the initialization mode against pod name %s with podIP %s\", firstPodName, firstPodIP)\n\n\tinitPodURL := \"http://\" + strings.TrimSpace(firstPodIP) + \":8200/v1/sys/init\"\n\tif !isInitializedOnPodIP(firstPodName, initPodURL) {\n\t\tinitJSONString := fmt.Sprintf(\"{ \\\"secret_shares\\\": %d, \\\"secret_threshold\\\": %d }\", common.SecShares, common.SecThreshold)\n\t\tinitResponse, err := FireRequest(initJSONString, initPodURL, nil, common.HttpMethodPUT)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Couldn't complete the init process, following error occurred: %v\", err)\n\t\t}\n\t\tparseJSONRespo(initResponse, &parsedKeys)\n\t\tlog.Debugf(\"The parsed Keys are %s \", parsedKeys)\n\t\terr = storeInSecret(parsedKeys)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error while storing the init keys into k8s secrets: %v\", err)\n\t\t}\n\t} else {\n\t\tlog.Infof(\"Vault running on %s pod is already initialized\", firstPodName)\n\t}\n}", "func NewHTTPClientFactory() *config.HTTPClientFactory {\n\tclientFunc := func(overrideTimeoutS *uint) *http.Client {\n\t\tvar timeoutS uint\n\t\tif overrideTimeoutS != nil {\n\t\t\ttimeoutS = *overrideTimeoutS\n\t\t} else {\n\t\t\ttimeoutS = config.HTTPRequestTimeoutS\n\t\t}\n\n\t\thttpClient := GetHTTPClient(int(timeoutS))\n\t\tif err := TrustIcpCert(httpClient); err != nil {\n\t\t\tFatal(FILE_IO_ERROR, err.Error())\n\t\t}\n\n\t\treturn httpClient\n\t}\n\n\t// get retry count and retry interval from env\n\tmaxRetries, retryInterval, err := GetHttpRetryParameters(5, 2)\n\tif err != nil {\n\t\tFatal(CLI_GENERAL_ERROR, err.Error())\n\t}\n\n\treturn &config.HTTPClientFactory{\n\t\tNewHTTPClient: clientFunc,\n\t\tRetryCount: maxRetries,\n\t\tRetryInterval: retryInterval,\n\t}\n}", "func (cfg *Static) New() (err error) {\n\treturn\n}", "func initUpdaters(ctx context.Context, opts *Opts, db *sqlx.DB, store vulnstore.Updater, dC chan context.CancelFunc, eC chan error) {\n\tcontrollers := map[string]*updater.Controller{}\n\n\tfor _, u := range opts.Updaters {\n\t\tif _, ok := controllers[u.Name()]; ok {\n\t\t\teC <- fmt.Errorf(\"duplicate updater found in UpdaterFactory. all names must be unique: %s\", u.Name())\n\t\t\treturn\n\t\t}\n\t\tcontrollers[u.Name()] = updater.NewController(&updater.Opts{\n\t\t\tUpdater: u,\n\t\t\tStore: store,\n\t\t\tName: u.Name(),\n\t\t\tInterval: opts.UpdateInterval,\n\t\t\tLock: pglock.NewLock(db, time.Duration(0)),\n\t\t\tUpdateOnStart: false,\n\t\t})\n\t}\n\n\t// limit initial concurrent updates\n\tcc := make(chan struct{}, DefaultUpdaterInitConcurrency)\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(controllers))\n\tfor _, v := range controllers {\n\t\tcc <- struct{}{}\n\t\tvv := v\n\t\tgo func() {\n\t\t\tupdateTO, cancel := context.WithTimeout(ctx, 10*time.Minute)\n\t\t\terr := vv.Update(updateTO)\n\t\t\tif err != nil {\n\t\t\t\teC <- fmt.Errorf(\"updater %s failed to update: %v\", vv.Name, err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t\tcancel()\n\t\t\t<-cc\n\t\t}()\n\t}\n\twg.Wait()\n\tclose(eC)\n\n\t// start all updaters and return context\n\tctx, cancel := context.WithCancel(ctx)\n\tfor _, v := range controllers {\n\t\tv.Start(ctx)\n\t}\n\tdC <- cancel\n}", "func Initialize(\n\tctx context.Context,\n\t// configuration\n\tcfg *config.TemporalConfig,\n\tversion string,\n\topts Options,\n\tclients Clients,\n\t// API dependencies\n\tl *zap.SugaredLogger,\n\n) (*API, error) {\n\tvar (\n\t\terr error\n\t\trouter = gin.Default()\n\t)\n\t// update dev mode\n\tdev = opts.DevMode\n\tl = l.Named(\"api\")\n\tim, err := rtfs.NewManager(\n\t\tcfg.IPFS.APIConnection.Host+\":\"+cfg.IPFS.APIConnection.Port,\n\t\t\"\", time.Minute*60,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timCluster, err := rtfscluster.Initialize(\n\t\tctx,\n\t\tcfg.IPFSCluster.APIConnection.Host,\n\t\tcfg.IPFSCluster.APIConnection.Port,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set up API struct\n\tapi, err := new(cfg, router, l, clients, im, imCluster, opts.DebugLogging)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapi.version = version\n\n\t// init routes\n\tif err = api.setupRoutes(); err != nil {\n\t\treturn nil, err\n\t}\n\tapi.l.Info(\"api initialization successful\")\n\n\t// return our configured API service\n\treturn api, nil\n}", "func NewFactory() Factory {\n\t// if an envoy binary is explicitly specified, use it\n\tenvoyPath := os.Getenv(testutils.EnvoyBinary)\n\tif envoyPath != \"\" {\n\t\tlog.Printf(\"Using envoy from environment variable: %s\", envoyPath)\n\t\treturn NewLinuxFactory(bootstrapTemplate, envoyPath, \"\")\n\t}\n\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tlog.Printf(\"Using docker to run envoy\")\n\n\t\timage := fmt.Sprintf(\"quay.io/solo-io/gloo-envoy-wrapper:%s\", mustGetEnvoyWrapperTag())\n\t\treturn NewDockerFactory(bootstrapTemplate, image)\n\n\tcase \"linux\":\n\t\ttmpdir, err := os.MkdirTemp(os.Getenv(\"HELPER_TMP\"), \"envoy\")\n\t\tif err != nil {\n\t\t\tginkgo.Fail(fmt.Sprintf(\"failed to create tmp dir: %v\", err))\n\t\t}\n\n\t\timage := fmt.Sprintf(\"quay.io/solo-io/envoy-gloo:%s\", mustGetEnvoyGlooTag())\n\n\t\tbinaryPath, err := utils.GetBinary(utils.GetBinaryParams{\n\t\t\tFilename: envoyBinaryName,\n\t\t\tDockerImage: image,\n\t\t\tDockerPath: \"/usr/local/bin/envoy\",\n\t\t\tEnvKey: testutils.EnvoyBinary, // this is inert here since we already check the env in this function, but leaving it for future compatibility\n\t\t\tTmpDir: tmpdir,\n\t\t})\n\t\tif err != nil {\n\t\t\tginkgo.Fail(fmt.Sprintf(\"failed to get binary: %v\", err))\n\t\t}\n\t\treturn NewLinuxFactory(bootstrapTemplate, binaryPath, tmpdir)\n\n\tdefault:\n\t\tginkgo.Fail(\"Unsupported OS: \" + runtime.GOOS)\n\t}\n\treturn nil\n}", "func (svc *Service) Init(ctx context.Context, cfg *config.Configuration, buildTime, gitCommit, version string) (err error) {\n\n\tsvc.cfg = cfg\n\n\t// Get mongoDB connection (non-fatal)\n\tsvc.mongoDataStore, err = getMongoDataStore(svc.cfg)\n\tif err != nil {\n\t\tlog.Event(ctx, \"mongodb datastore error\", log.ERROR, log.Error(err))\n\t}\n\n\t// Get data baker kafka producer\n\tsvc.dataBakerProducer, err = getKafkaProducer(ctx, svc.cfg.Brokers, svc.cfg.DatabakerImportTopic, svc.cfg.KafkaMaxBytes)\n\tif err != nil {\n\t\tlog.Event(ctx, \"databaker kafka producer error\", log.FATAL, log.Error(err))\n\t\treturn err\n\t}\n\n\t// Get input file available kafka producer\n\tsvc.inputFileAvailableProducer, err = getKafkaProducer(ctx, svc.cfg.Brokers, svc.cfg.InputFileAvailableTopic, svc.cfg.KafkaMaxBytes)\n\tif err != nil {\n\t\tlog.Event(ctx, \"direct kafka producer error\", log.FATAL, log.Error(err))\n\t\treturn err\n\t}\n\n\t// Create Identity Client\n\tsvc.identityClient = clientsidentity.New(svc.cfg.ZebedeeURL)\n\n\t// Create dataset and recie API clients.\n\t// TODO: We should consider replacing these with the corresponding dp-api-clients-go clients\n\tclient := dphttp.NewClient()\n\tsvc.datasetAPI = &dataset.API{Client: client, URL: svc.cfg.DatasetAPIURL, ServiceAuthToken: svc.cfg.ServiceAuthToken}\n\tsvc.recipeAPI = &recipe.API{Client: client, URL: svc.cfg.RecipeAPIURL}\n\n\t// Get HealthCheck and register checkers\n\tversionInfo, err := healthcheck.NewVersionInfo(buildTime, gitCommit, version)\n\tif err != nil {\n\t\tlog.Event(ctx, \"error creating version info\", log.FATAL, log.Error(err))\n\t\treturn err\n\t}\n\tsvc.healthCheck = getHealthCheck(versionInfo, svc.cfg.HealthCheckCriticalTimeout, svc.cfg.HealthCheckInterval)\n\tif err := svc.registerCheckers(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"unable to register checkers\")\n\t}\n\n\t// Get HTTP router and server with middleware\n\tr := mux.NewRouter()\n\tm := svc.createMiddleware(svc.cfg)\n\tsvc.server = getHTTPServer(svc.cfg.BindAddr, m.Then(r))\n\n\t// Create API with job service\n\turlBuilder := url.NewBuilder(svc.cfg.Host, svc.cfg.DatasetAPIURL)\n\tjobQueue := importqueue.CreateImportQueue(svc.dataBakerProducer.Channels().Output, svc.inputFileAvailableProducer.Channels().Output)\n\tjobService := job.NewService(svc.mongoDataStore, jobQueue, svc.datasetAPI, svc.recipeAPI, urlBuilder)\n\tsvc.importAPI = api.Setup(r, svc.mongoDataStore, jobService, cfg)\n\treturn nil\n}", "func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {\n\tabsolutePath := path.Join(group.prefix, relativePath) // client path\n\tfileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) // server path\n\n\treturn func(ctx *Context) {\n\t\t// Check whether the file exists\n\t\tfile := ctx.Param(\"filepath\") // custom parameter name\n\t\tif _, err := fs.Open(file); err != nil {\n\t\t\tctx.Fail(http.StatusNotFound, \"Status Not Found: \"+ctx.Pattern)\n\t\t\treturn\n\t\t}\n\n\t\t// Serve file content\n\t\tfileServer.ServeHTTP(ctx.RespWriter, ctx.Req)\n\t}\n}", "func (tf *factory) makeK8sFileSource(source *sources.LogSource) (*sources.LogSource, error) {\n\tcontainerID := source.Config.Identifier\n\n\tpod, err := tf.workloadmetaStore.GetKubernetesPodForContainer(containerID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot find pod for container %q: %w\", containerID, err)\n\t}\n\n\tvar container *workloadmeta.OrchestratorContainer\n\tfor _, pc := range pod.Containers {\n\t\tif pc.ID == containerID {\n\t\t\tcontainer = &pc\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif container == nil {\n\t\t// this failure is impossible, as GetKubernetesPodForContainer found\n\t\t// the pod by searching for this container\n\t\treturn nil, fmt.Errorf(\"cannot find container %q in pod %q\", containerID, pod.Name)\n\t}\n\n\t// get the path for the discovered pod and container\n\t// TODO: need a different base path on windows?\n\tpath := findK8sLogPath(pod, container.Name)\n\n\t// Note that it's not clear from k8s documentation that the container logs,\n\t// or even the directory containing these logs, must exist at this point.\n\t// To avoid incorrectly falling back to socket logging (or failing to log\n\t// entirely) we do not check for the file here. This matches older\n\t// kubernetes-launcher behavior.\n\n\tsourceName, serviceName := tf.defaultSourceAndService(source, containersorpods.LogPods)\n\n\t// New file source that inherits most of its parent's properties\n\tfileSource := sources.NewLogSource(\n\t\tfmt.Sprintf(\"%s/%s/%s\", pod.Namespace, pod.Name, container.Name),\n\t\t&config.LogsConfig{\n\t\t\tType: config.FileType,\n\t\t\tIdentifier: containerID,\n\t\t\tPath: path,\n\t\t\tService: serviceName,\n\t\t\tSource: sourceName,\n\t\t\tTags: source.Config.Tags,\n\t\t\tProcessingRules: source.Config.ProcessingRules,\n\t\t\tAutoMultiLine: source.Config.AutoMultiLine,\n\t\t\tAutoMultiLineSampleSize: source.Config.AutoMultiLineSampleSize,\n\t\t\tAutoMultiLineMatchThreshold: source.Config.AutoMultiLineMatchThreshold,\n\t\t})\n\n\tswitch source.Config.Type {\n\tcase config.DockerType:\n\t\t// docker runtime uses SourceType \"docker\"\n\t\tfileSource.SetSourceType(sources.DockerSourceType)\n\tdefault:\n\t\t// containerd runtime uses SourceType \"kubernetes\"\n\t\tfileSource.SetSourceType(sources.KubernetesSourceType)\n\t}\n\n\treturn fileSource, nil\n}", "func NewStaticResourceSnapshot(resourcePool *poolV1.ResourcePoolConfig, machines []*machineTypeV1.MachineTypeConfig,\n\tnodes []*k8sCore.Node, pods []*k8sCore.Pod, nodeBootstrapThreshold time.Duration,\n\tincludeKubeletBackend bool) *ResourceSnapshot {\n\tsnapshot := ResourceSnapshot{\n\t\tResourcePoolName: resourcePool.Name,\n\t\tResourcePool: resourcePool,\n\t\tNodeBootstrapThreshold: nodeBootstrapThreshold,\n\t\tIncludeKubeletBackend: includeKubeletBackend,\n\t\tMachines: machines,\n\t}\n\tsnapshot.updateNodeData(nodes)\n\tsnapshot.updatePodData(pods)\n\treturn &snapshot\n}", "func InitConfigFactory(f string, force bool) {\n\n\tif !force && APIConfig != nil {\n\t\treturn\n\t}\n\n\tcontent, err := ioutil.ReadFile(f)\n\tcheckErr(err)\n\n\tAPIConfig = &Config{}\n\n\terr = yaml.Unmarshal([]byte(content), &APIConfig)\n\tcheckErr(err)\n\tlogger.GNBLog.Infof(\"Successfully load gNB API module configuration %s\", f)\n}", "func (*Factory) Init(m *workflow.Manager, w *workflowpb.Workflow, args []string) error {\n\tsubFlags := flag.NewFlagSet(horizontalReshardingFactoryName, flag.ContinueOnError)\n\tkeyspace := subFlags.String(\"keyspace\", \"\", \"Name of keyspace to perform horizontal resharding\")\n\tvtworkersStr := subFlags.String(\"vtworkers\", \"\", \"A comma-separated list of vtworker addresses\")\n\texcludeTablesStr := subFlags.String(\"exclude_tables\", \"\", \"A comma-separated list of tables to exclude\")\n\tsourceShardsStr := subFlags.String(\"source_shards\", \"\", \"A comma-separated list of source shards\")\n\tdestinationShardsStr := subFlags.String(\"destination_shards\", \"\", \"A comma-separated list of destination shards\")\n\tminHealthyRdonlyTablets := subFlags.String(\"min_healthy_rdonly_tablets\", \"1\", \"Minimum number of healthy RDONLY tablets required in source shards\")\n\tskipSplitRatioCheck := subFlags.Bool(\"skip_split_ratio_check\", false, \"Skip validation on minimum number of healthy RDONLY tablets\")\n\tsplitCmd := subFlags.String(\"split_cmd\", \"SplitClone\", \"Split command to use to perform horizontal resharding (either SplitClone or LegacySplitClone)\")\n\tsplitDiffCmd := subFlags.String(\"split_diff_cmd\", \"SplitDiff\", \"Split diff command to use to perform horizontal resharding (either SplitDiff or MultiSplitDiff)\")\n\tsplitDiffDestTabletType := subFlags.String(\"split_diff_dest_tablet_type\", \"RDONLY\", \"Specifies tablet type to use in destination shards while performing SplitDiff operation\")\n\tphaseEnaableApprovalsDesc := fmt.Sprintf(\"Comma separated phases that require explicit approval in the UI to execute. Phase names are: %v\", strings.Join(WorkflowPhases(), \",\"))\n\tphaseEnableApprovalsStr := subFlags.String(\"phase_enable_approvals\", strings.Join(WorkflowPhases(), \",\"), phaseEnaableApprovalsDesc)\n\tuseConsistentSnapshot := subFlags.Bool(\"use_consistent_snapshot\", false, \"Instead of pausing replication on the source, uses transactions with consistent snapshot to have a stable view of the data.\")\n\n\tif err := subFlags.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif *keyspace == \"\" || *vtworkersStr == \"\" || *minHealthyRdonlyTablets == \"\" || *splitCmd == \"\" || *splitDiffCmd == \"\" {\n\t\treturn fmt.Errorf(\"keyspace name, min healthy rdonly tablets, split command, and vtworkers information must be provided for horizontal resharding\")\n\t}\n\n\tvtworkers := strings.Split(*vtworkersStr, \",\")\n\texcludeTables := strings.Split(*excludeTablesStr, \",\")\n\tsourceShards := strings.Split(*sourceShardsStr, \",\")\n\tdestinationShards := strings.Split(*destinationShardsStr, \",\")\n\tphaseEnableApprovals := parsePhaseEnableApprovals(*phaseEnableApprovalsStr)\n\tfor _, phase := range phaseEnableApprovals {\n\t\tvalidPhase := false\n\t\tfor _, registeredPhase := range WorkflowPhases() {\n\t\t\tif phase == registeredPhase {\n\t\t\t\tvalidPhase = true\n\t\t\t}\n\t\t}\n\t\tif !validPhase {\n\t\t\treturn fmt.Errorf(\"invalid phase in phase_enable_approvals: %v\", phase)\n\t\t}\n\t}\n\tuseConsistentSnapshotArg := \"\"\n\tif *useConsistentSnapshot {\n\t\tuseConsistentSnapshotArg = \"true\"\n\t}\n\n\terr := validateWorkflow(m, *keyspace, vtworkers, sourceShards, destinationShards, *minHealthyRdonlyTablets, *skipSplitRatioCheck)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.Name = fmt.Sprintf(\"Reshard shards %v into shards %v of keyspace %v.\", *keyspace, *sourceShardsStr, *destinationShardsStr)\n\tcheckpoint, err := initCheckpoint(*keyspace, vtworkers, excludeTables, sourceShards, destinationShards, *minHealthyRdonlyTablets, *splitCmd, *splitDiffCmd, *splitDiffDestTabletType, useConsistentSnapshotArg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheckpoint.Settings[\"phase_enable_approvals\"] = *phaseEnableApprovalsStr\n\n\tw.Data, err = proto.Marshal(checkpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Init(clusterDir, templateDir string) error {\n\treturn terraformExec(clusterDir, \"init\", templateDir)\n}", "func SmokeCloudSchedulerSourceSetup(t *testing.T, authConfig lib.AuthConfig) {\n\tclient := lib.Setup(t, true, authConfig.WorkloadIdentity)\n\tdefer lib.TearDown(client)\n\n\tsName := \"scheduler-test\"\n\n\tscheduler := kngcptesting.NewCloudSchedulerSource(sName, client.Namespace,\n\t\tkngcptesting.WithCloudSchedulerSourceLocation(\"us-central1\"),\n\t\tkngcptesting.WithCloudSchedulerSourceData(\"my test data\"),\n\t\tkngcptesting.WithCloudSchedulerSourceSchedule(\"* * * * *\"),\n\t\tkngcptesting.WithCloudSchedulerSourceSink(lib.ServiceGVK, \"event-display\"),\n\t\tkngcptesting.WithCloudSchedulerSourceGCPServiceAccount(authConfig.PubsubServiceAccount),\n\t)\n\n\tclient.CreateSchedulerOrFail(scheduler)\n\tclient.Core.WaitForResourceReadyOrFail(sName, lib.CloudSchedulerSourceTypeMeta)\n}", "func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tglobal.projectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\n\tglobal.dumpName = fmt.Sprintf(\"%s/%s.dump\",\n\t\tinstanceDeployment.Core.SolutionSettings.Hosting.GCS.Buckets.CAIExport.Name,\n\t\tos.Getenv(\"K_SERVICE\"))\n\n\tvar gcsDestinationURI assetpb.GcsDestination_Uri\n\tgcsDestinationURI.Uri = fmt.Sprintf(\"gs://%s\", global.dumpName)\n\n\tvar gcsDestination assetpb.GcsDestination\n\tgcsDestination.ObjectUri = &gcsDestinationURI\n\n\tvar outputConfigGCSDestination assetpb.OutputConfig_GcsDestination\n\toutputConfigGCSDestination.GcsDestination = &gcsDestination\n\n\tvar outputConfig assetpb.OutputConfig\n\toutputConfig.Destination = &outputConfigGCSDestination\n\n\tglobal.request = &assetpb.ExportAssetsRequest{}\n\tswitch instanceDeployment.Settings.Instance.CAI.ContentType {\n\tcase \"RESOURCE\":\n\t\tglobal.request.ContentType = assetpb.ContentType_RESOURCE\n\tcase \"IAM_POLICY\":\n\t\tglobal.request.ContentType = assetpb.ContentType_IAM_POLICY\n\tdefault:\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"unsupported content type: %s\", instanceDeployment.Settings.Instance.CAI.ContentType),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.request.Parent = instanceDeployment.Settings.Instance.CAI.Parent\n\tglobal.request.AssetTypes = instanceDeployment.Settings.Instance.CAI.AssetTypes\n\tglobal.request.OutputConfig = &outputConfig\n\n\tglobal.assetClient, err = asset.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"asset.NewClient(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.firestoreClient, err = firestore.NewClient(global.ctx, global.projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}", "func newFactory() func(config *client.Config) (client.Client, *probe.Error) {\n\tclientCache := make(map[uint32]minio.CloudStorageAPI)\n\tmutex := &sync.Mutex{}\n\n\t// Return New function.\n\treturn func(config *client.Config) (client.Client, *probe.Error) {\n\t\tu := client.NewURL(config.HostURL)\n\t\ttransport := http.DefaultTransport\n\t\tif config.Debug == true {\n\t\t\tif config.Signature == \"S3v4\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)\n\t\t\t}\n\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)\n\t\t\t}\n\t\t}\n\n\t\t// New S3 configuration.\n\t\ts3Conf := minio.Config{\n\t\t\tAccessKeyID: config.AccessKey,\n\t\t\tSecretAccessKey: config.SecretKey,\n\t\t\tTransport: transport,\n\t\t\tEndpoint: u.Scheme + u.SchemeSeparator + u.Host,\n\t\t\tSignature: func() minio.SignatureType {\n\t\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\t\treturn minio.SignatureV2\n\t\t\t\t}\n\t\t\t\treturn minio.SignatureV4\n\t\t\t}(),\n\t\t}\n\n\t\ts3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)\n\n\t\t// Generate a hash out of s3Conf.\n\t\tconfHash := fnv.New32a()\n\t\tconfHash.Write([]byte(s3Conf.Endpoint + s3Conf.AccessKeyID + s3Conf.SecretAccessKey))\n\t\tconfSum := confHash.Sum32()\n\n\t\t// Lookup previous cache by hash.\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\t\tvar api minio.CloudStorageAPI\n\t\tfound := false\n\t\tif api, found = clientCache[confSum]; !found {\n\t\t\t// Not found. Instantiate a new minio client.\n\t\t\tvar e error\n\t\t\tapi, e = minio.New(s3Conf)\n\t\t\tif e != nil {\n\t\t\t\treturn nil, probe.NewError(e)\n\t\t\t}\n\t\t\t// Cache the new minio client with hash of config as key.\n\t\t\tclientCache[confSum] = api\n\t\t}\n\n\t\ts3Clnt := &s3Client{\n\t\t\tmu: new(sync.Mutex),\n\t\t\tapi: api,\n\t\t\thostURL: u,\n\t\t\tvirtualStyle: isVirtualHostStyle(u.Host),\n\t\t}\n\t\treturn s3Clnt, nil\n\t}\n}", "func initializeResources(ctx context.Context, f *framework.Framework, protocols []v1.Protocol, ports []int32) *kubeManager {\n\tk8s, err := initializeCluster(ctx, f, protocols, ports)\n\tframework.ExpectNoError(err, \"unable to initialize resources\")\n\treturn k8s\n}", "func (c *MasterConfig) NewOpenShiftControllerPreStartInitializers() (map[string]controller.InitFunc, error) {\n\tret := map[string]controller.InitFunc{}\n\n\tsaToken := controller.ServiceAccountTokenControllerOptions{\n\t\tRootClientBuilder: kubecontroller.SimpleControllerClientBuilder{\n\t\t\tClientConfig: &c.PrivilegedLoopbackClientConfig,\n\t\t},\n\t}\n\n\tif len(c.Options.ServiceAccountConfig.PrivateKeyFile) == 0 {\n\t\tglog.Infof(\"Skipped starting Service Account Token Manager, no private key specified\")\n\t\treturn nil, nil\n\t}\n\n\tvar err error\n\n\tsaToken.PrivateKey, err = serviceaccount.ReadPrivateKey(c.Options.ServiceAccountConfig.PrivateKeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading signing key for Service Account Token Manager: %v\", err)\n\t}\n\n\tif len(c.Options.ServiceAccountConfig.MasterCA) > 0 {\n\t\tsaToken.RootCA, err = ioutil.ReadFile(c.Options.ServiceAccountConfig.MasterCA)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading master ca file for Service Account Token Manager: %s: %v\", c.Options.ServiceAccountConfig.MasterCA, err)\n\t\t}\n\t\tif _, err := cert.ParseCertsPEM(saToken.RootCA); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing master ca file for Service Account Token Manager: %s: %v\", c.Options.ServiceAccountConfig.MasterCA, err)\n\t\t}\n\t}\n\n\tif c.Options.ControllerConfig.ServiceServingCert.Signer != nil && len(c.Options.ControllerConfig.ServiceServingCert.Signer.CertFile) > 0 {\n\t\tcertFile := c.Options.ControllerConfig.ServiceServingCert.Signer.CertFile\n\t\tserviceServingCA, err := ioutil.ReadFile(certFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading ca file for Service Serving Certificate Signer: %s: %v\", certFile, err)\n\t\t}\n\t\tif _, err := crypto.CertsFromPEM(serviceServingCA); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing ca file for Service Serving Certificate Signer: %s: %v\", certFile, err)\n\t\t}\n\n\t\t// if we have a rootCA bundle add that too. The rootCA will be used when hitting the default master service, since those are signed\n\t\t// using a different CA by default. The rootCA's key is more closely guarded than ours and if it is compromised, that power could\n\t\t// be used to change the trusted signers for every pod anyway, so we're already effectively trusting it.\n\t\tif len(saToken.RootCA) > 0 {\n\t\t\tsaToken.ServiceServingCA = append(saToken.ServiceServingCA, saToken.RootCA...)\n\t\t\tsaToken.ServiceServingCA = append(saToken.ServiceServingCA, []byte(\"\\n\")...)\n\t\t}\n\t\tsaToken.ServiceServingCA = append(saToken.ServiceServingCA, serviceServingCA...)\n\t}\n\t// this matches the upstream name\n\tret[\"serviceaccount-token\"] = saToken.RunController\n\n\treturn ret, nil\n}", "func Init(endpoint, region, secretKeySecretPath, accessKeySecretPath string, tlsEnabled bool) (faasflow.DataStore, error) {\n\tminioDataStore := &MinioDataStore{}\n\n\tminioDataStore.region = region\n\n\tminioClient, connectErr := connectToMinio(endpoint, secretKeySecretPath, accessKeySecretPath, tlsEnabled)\n\tif connectErr != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to initialize minio, error %s\", connectErr.Error())\n\t}\n\tminioDataStore.minioClient = minioClient\n\n\treturn minioDataStore, nil\n}", "func MakeFactory(ctor Ctor, logger *zap.Logger) Factory {\n\treturn func(t *testing.T, r *TableRow) (controller.Reconciler, ActionRecorderList, EventList, *FakeStatsReporter) {\n\t\tls := NewListers(r.Objects)\n\n\t\tctx := context.Background()\n\t\tctx = logging.WithLogger(ctx, logger.Sugar())\n\n\t\tctx, kubeClient := fakekubeclient.With(ctx, ls.GetKubeObjects()...)\n\t\tctx, eventingClient := fakeeventingclient.With(ctx, ls.GetEventingObjects()...)\n\t\tctx, legacy := fakelegacyclient.With(ctx, ls.GetLegacyObjects()...)\n\t\tctx, client := fakeknativekafkaclient.With(ctx, ls.GetKafkaChannelObjects()...)\n\n\t\tdynamicScheme := runtime.NewScheme()\n\t\tfor _, addTo := range clientSetSchemes {\n\t\t\taddTo(dynamicScheme)\n\t\t}\n\n\t\tctx, dynamicClient := fakedynamicclient.With(ctx, dynamicScheme, ls.GetAllObjects()...)\n\n\t\teventRecorder := record.NewFakeRecorder(maxEventBufferSize)\n\t\tctx = controller.WithEventRecorder(ctx, eventRecorder)\n\t\tstatsReporter := &FakeStatsReporter{}\n\n\t\t// Set up our Controller from the fakes.\n\t\tc := ctor(ctx, &ls, configmap.NewStaticWatcher())\n\n\t\tfor _, reactor := range r.WithReactors {\n\t\t\tkubeClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tclient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tlegacy.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tdynamicClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\teventingClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t}\n\n\t\t// Validate all Create operations through the eventing client.\n\t\tclient.PrependReactor(\"create\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateCreates(context.Background(), action)\n\t\t})\n\t\tclient.PrependReactor(\"update\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateUpdates(context.Background(), action)\n\t\t})\n\n\t\t// Validate all Create operations through the legacy client.\n\t\tlegacy.PrependReactor(\"create\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateCreates(ctx, action)\n\t\t})\n\t\tlegacy.PrependReactor(\"update\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateUpdates(ctx, action)\n\t\t})\n\n\t\tactionRecorderList := ActionRecorderList{dynamicClient, client, kubeClient, legacy}\n\t\teventList := EventList{Recorder: eventRecorder}\n\n\t\treturn c, actionRecorderList, eventList, statsReporter\n\t}\n}", "func New(targetNamespace string,\n\tpodLabelSelector labels.Selector,\n\toperatorClient operatorv1helpers.OperatorClient,\n\tkubeInformersForNamespaces operatorv1helpers.KubeInformersForNamespaces,\n\tstartupMonitorEnabledFn func() (bool, error),\n\teventRecorder events.Recorder) (factory.Controller, error) {\n\tif podLabelSelector == nil {\n\t\treturn nil, fmt.Errorf(\"StaticPodFallbackConditionController: missing required podLabelSelector\")\n\t}\n\tif podLabelSelector.Empty() {\n\t\treturn nil, fmt.Errorf(\"StaticPodFallbackConditionController: podLabelSelector cannot be empty\")\n\t}\n\tfd := &staticPodFallbackConditionController{\n\t\toperatorClient: operatorClient,\n\t\tpodLabelSelector: podLabelSelector,\n\t\tpodLister: kubeInformersForNamespaces.InformersFor(targetNamespace).Core().V1().Pods().Lister().Pods(targetNamespace),\n\t\tstartupMonitorEnabledFn: startupMonitorEnabledFn,\n\t}\n\treturn factory.New().WithSync(fd.sync).ResyncEvery(6*time.Minute).WithInformers(kubeInformersForNamespaces.InformersFor(targetNamespace).Core().V1().Pods().Informer()).ToController(\"StaticPodStateFallback\", eventRecorder), nil\n}", "func (f *Factory) New(providerConf digitalocean.Config, clusterState *cluster.State) (provider.Activity, error) {\n\tk8s := &K8s{}\n\tk8s.moduleDir = filepath.Join(config.Global.ProjectRoot, \"terraform/digitalocean/\"+myName)\n\tk8s.backendKey = \"states/terraform-\" + myName + \".state\"\n\tk8s.backendConf = digitalocean.BackendSpec{\n\t\tBucket: providerConf.ClusterName,\n\t\tKey: k8s.backendKey,\n\t\tEndpoint: providerConf.Region + \".digitaloceanspaces.com\",\n\t}\n\trawProvisionerData, err := yaml.Marshal(providerConf.Provisioner)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurret while marshal provisioner config: %s\", err.Error())\n\t}\n\tif err = yaml.Unmarshal(rawProvisionerData, &k8s.config); err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurret while parsing provisioner config: %s\", err.Error())\n\t}\n\n\tk8s.config.ClusterName = providerConf.ClusterName\n\tk8s.config.Region = providerConf.Region\n\n\tk8s.terraform, err = executor.NewTerraformRunner(k8s.moduleDir, provisioner.GetAwsAuthEnv()...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk8s.terraform.LogLabels = append(k8s.terraform.LogLabels, fmt.Sprintf(\"cluster='%s'\", providerConf.ClusterName))\n\treturn k8s, nil\n}", "func NewStaticConfigWatcher(cfg *Config) *StaticConfigWatcher {\n\tsc := &StaticConfigWatcher{\n\t\t// Buffer it so we can queue up the config for first delivery.\n\t\tch: make(chan *Config, 1),\n\t}\n\tsc.ch <- cfg\n\treturn sc\n}", "func NewStaticProvider(data interface{}) Provider {\n\tb, err := yaml.Marshal(data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn staticProvider{NewYAMLProviderFromBytes(b)}\n}", "func Init(repo *config.RepoConfig, opr *operator.Operator) *Watcher {\n\twatcher := &Watcher{\n\t\trepo: repo,\n\t\topr: opr,\n\t\tcheckPoints: make(map[string]map[string]checkPoint),\n\t}\n\tif repo.WatchFiles == nil {\n\t\treturn watcher\n\t}\n\n\tgo func() {\n\t\tutil.Error(watcher.composeJobs())\n\t\tutil.Error(watcher.initCheckPoints())\n\t\tutil.Println(\"init complete\", watcher.checkPoints)\n\t\tgo watcher.polling()\n\t}()\n\n\treturn watcher\n}", "func (cr *Crawler) InitReloadingFtps(sig os.Signal) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, sig)\n\n\tgo func(cr *Crawler) {\n\t\t<-c\n\n\t\terr := cr.LoadFtpsAndStartCrawling()\n\t\tif err != nil {\n\t\t\tcr.Log.Print(err)\n\t\t}\n\t}(cr)\n}", "func init() {\n\tif err := RegisterDriver(k8s.Name, NewK8S); err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func TestDynamicSource_CARotation(t *testing.T) {\n\tctx, cancel := context.WithTimeout(logr.NewContext(context.Background(), logtesting.NewTestLogger(t)), time.Second*40)\n\tdefer cancel()\n\n\tconfig, stop := framework.RunControlPlane(t, ctx)\n\tdefer stop()\n\n\tkubeClient, _, _, _ := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tsource := tls.DynamicSource{\n\t\tDNSNames: []string{\"example.com\"},\n\t\tAuthority: &authority.DynamicAuthority{\n\t\t\tSecretNamespace: namespace,\n\t\t\tSecretName: \"testsecret\",\n\t\t\tRESTConfig: config,\n\t\t},\n\t}\n\terrCh := make(chan error)\n\tdefer func() {\n\t\tcancel()\n\t\terr := <-errCh\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\t// run the dynamic authority controller in the background\n\tgo func() {\n\t\tdefer close(errCh)\n\t\tif err := source.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {\n\t\t\terrCh <- fmt.Errorf(\"Unexpected error running source: %v\", err)\n\t\t}\n\t}()\n\n\tvar serialNumber *big.Int\n\t// allow the controller 5s to provision the Secret - this is far longer\n\t// than it should ever take.\n\tif err := wait.PollUntilContextCancel(ctx, time.Millisecond*500, true, func(ctx context.Context) (done bool, err error) {\n\t\tcert, err := source.GetCertificate(nil)\n\t\tif err == tls.ErrNotAvailable {\n\t\t\tt.Logf(\"GetCertificate has no certificate available, waiting...\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif cert == nil {\n\t\t\tt.Fatalf(\"Returned certificate is nil\")\n\t\t}\n\t\tt.Logf(\"Got non-nil certificate from dynamic source\")\n\n\t\tx509cert, err := x509.ParseCertificate(cert.Certificate[0])\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode certificate: %v\", err)\n\t\t}\n\n\t\tserialNumber = x509cert.SerialNumber\n\t\treturn true, nil\n\t}); err != nil {\n\t\tt.Errorf(\"Failed waiting for source to return a certificate: %v\", err)\n\t\treturn\n\t}\n\n\tcl := kubernetes.NewForConfigOrDie(config)\n\tif err := cl.CoreV1().Secrets(source.Authority.SecretNamespace).Delete(ctx, source.Authority.SecretName, metav1.DeleteOptions{}); err != nil {\n\t\tt.Fatalf(\"Failed to delete CA secret: %v\", err)\n\t}\n\n\t// wait for the serving certificate to have a new serial number (which\n\t// indicates it has been regenerated)\n\tif err := wait.PollUntilContextCancel(ctx, time.Millisecond*500, true, func(ctx context.Context) (done bool, err error) {\n\t\tcert, err := source.GetCertificate(nil)\n\t\tif err == tls.ErrNotAvailable {\n\t\t\tt.Logf(\"GetCertificate has no certificate available, waiting...\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif cert == nil {\n\t\t\tt.Fatalf(\"Returned certificate is nil\")\n\t\t}\n\t\tt.Logf(\"Got non-nil certificate from dynamic source\")\n\n\t\tx509cert, err := x509.ParseCertificate(cert.Certificate[0])\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode certificate: %v\", err)\n\t\t}\n\n\t\tif serialNumber.Cmp(x509cert.SerialNumber) == 0 {\n\t\t\tt.Log(\"Certificate has not been regenerated, waiting...\")\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t}); err != nil {\n\t\tt.Errorf(\"Failed waiting for source to return a certificate: %v\", err)\n\t\treturn\n\t}\n}", "func initialize(config *config.Configuration) error {\n\tclientFactory := clientFactory{\n\t\troleSrv: config.LookupService(\"srv\", \"role\"),\n\t\tpermsSrv: config.LookupService(\"srv\", \"perms\"),\n\t\tclient: service.Client()}\n\n\tproto.RegisterCommandHandler(service.Server(),\n\t\tcommand.NewCommand(name,\n\t\t\t&clientFactory,\n\t\t),\n\t)\n\n\treturn nil\n}", "func (gr *Reconciler) Init() {\n\tkm := k8s.NewRsrcManager().WithName(\"basek8s\").WithClient(gr.Manager.GetClient()).WithScheme(gr.Manager.GetScheme())\n\tgr.RsrcMgr.Add(k8s.Type, km)\n\tapp.AddToScheme(&AddToSchemes)\n\tAddToSchemes.AddToScheme(gr.Manager.GetScheme())\n}", "func runPreInit(ctx context.Context, workingDir string, deps *clientset.Clientset, cmdline cmdline.Cmdline, msg string) error {\n\tisEmptyDir, err := location.DirIsEmpty(deps.FS, workingDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isEmptyDir {\n\t\treturn NewNoDevfileError(workingDir)\n\t}\n\n\tinitFlags := deps.InitClient.GetFlags(cmdline.GetFlags())\n\n\terr = deps.InitClient.InitDevfile(ctx, initFlags, workingDir,\n\t\tfunc(interactiveMode bool) {\n\t\t\tscontext.SetInteractive(cmdline.Context(), interactiveMode)\n\t\t\tif interactiveMode {\n\t\t\t\tlog.Title(msg, messages.SourceCodeDetected, \"odo version: \"+version.VERSION)\n\t\t\t\tlog.Info(\"\\n\" + messages.InteractiveModeEnabled)\n\t\t\t}\n\t\t},\n\t\tfunc(newDevfileObj parser.DevfileObj) error {\n\t\t\tdErr := newDevfileObj.WriteYamlDevfile()\n\t\t\tif dErr != nil {\n\t\t\t\treturn dErr\n\t\t\t}\n\t\t\tdErr = files.ReportLocalFileGeneratedByOdo(deps.FS, workingDir, filepath.Base(newDevfileObj.Ctx.GetAbsPath()))\n\t\t\tif dErr != nil {\n\t\t\t\tklog.V(4).Infof(\"error trying to report local file generated: %v\", dErr)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Initialize() {\n\tonce.Do(func(){\n\t\t// Ensure all dependencies are initialized\n\t\tconstructs.Initialize()\n\n\t\t// Load this library into the kernel\n\t\trt.Load(\"cdk8s\", \"1.0.0-beta.8\", tarball)\n\t})\n}", "func CreateFactory() ValidationFactory {\n\treturn &k8sFactory{}\n}", "func New(config Config) (*Service, error) {\n\t// Settings.\n\tif config.Flag == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Flag must not be empty\")\n\t}\n\tif config.Viper == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Viper must not be empty\")\n\t}\n\n\tvar err error\n\n\tvar k8sClient kubernetes.Interface\n\t{\n\t\tk8sConfig := k8sclient.DefaultConfig()\n\n\t\tk8sConfig.Logger = config.Logger\n\n\t\tk8sConfig.Address = config.Viper.GetString(config.Flag.Service.Kubernetes.Address)\n\t\tk8sConfig.InCluster = config.Viper.GetBool(config.Flag.Service.Kubernetes.InCluster)\n\t\tk8sConfig.TLS.CAFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CAFile)\n\t\tk8sConfig.TLS.CrtFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CrtFile)\n\t\tk8sConfig.TLS.KeyFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.KeyFile)\n\n\t\tk8sClient, err = k8sclient.New(k8sConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar vaultClient *vaultapi.Client\n\t{\n\t\tvaultConfig := vaultutil.Config{\n\t\t\tFlag: config.Flag,\n\t\t\tViper: config.Viper,\n\t\t}\n\n\t\tvaultClient, err = vaultutil.NewClient(vaultConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar crdFramework *framework.Framework\n\t{\n\t\tcrdFramework, err = newCRDFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar customObjectFramework *framework.Framework\n\t{\n\t\tcustomObjectFramework, err = newCustomObjectFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar healthzService *healthz.Service\n\t{\n\t\thealthzConfig := healthz.DefaultConfig()\n\n\t\thealthzConfig.K8sClient = k8sClient\n\t\thealthzConfig.Logger = config.Logger\n\t\thealthzConfig.VaultClient = vaultClient\n\n\t\thealthzService, err = healthz.New(healthzConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar versionService *version.Service\n\t{\n\t\tversionConfig := version.DefaultConfig()\n\n\t\tversionConfig.Description = config.Description\n\t\tversionConfig.GitCommit = config.GitCommit\n\t\tversionConfig.Name = config.Name\n\t\tversionConfig.Source = config.Source\n\t\tversionConfig.VersionBundles = NewVersionBundles()\n\n\t\tversionService, err = version.New(versionConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tnewService := &Service{\n\t\t// Dependencies.\n\t\tCRDFramework: crdFramework,\n\t\tCustomObjectFramework: customObjectFramework,\n\t\tHealthz: healthzService,\n\t\tVersion: versionService,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t}\n\n\treturn newService, nil\n}", "func (c *criService) initPlatform() error {\n\tpluginDirs := map[string]string{\n\t\tdefaultNetworkPlugin: c.config.NetworkPluginConfDir,\n\t}\n\tfor name, conf := range c.config.Runtimes {\n\t\tif conf.NetworkPluginConfDir != \"\" {\n\t\t\tpluginDirs[name] = conf.NetworkPluginConfDir\n\t\t}\n\t}\n\n\tc.netPlugin = make(map[string]cni.CNI)\n\tfor name, dir := range pluginDirs {\n\t\tmax := c.config.NetworkPluginMaxConfNum\n\t\tif name != defaultNetworkPlugin {\n\t\t\tif m := c.config.Runtimes[name].NetworkPluginMaxConfNum; m != 0 {\n\t\t\t\tmax = m\n\t\t\t}\n\t\t}\n\t\t// For windows, the loopback network is added as default.\n\t\t// There is no need to explicitly add one hence networkAttachCount is 1.\n\t\t// If there are more network configs the pod will be attached to all the\n\t\t// networks but we will only use the ip of the default network interface\n\t\t// as the pod IP.\n\t\ti, err := cni.New(cni.WithMinNetworkCount(windowsNetworkAttachCount),\n\t\t\tcni.WithPluginConfDir(dir),\n\t\t\tcni.WithPluginMaxConfNum(max),\n\t\t\tcni.WithPluginDir([]string{c.config.NetworkPluginBinDir}))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to initialize cni: %w\", err)\n\t\t}\n\t\tc.netPlugin[name] = i\n\t}\n\n\treturn nil\n}", "func (s *SimpleDriver) Initialize(lc logger.LoggingClient, asyncCh chan<- *dsModels.AsyncValues) error {\n\tcommand_list = make(map[string][2]string)\n\tcurrent_running_task = make(map[string][]string)\n\tvar opts Options\n\tflags.Parse(&opts)\n\tif opts.ConfProfile == \"docker\" {\n\t\tIPE_addr = \"dockerhost:8700\"\n\t}\n\tfmt.Println(IPE_addr)\n\tconn, _ = net.Dial(\"tcp\",IPE_addr)\n\n\tgo IPEMessageHandler()\n\n\ts.lc = lc\n\ts.asyncCh = asyncCh\n\treturn nil\n}", "func NewStaticService(configuration *config.Config,\n\tlogger *zap.Logger) (BadgeService, error) {\n\tif configuration == nil {\n\t\treturn nil, fmt.Errorf(\"missing config dependency\")\n\t}\n\tif logger == nil {\n\t\treturn nil, fmt.Errorf(\"missing logger dependency\")\n\t}\n\n\treturn &staticService{\n\t\tname: \"static\",\n\t\tconfig: configuration,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewStaticLoader() *StaticLoader {\n\treturn &StaticLoader{false}\n}", "func PrebuiltSharedLibraryFactory() android.Module {\n\tmodule, _ := NewPrebuiltSharedLibrary(android.HostAndDeviceSupported)\n\treturn module.Init()\n}", "func (m *Main) Init() error {\n\n\tlog.Printf(\"Loading GeoCode data ...\")\n\t//u.LoadGeoCodes()\n\n\tvar err error\n\tm.indexer, err = pdk.SetupPilosa(m.Hosts, m.IndexName, u.Frames, m.BufferSize)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting up Pilosa '%v'\", err)\n\t}\n\t//m.client = m.indexer.Client()\n\n\t// Initialize S3 client\n\tsess, err2 := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(m.AWSRegion)},\n\t)\n\n\tif err2 != nil {\n\t\treturn fmt.Errorf(\"Creating S3 session: %v\", err2)\n\t}\n\n\t// Create S3 service client\n\tm.S3svc = s3.New(sess)\n\n\treturn nil\n}", "func (p *PublisherMunger) Initialize(config *github.Config, features *features.Features) error {\n\tgopath := os.Getenv(\"GOPATH\")\n\tp.k8sIOPath = filepath.Join(gopath, \"src\", \"k8s.io\")\n\n\tclientGo := repoRules{\n\t\tdstRepo: \"client-go\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the client-go master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/client-go\"},\n\t\t\t\tdst: coordinate{repo: \"client-go\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{coordinate{repo: \"apimachinery\", branch: \"master\"}},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the client-go release-2.0 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.5\", dir: \"staging/src/k8s.io/client-go\"},\n\t\t\t\tdst: coordinate{repo: \"client-go\", branch: \"release-2.0\", dir: \"./\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the client-go release-3.0 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.6\", dir: \"staging/src/k8s.io/client-go\"},\n\t\t\t\tdst: coordinate{repo: \"client-go\", branch: \"release-3.0\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{coordinate{repo: \"apimachinery\", branch: \"release-1.6\"}},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_client_go.sh\",\n\t}\n\n\tapimachinery := repoRules{\n\t\tdstRepo: \"apimachinery\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the apimachinery master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/apimachinery\"},\n\t\t\t\tdst: coordinate{repo: \"apimachinery\", branch: \"master\", dir: \"./\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the apimachinery 1.6 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.6\", dir: \"staging/src/k8s.io/apimachinery\"},\n\t\t\t\tdst: coordinate{repo: \"apimachinery\", branch: \"release-1.6\", dir: \"./\"},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_apimachinery.sh\",\n\t}\n\n\tapiserver := repoRules{\n\t\tdstRepo: \"apiserver\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the apiserver master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/apiserver\"},\n\t\t\t\tdst: coordinate{repo: \"apiserver\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"master\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the apiserver 1.6 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.6\", dir: \"staging/src/k8s.io/apiserver\"},\n\t\t\t\tdst: coordinate{repo: \"apiserver\", branch: \"release-1.6\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"release-1.6\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"release-3.0\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_apiserver.sh\",\n\t}\n\n\tkubeAggregator := repoRules{\n\t\tdstRepo: \"kube-aggregator\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the kube-aggregator master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/kube-aggregator\"},\n\t\t\t\tdst: coordinate{repo: \"kube-aggregator\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"apiserver\", branch: \"master\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the kube-aggregator 1.6 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.6\", dir: \"staging/src/k8s.io/kube-aggregator\"},\n\t\t\t\tdst: coordinate{repo: \"kube-aggregator\", branch: \"release-1.6\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"release-1.6\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"release-3.0\"},\n\t\t\t\t\tcoordinate{repo: \"apiserver\", branch: \"release-1.6\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_kube_aggregator.sh\",\n\t}\n\n\tsampleAPIServer := repoRules{\n\t\tdstRepo: \"sample-apiserver\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the sample-apiserver master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/sample-apiserver\"},\n\t\t\t\tdst: coordinate{repo: \"sample-apiserver\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"apiserver\", branch: \"master\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// rule for the sample-apiserver 1.6 branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"release-1.6\", dir: \"staging/src/k8s.io/sample-apiserver\"},\n\t\t\t\tdst: coordinate{repo: \"sample-apiserver\", branch: \"release-1.6\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"release-1.6\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"release-3.0\"},\n\t\t\t\t\tcoordinate{repo: \"apiserver\", branch: \"release-1.6\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_sample_apiserver.sh\",\n\t}\n\n\tapiExtensionsAPIServer := repoRules{\n\t\tdstRepo: \"apiextensions-apiserver\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the sample-apiserver master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/apiextensions-apiserver\"},\n\t\t\t\tdst: coordinate{repo: \"apiextensions-apiserver\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"client-go\", branch: \"master\"},\n\t\t\t\t\tcoordinate{repo: \"apiserver\", branch: \"master\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_apiextensions_apiserver.sh\",\n\t}\n\n\tapi := repoRules{\n\t\tdstRepo: \"api\",\n\t\tsrcToDst: []branchRule{\n\t\t\t{\n\t\t\t\t// rule for the api master branch\n\t\t\t\tsrc: coordinate{repo: config.Project, branch: \"master\", dir: \"staging/src/k8s.io/api\"},\n\t\t\t\tdst: coordinate{repo: \"api\", branch: \"master\", dir: \"./\"},\n\t\t\t\tdeps: []coordinate{\n\t\t\t\t\tcoordinate{repo: \"apimachinery\", branch: \"master\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tpublishScript: \"/publish_scripts/publish_api.sh\",\n\t}\n\t// NOTE: Order of the repos is sensitive!!! A dependent repo needs to be published first, so that other repos can vendor its latest revision.\n\tp.reposRules = []repoRules{apimachinery, api, clientGo, apiserver, kubeAggregator, sampleAPIServer, apiExtensionsAPIServer}\n\tglog.Infof(\"publisher munger rules: %#v\\n\", p.reposRules)\n\tp.features = features\n\tp.githubConfig = config\n\treturn nil\n}", "func Init(ctx context.Context) (*Client, error) {\n\tclient, err := scheduler.NewCloudSchedulerClient(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{ctx, client}, nil\n}", "func NewFakeSource(svc *ExternalService, err error, rs ...*Repo) *FakeSource {\n\treturn &FakeSource{svc: svc, err: err, repos: rs}\n}", "func (o *Options) generateSources(log logr.Logger, fs vfs.FileSystem) ([]InternalSourceOptions, error) {\n\tif len(o.SourceObjectPaths) == 0 {\n\t\t// try to read from stdin if no resources are defined\n\t\tsourceOptions := make([]InternalSourceOptions, 0)\n\t\tstdinInfo, err := os.Stdin.Stat()\n\t\tif err != nil {\n\t\t\tlog.V(3).Info(\"unable to read from stdin\", \"error\", err.Error())\n\t\t\treturn nil, nil\n\t\t}\n\t\tif (stdinInfo.Mode()&os.ModeNamedPipe != 0) || stdinInfo.Size() != 0 {\n\t\t\tstdinResources, err := o.generateSourcesFromReader(os.Stdin)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read from stdin: %w\", err)\n\t\t\t}\n\t\t\tsourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, \"\")...)\n\t\t}\n\t\treturn sourceOptions, nil\n\t}\n\n\tsourceOptions := make([]InternalSourceOptions, 0)\n\tfor _, resourcePath := range o.SourceObjectPaths {\n\t\tif resourcePath == \"-\" {\n\t\t\tstdinInfo, err := os.Stdin.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read from stdin: %w\", err)\n\t\t\t}\n\t\t\tif (stdinInfo.Mode()&os.ModeNamedPipe != 0) || stdinInfo.Size() != 0 {\n\t\t\t\tstdinResources, err := o.generateSourcesFromReader(os.Stdin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to read from stdin: %w\", err)\n\t\t\t\t}\n\t\t\t\tsourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, \"\")...)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tresourceObjectReader, err := fs.Open(resourcePath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to read source object from %s: %w\", resourcePath, err)\n\t\t}\n\t\tnewResources, err := o.generateSourcesFromReader(resourceObjectReader)\n\t\tif err != nil {\n\t\t\tif err2 := resourceObjectReader.Close(); err2 != nil {\n\t\t\t\tlog.Error(err, \"unable to close file reader\", \"path\", resourcePath)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"unable to read sources from %s: %w\", resourcePath, err)\n\t\t}\n\t\tif err := resourceObjectReader.Close(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to read source from %q: %w\", resourcePath, err)\n\t\t}\n\t\tsourceOptions = append(sourceOptions, convertToInternalSourceOptions(newResources, resourcePath)...)\n\t}\n\treturn sourceOptions, nil\n}", "func New(cfg *config.Config) (sp *Service, err error) {\n\tvar s Service\n\ts.cfg = cfg\n\n\tif err = os.Chdir(s.cfg.Dir); err != nil {\n\t\terr = fmt.Errorf(\"error changing directory: %v\", err)\n\t\treturn\n\t}\n\n\tif s.plog, err = newPanicLog(); err != nil {\n\t\treturn\n\t}\n\n\tif err = initDir(s.cfg.Environment[\"dataDir\"]); err != nil {\n\t\terr = fmt.Errorf(\"error initializing data directory: %v\", err)\n\t\treturn\n\t}\n\n\tif err = initDir(\"build\"); err != nil {\n\t\terr = fmt.Errorf(\"error initializing plugin build directory: %v\", err)\n\t\treturn\n\t}\n\n\ts.srv = httpserve.New()\n\tif err = s.initPlugins(); err != nil {\n\t\terr = fmt.Errorf(\"error loading plugins: %v\", err)\n\t\treturn\n\t}\n\n\tif err = s.loadPlugins(); err != nil {\n\t\terr = fmt.Errorf(\"error initializing plugins: %v\", err)\n\t\treturn\n\t}\n\n\tif err = s.initGroups(); err != nil {\n\t\terr = fmt.Errorf(\"error initializing groups: %v\", err)\n\t\treturn\n\t}\n\n\tif err = s.initRoutes(); err != nil {\n\t\terr = fmt.Errorf(\"error initializing routes: %v\", err)\n\t\treturn\n\t}\n\n\t// TODO: Move this to docs/testing only?\n\tif err = s.initRouteExamples(); err != nil {\n\t\terr = fmt.Errorf(\"error initializing routes: %v\", err)\n\t\treturn\n\t}\n\n\tsp = &s\n\treturn\n}", "func Init(ctx context.Context, ds datastore.DataStore) {\n\tclusterUsecase := usecase.NewClusterUsecase(ds)\n\tapplicationUsecase := usecase.NewApplicationUsecase(ds)\n\tRegistWebService(NewClusterWebService(clusterUsecase))\n\tRegistWebService(NewApplicationWebService(applicationUsecase))\n\tRegistWebService(&namespaceWebService{})\n\tRegistWebService(&componentDefinitionWebservice{})\n\tRegistWebService(&addonWebService{})\n\tRegistWebService(&oamApplicationWebService{})\n\tRegistWebService(&policyDefinitionWebservice{})\n\tRegistWebService(&workflowWebService{})\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\treturn nil\n\n}", "func setupStatic(mux *goji.Mux) {\n\tif len(opts.DevServerUri) > 0 {\n\t\tlog.Printf(\"Proxying static files to development server %v.\",\n\t\t\topts.DevServerUri)\n\t\tdevServerProxyUrl, err := url.Parse(opts.DevServerUri)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdevServerProxy :=\n\t\t\thttputil.NewSingleHostReverseProxy(devServerProxyUrl)\n\t\tmux.Handle(pat.Get(\"/*\"), devServerProxy)\n\t} else {\n\t\tpublic := http.FileServer(\n\t\t\trice.MustFindBox(\"./public\").HTTPBox())\n\t\tmux.Handle(pat.Get(\"/*\"), public)\n\t}\n}", "func (e EmptyTargetsNotaryRepository) InitializeWithCertificate([]string, []data.PublicKey, ...data.RoleName) error {\n\treturn nil\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\n\treturn nil\n\n}", "func NewStatic(peers ...*memberlist.Node) Static {\n\treturn Static{\n\t\tpeers: peers,\n\t}\n}", "func createSourceRun(ctx context.Context) error {\n\tlog := logging.CreateStdLog(\"create\")\n\tsource, err := createSource(ctx, log, organizationID.Value(), displayName.Value(), description.Value(), googleServiceAccount.Value())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn print.AsJSON(source)\n}", "func (kr *KRun) InitK8SClient(ctx context.Context) error {\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\terr := kr.initUsingKubeConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = kr.initInCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif kr.VendorInit != nil {\n\t\terr = kr.VendorInit(ctx, kr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"not found\")\n}", "func init() {\n\tcore.RegisterConfigGroup(defaultConfigs)\n\tcore.RegisterServiceWithConfig(\"api\", &api.ApiServiceFactory{}, api.Configs)\n\tcore.RegisterServiceWithConfig(\"collector\", &collector.CollectorServiceFactory{}, collector.Configs)\n}", "func main() {\n\tflag.Parse()\n\tstop := make(chan struct{})\n\n\tclient, kcfg, err := k8s.CreateClientset(os.Getenv(\"KUBECONFIG\"), \"\")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to connect to k8s\", err)\n\t}\n\n\ts, err := istiod.InitConfig(\"/var/lib/istio/config\")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to start \", err)\n\t}\n\n\t// InitConfig certificates - first thing.\n\tinitCerts(s, client, kcfg)\n\n\tkc, err := k8s.InitK8S(s, client, kcfg, s.Args)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to start k8s\", err)\n\t}\n\n\t// Initialize Galley config source for K8S.\n\tgalleyK8S, err := kc.NewGalleyK8SSource(s.Galley.Resources)\n\ts.Galley.Sources = append(s.Galley.Sources, galleyK8S)\n\n\terr = s.InitDiscovery()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to start \", err)\n\t}\n\n\tkc.InitK8SDiscovery(s, client, kcfg, s.Args)\n\n\tif false {\n\t\tkc.WaitForCacheSync(stop)\n\t}\n\n\t// Off for now - working on replacement/simplified version\n\t// StartSDSK8S(baseDir, s.Mesh)\n\n\terr = s.Start(stop, kc.OnXDSStart)\n\tif err != nil {\n\t\tlog.Fatal(\"Failure on start\", err)\n\t}\n\n\t// Injector should run along, even if not used.\n\terr = k8s.StartInjector(stop)\n\tif err != nil {\n\t\t//log.Fatal(\"Failure on start injector\", err)\n\t\tlog.Println(\"Failure to start injector - ignore for now \", err)\n\t}\n\n\ts.WaitDrain(\".\")\n}", "func newGoFactory() *GOFactory {\n\tgologger.SLogger.Println(\"Init Game Object Factory Singleton\")\n\tfOnce.Do(func() {\n\t\tgofactory = &GOFactory{\n\t\t\tGoCreator: make(map[string]ICreator),\n\t\t}\n\t})\n\treturn gofactory\n}", "func (p *pgSerDe) FetchOrCreateDataSource(ident Ident, dsSpec *rrd.DSSpec) (rrd.DataSourcer, error) {\n\tvar (\n\t\terr error\n\t\trows *sql.Rows\n\t)\n\trows, err = p.sql4.Query(ident.String(), dsSpec.Step.Nanoseconds()/1000000, dsSpec.Heartbeat.Nanoseconds()/1000000)\n\tif err != nil {\n\t\tlog.Printf(\"FetchOrCreateDataSource(): error querying database: %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tif !rows.Next() {\n\t\tlog.Printf(\"FetchOrCreateDataSource(): unable to lookup/create\")\n\t\treturn nil, fmt.Errorf(\"unable to lookup/create\")\n\t}\n\tds, err := dataSourceFromRow(rows)\n\tif err != nil {\n\t\tlog.Printf(\"FetchOrCreateDataSource(): error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// RRAs\n\tvar rras []rrd.RoundRobinArchiver\n\tfor _, rraSpec := range dsSpec.RRAs {\n\t\tsteps := int64(rraSpec.Step / ds.Step())\n\t\tsize := rraSpec.Span.Nanoseconds() / rraSpec.Step.Nanoseconds()\n\t\tvar cf string\n\t\tswitch rraSpec.Function {\n\t\tcase rrd.WMEAN:\n\t\t\tcf = \"WMEAN\"\n\t\tcase rrd.MIN:\n\t\t\tcf = \"MIN\"\n\t\tcase rrd.MAX:\n\t\t\tcf = \"MAX\"\n\t\tcase rrd.LAST:\n\t\t\tcf = \"LAST\"\n\t\t}\n\t\trraRows, err := p.sql5.Query(ds.Id(), cf, steps, size, rraSpec.Xff)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"FetchOrCreateDataSource(): error creating RRAs: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\trraRows.Next()\n\t\trra, err := roundRobinArchiveFromRow(rraRows, ds.Step())\n\t\tif err != nil {\n\t\t\tlog.Printf(\"FetchOrCreateDataSource(): error2: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\trras = append(rras, rra)\n\n\t\t// sql1 UPSERT obsoletes the need for this\n\t\t// rraSize, rraWidth := rra.Size(), rra.Width()\n\t\t// for n := int64(0); n <= (rraSize/rraWidth + rraSize%rraWidth/rraWidth); n++ {\n\t\t// \tr, err := p.sql6.Query(rra.Id(), n)\n\t\t// \tif err != nil {\n\t\t// \t\tlog.Printf(\"FetchOrCreateDataSource(): error creating TSs: %v\", err)\n\t\t// \t\treturn nil, err\n\t\t// \t}\n\t\t// \tr.Close()\n\t\t// }\n\n\t\trraRows.Close()\n\t}\n\tds.SetRRAs(rras)\n\n\tif debug {\n\t\tlog.Printf(\"FetchOrCreateDataSource(): returning ds.id %d: LastUpdate: %v, %#v\", ds.Id(), ds.LastUpdate(), ds)\n\t}\n\treturn ds, nil\n}", "func New(root string, config *converter.Config) (runtime.Source, error) {\n\treturn newFsSource(root, config, kube_meta.Types.All())\n}", "func PrebuiltFactory() android.Module {\n\tmodule := &Prebuilt{}\n\tmodule.AddProperties(&module.properties)\n\tandroid.InitSingleSourcePrebuiltModule(module, &module.properties, \"Source\")\n\tandroid.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)\n\treturn module\n}", "func (p *StaticCapacityPlugin) Init(provider *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, scrapeSubcapacities map[string]map[string]bool) error {\n\treturn nil\n}", "func generatePod(c *client.Client, podName string, nsName string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tp := pod.Instance{\n\t\tName: podName,\n\t\tNamespace: nsName,\n\t\tImage: imageSource,\n\t\tLabelKey: \"app\",\n\t\tImagePullPolicy: \"ifnotpresent\",\n\t\tLabelValue: \"podTest\",\n\t}\n\n\ttimeNow := time.Now()\n\tfmt.Printf(\"creating pod %s in namespace %s\\n\", podName, nsName)\n\terr := pod.CreateWaitRunningState(c, &p)\n\t//if err != nil {\n\t//\tfmt.Printf(\"%s\\n\", err)\n\t//\tos.Exit(1)\n\t//}\n\n\tlastTime, err := pod.GetLastTimeConditionHappened(c,\n\t\t\"Ready\",\n\t\tpodName,\n\t\tnsName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\thour := lastTime.Sub(timeNow).Hours()\n\thour, mf := math.Modf(hour)\n\ttotalHour = totalHour + hour\n\n\tminutes := mf * 60\n\tminutes, sf := math.Modf(minutes)\n\ttotalMinutes = totalMinutes + minutes\n\n\tseconds := sf * 60\n\ttotalSec = totalSec + seconds\n\n\tfmt.Printf(\"\\n- %s is created and responsive in namespace %s ✅\\n\", p.Name, p.Namespace)\n\tfmt.Printf(\"- image used: %s\\n\", imageSource)\n\n\tfmt.Println(\" took:\", hour, \"hours\",\n\t\tminutes, \"minutes\",\n\t\tseconds, \"seconds\")\n\tsumSec = append(sumSec, totalSec)\n\tsumMin = append(sumMin, totalMinutes)\n\tsumHour = append(sumHour, totalHour)\n\ttotalPodsRunning = totalPodsRunning + 1\n\tfmt.Printf(\"TOTAL NUMBER OF PODS RUNNING: %v\\n\", totalPodsRunning)\n\tfmt.Printf(\"TIME NOW: %v\\n\", time.Now().Format(\"2006-01-02 3:4:5 PM\"))\n\n\ttotalHour = 0\n\ttotalMinutes = 0\n\ttotalSec = 0\n}", "func NewStaticLoaderFromWorkingDirectory() *StaticLoader {\n\treturn &StaticLoader{true}\n}", "func Init(\n\tctx context.Context,\n\tobservationCtx *observation.Context,\n\tdb database.DB,\n\t_ codeintel.Services,\n\t_ conftypes.UnifiedWatchable,\n\tenterpriseServices *enterprise.Services,\n) error {\n\tenterpriseServices.OwnResolver = resolvers.New()\n\n\treturn nil\n}", "func InitMetrics(\n\tclient *client.Client,\n\tscanner *scanner.Scanner,\n\tkube *kuber.Kube,\n\toptInAnalysisData bool,\n\targs map[string]interface{},\n) ([]MetricsSource, error) {\n\tvar (\n\t\tmetricsInterval = utils.MustParseDuration(args, \"--metrics-interval\")\n\t\tfailOnError = false // whether the agent will fail to start if an error happened during init metric source\n\n\t\tmetricsSources = make([]MetricsSource, 0)\n\t\tfoundErrors = make([]error, 0)\n\t)\n\n\tmetricsSourcesNames := []string{\"influx\", \"kubelet\"}\n\tif names, ok := args[\"--source\"].([]string); ok && len(names) > 0 {\n\t\tmetricsSourcesNames = names\n\t\tfailOnError = true\n\t}\n\n\tkubeletClient, err := NewKubeletClient(client.Logger, scanner, kube, args)\n\tif err != nil {\n\t\tfoundErrors = append(foundErrors, err)\n\t\tfailOnError = true\n\t}\n\n\tfor _, metricsSource := range metricsSourcesNames {\n\t\tswitch metricsSource {\n\t\tcase \"kubelet\":\n\t\t\tclient.Info(\"using kubelet as metrics source\")\n\n\t\t\tkubelet, err := NewKubelet(\n\t\t\t\tkubeletClient,\n\t\t\t\tclient.Logger,\n\t\t\t\tmetricsInterval,\n\t\t\t\tkubeletTimeouts{\n\t\t\t\t\tbackoff: backOff{\n\t\t\t\t\t\tsleep: utils.MustParseDuration(args, \"--kubelet-backoff-sleep\"),\n\t\t\t\t\t\tmaxRetries: utils.MustParseInt(args, \"--kubelet-backoff-max-retries\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\toptInAnalysisData,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tfoundErrors = append(foundErrors, karma.Format(\n\t\t\t\t\terr,\n\t\t\t\t\t\"unable to initialize kubelet source\",\n\t\t\t\t))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmetricsSources = append(metricsSources, kubelet)\n\t\t}\n\t}\n\tif len(foundErrors) > 0 && (failOnError || len(metricsSources) == 0) {\n\t\treturn nil, karma.Format(foundErrors, \"unable to init metric sources\")\n\t}\n\n\tfor _, source := range metricsSources {\n\t\tgo watchMetrics(\n\t\t\tclient,\n\t\t\tsource,\n\t\t\tscanner,\n\t\t\tmetricsInterval,\n\t\t)\n\t}\n\n\treturn metricsSources, nil\n}", "func (u *CidaasUtils) Init() error {\n\trefreshInterval := time.Hour\n\tif u.options.RefreshInterval != 0 {\n\t\trefreshInterval = u.options.RefreshInterval\n\t}\n\n\toptions := keyfunc.Options{\n\t\tRefreshInterval: &refreshInterval,\n\t\tRefreshErrorHandler: func(err error) {\n\t\t\tlog.Printf(\"There was an error with the jwt.KeyFunc\\nError: %s\", err.Error())\n\t\t},\n\t}\n\n\tjwks, err := keyfunc.Get(u.buildUrl(jwkEndpoint), options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.jwks = jwks\n\n\treturn nil\n}", "func (d *portworx) init(sched, nodeDriver, token, storageProvisioner, csiGenericDriverConfigMap, driverName string) error {\n\tlog.Infof(\"Using the Portworx volume driver with provisioner %s under scheduler: %v\", storageProvisioner, sched)\n\tvar err error\n\n\tif skipStr := os.Getenv(envSkipPXServiceEndpoint); skipStr != \"\" {\n\t\td.skipPXSvcEndpoint, _ = strconv.ParseBool(skipStr)\n\t}\n\n\td.token = token\n\n\tif d.nodeDriver, err = node.Get(nodeDriver); err != nil {\n\t\treturn err\n\t}\n\n\tif d.schedOps, err = schedops.Get(sched); err != nil {\n\t\treturn fmt.Errorf(\"failed to get scheduler operator for portworx. Err: %v\", err)\n\t}\n\td.schedOps.Init()\n\n\tnamespace, err := d.GetVolumeDriverNamespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\td.namespace = namespace\n\n\tif err = d.setDriver(); err != nil {\n\t\treturn err\n\t}\n\n\tstorageNodes, err := d.getStorageNodesOnStart()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(storageNodes) == 0 {\n\t\treturn fmt.Errorf(\"cluster inspect returned empty nodes\")\n\t}\n\n\tif err := d.updateNodes(storageNodes); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, n := range node.GetStorageDriverNodes() {\n\t\tif err := d.WaitDriverUpOnNode(n, validatePXStartTimeout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Infof(\"The following Portworx nodes are in the cluster:\")\n\tfor _, n := range storageNodes {\n\t\tlog.Infof(\n\t\t\t\"Node UID: %v Node IP: %v Node Status: %v\",\n\t\t\tn.Id,\n\t\t\tn.DataIp,\n\t\t\tn.Status,\n\t\t)\n\t}\n\ttorpedovolume.StorageDriver = driverName\n\t// Set provisioner for torpedo\n\tif storageProvisioner != \"\" {\n\t\tif p, ok := provisioners[torpedovolume.StorageProvisionerType(storageProvisioner)]; ok {\n\t\t\ttorpedovolume.StorageProvisioner = p\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"driver %s, does not support provisioner %s\", driverName, storageProvisioner)\n\t\t}\n\t} else {\n\t\ttorpedovolume.StorageProvisioner = provisioners[torpedovolume.DefaultStorageProvisioner]\n\t}\n\treturn nil\n}", "func (dh *darwinHarvester) populateStaticData(sample *types.ProcessSample, processSnapshot Snapshot) error {\n\tvar err error\n\n\tsample.CmdLine, err = processSnapshot.CmdLine(!dh.stripCommandLine)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"acquiring command line\")\n\t}\n\n\tsample.User, err = processSnapshot.Username()\n\tif err != nil {\n\t\tmplog.WithError(err).WithField(\"processID\", sample.ProcessID).Debug(\"Can't get Username for process.\")\n\t}\n\n\tsample.ProcessID = processSnapshot.Pid()\n\tsample.CommandName = processSnapshot.Command()\n\tsample.ParentProcessID = processSnapshot.Ppid()\n\n\treturn nil\n}", "func initTemplates(cfg *env.Config, staticAssets *static.Files) (*template.Template, error) {\n\n\tlog.Info(\"Initializing Templates\")\n\n\t// setup any template functions here\n\tglobalTemplateFunctions := template.FuncMap{\n\t\t\"jquery\": func() template.HTML {\n\t\t\tif cfg.IsProduction {\n\t\t\t\treturn template.HTML(productionJQuery)\n\t\t\t}\n\n\t\t\treturn template.HTML(developmentJQuery)\n\t\t},\n\t\t\"livereload\": func() template.HTML {\n\t\t\tif !cfg.IsProduction {\n\t\t\t\treturn template.HTML(livereloadScript)\n\t\t\t}\n\n\t\t\treturn template.HTML(\"\")\n\t\t},\n\t\t\"multi\": func(values ...interface{}) (map[string]interface{}, error) {\n\n\t\t\tif len(values)%2 != 0 {\n\t\t\t\treturn nil, errors.New(\"invalid multi call\")\n\t\t\t}\n\n\t\t\tparams := make(map[string]interface{}, len(values)/2)\n\n\t\t\tfor i := 0; i < len(values); i += 2 {\n\n\t\t\t\tkey, ok := values[i].(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"key must be a string\")\n\t\t\t\t}\n\n\t\t\t\tparams[key] = values[i+1]\n\t\t\t}\n\n\t\t\treturn params, nil\n\t\t},\n\t}\n\n\tvar err error\n\tvar funcs template.FuncMap\n\n\tif cfg.IsProduction {\n\n\t\tb, err := staticAssets.ReadFile(\"/assets/manifest.txt\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfuncs, err = assets.ProcessManifestFiles(bytes.NewBuffer(b), \"assets/\", assets.Production, true, leftDelim, rightDelim)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t} else {\n\t\tfuncs, err = assets.LoadManifestFiles(\"assets/\", assets.Development, true, leftDelim, rightDelim)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfor k, v := range funcs {\n\t\tglobalTemplateFunctions[k] = v\n\t}\n\n\ttpls, err := newStaticTemplates(&static.Config{\n\t\tUseStaticFiles: cfg.IsProduction,\n\t\tFallbackToDisk: true,\n\t\tAbsPkgPath: appPath,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Info(\"Reading Templates\")\n\n\tfiles, err := tpls.ReadFiles(\"/templates\", true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// glob load templates\n\tbuff := new(bytes.Buffer)\n\n\tfor _, file := range files {\n\t\t_, err = buff.Write(file)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.F(\"error\", err)).Warn(\"Issue writing template to buffer\")\n\t\t}\n\t}\n\n\ttpl, err := template.New(\"all\").Funcs(globalTemplateFunctions).Parse(buff.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tpl, nil\n}" ]
[ "0.53108597", "0.5267172", "0.51631904", "0.5085178", "0.5085178", "0.50606376", "0.50326127", "0.49595925", "0.49181592", "0.48047745", "0.4782862", "0.4779853", "0.4723916", "0.4684475", "0.46661323", "0.46650508", "0.4595088", "0.4586911", "0.45775932", "0.45775932", "0.4574467", "0.45481613", "0.45386854", "0.45365533", "0.45016062", "0.44985098", "0.44921127", "0.44896787", "0.44783062", "0.4476556", "0.4476556", "0.44459212", "0.44333875", "0.44331518", "0.44230705", "0.4411639", "0.4408541", "0.43889913", "0.43888178", "0.43840843", "0.43830335", "0.4361607", "0.43612927", "0.4357941", "0.43512177", "0.4345203", "0.43423855", "0.43255243", "0.4318384", "0.43036482", "0.43026242", "0.4296469", "0.428571", "0.42819786", "0.42787883", "0.42747468", "0.42734942", "0.4268384", "0.42604038", "0.4257087", "0.4250102", "0.4248927", "0.42347577", "0.42321378", "0.42300326", "0.42255276", "0.42250773", "0.4220891", "0.4219901", "0.4218493", "0.4213396", "0.42065108", "0.4201655", "0.42010084", "0.41974303", "0.4192676", "0.4182127", "0.4181824", "0.41810498", "0.4179479", "0.41779184", "0.4175519", "0.4161721", "0.41599664", "0.41575736", "0.4155472", "0.41508543", "0.41490275", "0.41457897", "0.41440278", "0.4143951", "0.41421637", "0.41412717", "0.41392434", "0.41328868", "0.41294003", "0.412552", "0.41247007", "0.41246757", "0.41134778" ]
0.85254854
0
Disconnected is called when the executor is disconnected from the slave.
func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) { if k.isDone() { return } log.Infof("Slave is disconnected\n") if !(&k.state).transition(connectedState, disconnectedState) { log.Errorf("failed to disconnect/transition to a disconnected state") } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !k.swapState(connectedState, disconnectedState) {\n\t\t//programming error?\n\t\tpanic(\"already disconnected?!\")\n\t}\n}", "func (c *Client) OnDisconnected(_ context.Context, status rpc.DisconnectStatus) {\n}", "func (s *eremeticScheduler) Disconnected(sched.SchedulerDriver) {\n\tlog.Debugf(\"Framework disconnected with master\")\n}", "func (er *EventRelay) Disconnected(err error) {\n\tlogger.Warnf(\"Disconnected: %s. Attempting to reconnect...\\n\", err)\n\n\ter.ehmutex.Lock()\n\tdefer er.ehmutex.Unlock()\n\n\ter.eventHub = nil\n\n\tgo er.connectEventHub()\n}", "func (s *Slave) disconnect() (err error) {\n\ts.c.stop()\n\n\treturn\n}", "func printDisconnected() {\n\tfmt.Println(\"Disconnected\")\n}", "func (k *KubernetesScheduler) Disconnected(driver mesos.SchedulerDriver) {\n\tlog.Infof(\"Master disconnected!\\n\")\n\tk.registered = false\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// discard all cached offers to avoid unnecessary TASK_LOST updates\n\tfor offerId := range k.offers {\n\t\tk.deleteOffer(offerId)\n\t}\n\n\t// TODO(jdef): it's possible that a task is pending, in between Schedule() and\n\t// Bind(), such that it's offer is now invalid. We should check for that and\n\t// clearing the offer from the task (along with a related check in Bind())\n}", "func (bn *BasicNotifiee) Disconnected(n net.Network, conn net.Conn) {\n\tglog.V(4).Infof(\"Notifiee - Disconnected. Local: %v - Remote: %v\", peer.IDHexEncode(conn.LocalPeer()), peer.IDHexEncode(conn.RemotePeer()))\n\tif bn.monitor != nil {\n\t\tbn.monitor.RemoveConn(peer.IDHexEncode(conn.LocalPeer()), peer.IDHexEncode(conn.RemotePeer()))\n\t}\n\tif bn.disconnectHandler != nil {\n\t\tbn.disconnectHandler(conn.RemotePeer())\n\t}\n}", "func (a *adapter) Disconnected(err error) {\n\tfmt.Printf(\"Disconnected...exiting\\n\")\n\tos.Exit(1)\n}", "func (a *adapter) Disconnected(err error) {\n\tfmt.Print(\"Disconnected...exiting\\n\")\n\tos.Exit(1)\n}", "func (a *AbstractNetworkConnectionHandler) OnDisconnect() {\n}", "func printDisconnected() {\n\tfmt.Println(\"Disconnected from the server.\")\n return\n}", "func (vm *VM) Disconnected(id ids.ShortID) error {\n\treturn nil\n}", "func (notifee *Notifee) Disconnected(net network.Network, conn network.Conn) {\n\n\tnotifee.logger.Info().Msgf(\n\t\t\"Disconnected from peer %s\",\n\t\tconn.RemotePeer().Pretty(),\n\t)\n\tpinfo := notifee.myRelayPeer\n\tif conn.RemotePeer().Pretty() != pinfo.ID.Pretty() {\n\t\treturn\n\t}\n\n\tnotifee.myHost.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)\n\tfor {\n\t\tvar err error\n\t\tselect {\n\t\tcase _, open := <-notifee.closing:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tnotifee.logger.Warn().Msgf(\n\t\t\t\t\"Lost connection to relay peer %s, reconnecting...\",\n\t\t\t\tpinfo.ID.Pretty(),\n\t\t\t)\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout)\n\t\t\tdefer cancel()\n\t\t\tif err = notifee.myHost.Connect(ctx, pinfo); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\n\t\t}\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tnotifee.logger.Info().Msgf(\"Connection to relay peer %s reestablished\", pinfo.ID.Pretty())\n}", "func (this *Monitor) Disconnect() error {\n\t// Advance to disconnecting state only if connected\n\tok, state := this.stateTransition(StateConnected, StateDisconnecting)\n\tif !ok {\n\t\tthis.Logf(LogLevelDebug, \"Cannot disconnect because monitor is %s\", state.String())\n\t\treturn errors.New(\"Cannot disconnect because monitor is \" + state.String())\n\t}\n\n\t// TODO: Implmement a graceful disconnect from the server\n\t// TODO: send termination package, requires an ACK to work properly\n\t// TODO: but only with max retries just like for connect\n\n\t// Interupt loops\n\tthis.disconnectWaitGroup.Add(3) // TODO: how many routines do we actually have?\n\tthis.connected = false // this prevents any more messages to be sent\n\tclose(this.disconnect)\n\tthis.disconnectWaitGroup.Wait()\n\tclose(this.statusMessageChannel)\n\tclose(this.controlMessageChannel)\n\n\t// Close the connection and signal connection state\n\tthis.connection.Close()\n\tthis.stateTransition(StateDisconnecting, StateDisconnected)\n\tthis.Log(LogLevelDebug, \"Disconnected\")\n\treturn nil\n}", "func (hs *Handshake) Disconnected(c p2p.Conn) {\n\tfmt.Println(\"disconnect\")\n}", "func (m *ConnManager) DisConnected(k interface{}) {\n\tm.connections.Delete(k)\n\n\tatomic.AddInt32(m.Online, -1)\n}", "func (driver *MesosExecutorDriver) slaveExited() {\n\tif driver.status == mesosproto.Status_DRIVER_ABORTED {\n\t\tlog.Infof(\"Ignoring slave exited event because the driver is aborted!\\n\")\n\t\treturn\n\t}\n\n\tif driver.checkpoint && driver.connected {\n\t\tdriver.connected = false\n\n\t\tlog.Infof(\"Slave exited, but framework has checkpointing enabled. Waiting %v to reconnect with slave %v\",\n\t\t\tdriver.recoveryTimeout, driver.slaveID)\n\t\ttime.AfterFunc(driver.recoveryTimeout, func() { driver.recoveryTimeouts(driver.connection) })\n\t\treturn\n\t}\n\n\tlog.Infof(\"Slave exited ... shutting down\\n\")\n\tdriver.connected = false\n\t// Clean up\n\tdriver.Executor.Shutdown(driver)\n\tdriver.status = mesosproto.Status_DRIVER_ABORTED\n\tdriver.Stop()\n}", "func (*listener) OnDisconnect() {}", "func (h *Hub) RemoteDisconnect(msg *common.RemoteDisconnectMessage) {\n\th.disconnect <- msg\n}", "func (m *Mock) Disconnected(peer p2p.Peer) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tm.peers = swarm.RemoveAddress(m.peers, peer.Address)\n\n\tm.Trigger()\n}", "func onDisconnect(c *gnet.Connection,\n\treason gnet.DisconnectReason) {\n\tfmt.Printf(\"Event Callback: disconnect event \\n\")\n}", "func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}", "func (k *KubernetesScheduler) ExecutorLost(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, status int) {\n\tlog.Infof(\"Executor %v of slave %v is lost, status: %v\\n\", executorId, slaveId, status)\n\t// TODO(yifan): Restart any unfinished tasks of the executor.\n}", "func (s *SocketModeAdapter) onDisconnected(info *adapter.Info) *adapter.ProviderEvent {\n\treturn s.wrapEvent(\n\t\tadapter.EventDisconnected,\n\t\tinfo,\n\t\t&adapter.DisconnectedEvent{},\n\t)\n}", "func (b *BTCC) OnDisconnect(output chan socketio.Message) {\n\tlog.Printf(\"%s Disconnected from websocket server.. Reconnecting.\\n\", b.GetName())\n\tb.WebsocketClient()\n}", "func (i *IRC) Disconnect(msg string) {\n\tif msg != \"\" {\n\t\t_, _ = i.writeLine(\"QUIT\", msg)\n\t} else {\n\t\t_, _ = i.writeLine(\"QUIT\", \"Disconnecting\")\n\t}\n\n\ti.StopRequested.Set(true)\n\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond * 500)\n\n\t\tif i.Connected.Get() {\n\t\t\ti.log.Warn(\"disconnect did not happen as expected. forcing a socket close\")\n\t\t\ti.socket.Close()\n\t\t}\n\t}()\n}", "func (self *OFSwitch) switchDisconnected() {\n\tself.changeStatus(false)\n\tself.cancel()\n\tself.heartbeatCh <- struct{}{}\n\tswitchDb.Remove(self.DPID().String())\n\tself.app.SwitchDisconnected(self)\n\tif self.connCh != nil {\n\t\tself.connCh <- ReConnection\n\t}\n}", "func (this User) disconnect() {\n disconnected := Message {this.Name, this.Id, \"disconnected\"}\n this.broadcast(disconnected)\n mu.Lock()\n delete(clients, this.Id)\n mu.Unlock()\n}", "func (self *discovery) disconnect() error {\n\tself.Lock()\n\tdefer self.Unlock()\n\n\tif self.connected {\n\t\treturn self.callDiscoveryService(\"unregister\", false)\n\t}\n\n\treturn nil\n}", "func (vl *VlanBridge) SwitchDisconnected(sw *ofctrl.OFSwitch) {\n\t// FIXME: ??\n}", "func (bb *BasicBot) Disconnect() {\n\tbb.conn.Close()\n\tupTime := time.Now().Sub(bb.startTime).Seconds()\n\trgb.YPrintf(\"[%s] Closed connection from %s! | Live for: %fs\\n\", timeStamp(), bb.Server, upTime)\n}", "func (ch *InternalChannel) Disconnect(c *Client) {}", "func (n *natsBroker) Disconnect() error {\n\n\tif n.connection == nil {\n\t\treturn errors.New(\"[NATS]: Cannot Disconnect. Not connected to broker\")\n\t}\n\n\tn.connection.Close()\n\tlog.Printf(\"[NATS]: Disconnected from %s\", n.Address())\n\treturn nil\n}", "func (ch *ServerChannel) Disconnect(c *Client) {}", "func (t *TableCache) Disconnected() {\n}", "func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to reregister/transition to a connected state\")\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes))\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tk.initialRegistration.Do(k.onInitialRegistration)\n}", "func (p *Peer) connectionClosed() {\n\tif !atomic.CompareAndSwapInt32(&p.connected, 1, 2) {\n\t\treturn\n\t}\n\tp.connclosed <- struct{}{}\n\n\terr := p.config.Listeners.OnDisconnect()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (c *client) Disconnect() error {\n\tc.mutex.Lock()\n\tif c.grpc != nil {\n\t\tif err := c.grpc.Close(); err != nil {\n\t\t\tklog.V(2).ErrorS(err, \"Failed to close grcp connection\", \"resource\", c.Resource())\n\t\t}\n\t\tc.grpc = nil\n\t}\n\tc.mutex.Unlock()\n\tc.handler.PluginDisconnected(c.resource)\n\treturn nil\n}", "func (self *PolicyAgent) SwitchDisconnected(sw *ofctrl.OFSwitch) {\n\t// FIXME: ??\n}", "func (c *gRPCConnection) Disconnect() {\n\tif !c.IsConnected() {\n\t\treturn\n\t}\n\tatomic.StoreUint32(&c.isConnected, 0)\n\n\tclose(c.stopChan)\n\n\tif c.IsOutbound() {\n\t\tc.closeSend()\n\t\tlog.Debugf(\"Disconnected from %s\", c)\n\t}\n\n\tlog.Debugf(\"Disconnecting from %s\", c)\n\tif c.onDisconnectedHandler != nil {\n\t\tc.onDisconnectedHandler()\n\t}\n}", "func (c Connection) Disconnect() error {\n\n\tif c.IsConnected {\n\t\tfmt.Println(\"Disconnected.\")\n\t} else {\n\t\tfmt.Println(\"Already disconnected.\")\n\t}\n\n\treturn nil\n}", "func (peer *Peer) Disconnect() {\n\tif peer.ServerNetworkNode != nil && peer.State != PeerStateDisconnected {\n\t\tpeer.State = PeerStateDisconnected\n\t\tif peer.HeartbeatTicker != nil {\n\t\t\tpeer.HeartbeatTicker.Stop()\n\t\t}\n\t\tif peer.ServerNetworkNode != nil {\n\t\t\tpeer.Server.ServerNode.DeregisterNode(peer.ServerNetworkNode)\n\t\t\tpeer.Server.ConnectionClear(peer.ServerNetworkNode.ID)\n\t\t\tpeer.Logger.Info(\"Peer\", \"%02X: Disconnected\", peer.ServerNetworkNode.ID)\n\t\t} else {\n\t\t\tpeer.Logger.Info(\"Peer\", \"Unregistered Peer Disconnected (%s)\", peer.Address)\n\t\t}\n\t\tif peer.Connection != nil {\n\t\t\tpeer.Connection.Close()\n\t\t}\n\t}\n}", "func (v vehicleList) Disconnected(vehicleID string) {\n\tlog.Printf(\"Vehicle '%v' disconnected\\n\", vehicleID)\n\tdb.Delete(v.connectionKey(vehicleID))\n\t//v.vehicles.Delete(key(vehicle.ID))\n\tv.Publish(nil)\n}", "func (n *DcrdNotifier) onBlockDisconnected(blockHeader []byte) {\n\tvar header wire.BlockHeader\n\tif err := header.FromBytes(blockHeader); err != nil {\n\t\tchainntnfs.Log.Warnf(\"Received block disconnected with malformed \"+\n\t\t\t\"header: %v\", err)\n\t\treturn\n\t}\n\n\t// Append this new chain update to the end of the queue of new chain\n\t// updates.\n\tselect {\n\tcase n.chainUpdates.ChanIn() <- &filteredBlock{\n\t\theader: &header,\n\t\tconnect: false,\n\t}:\n\tcase <-n.quit:\n\t\treturn\n\t}\n}", "func (engine *TcpEngin) HandleDisconnected(onDisconnected func(client *TcpClient)) {\r\n\tpre := engine.onDisconnectedHandler\r\n\tengine.onDisconnectedHandler = func(c *TcpClient) {\r\n\t\tdefer handlePanic()\r\n\t\tif pre != nil {\r\n\t\t\tpre(c)\r\n\t\t}\r\n\t\tonDisconnected(c)\r\n\t}\r\n}", "func (rpc *LibvirtRPCMonitor) Disconnect() error {\n\treturn rpc.l.Disconnect()\n}", "func (c *UDPChannel) OnDisconnect(callback func(c IChannel)) {\n\tc.onDisconnect = callback\n}", "func Disconnect(err error) error {\n\treturn &DisconnectError{\n\t\terr: err,\n\t}\n}", "func (c *Client) OnDisconnect(fn ConnCallback) {\n\tc.disconnectcb = fn\n}", "func (hs *HealthStatusInfo) DisconnectedFromBroker() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.DisconnectedFromMQTTBroker = true\n\tMQTTHealth.disconnectFromBrokerStartTime = time.Now()\n\tMQTTHealth.LastDisconnectFromBrokerDuration = 0\n}", "func (h *handler) Disconnect(c *session.Client) {\n\tif c == nil {\n\t\th.logger.Error(LogErrFailedDisconnect + (ErrClientNotInitialized).Error())\n\t\treturn\n\t}\n\th.logger.Error(fmt.Sprintf(LogInfoDisconnected, c.ID, c.Username))\n\tif err := h.es.Disconnect(c.Username); err != nil {\n\t\th.logger.Error(LogErrFailedPublishDisconnectEvent + err.Error())\n\t}\n}", "func (driver *TestServerDriver) ClientDisconnected(cc ClientContext) {\n\tdriver.clientMU.Lock()\n\tdefer driver.clientMU.Unlock()\n\n\tfor idx, client := range driver.Clients {\n\t\tif client.ID() == cc.ID() {\n\t\t\tlastIdx := len(driver.Clients) - 1\n\t\t\tdriver.Clients[idx] = driver.Clients[lastIdx]\n\t\t\tdriver.Clients[lastIdx] = nil\n\t\t\tdriver.Clients = driver.Clients[:lastIdx]\n\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Config) disconnect() {\n\tc.emitEvent(Event{Type: EventDisconnected})\n\n\t// TODO: remove when closed channel is removed.\n\tselect {\n\tcase c.closed <- true:\n\tdefault:\n\t}\n}", "func (b *Bot) Disconnect() {\n\tb.serversProtect.RLock()\n\tfor _, srv := range b.servers {\n\t\tb.disconnectServer(srv)\n\t}\n\tb.serversProtect.RUnlock()\n}", "func (i *IrcClient) Disconnect() {\n\ti.Connected = false\n\tif(i.Conn != nil) {\n\t\ti.Conn.Close()\n\t}\n\tlog(\"IRC disconnect - connection closed\")\n}", "func (*ClientDisconnectEvent) Op() ws.OpCode { return 13 }", "func (t *clients) Disconnected(id string, reason mqttp.ReasonCode) {\n\tatomic.AddUint64(&t.curr.val, ^uint64(0))\n\n\tnm, _ := mqttp.New(mqttp.ProtocolV311, mqttp.PUBLISH)\n\tnotifyMsg, _ := nm.(*mqttp.Publish)\n\tnotifyMsg.SetRetain(false)\n\t_ = notifyMsg.SetQoS(mqttp.QoS0)\n\t_ = notifyMsg.SetTopic(t.topic + id + \"/disconnected\")\n\tnotifyPayload := clientDisconnectStatus{\n\t\tReason: \"normal\",\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t}\n\n\tif out, err := json.Marshal(&notifyPayload); err != nil {\n\t\tnotifyMsg.SetPayload([]byte(\"data error\"))\n\t} else {\n\t\tnotifyMsg.SetPayload(out)\n\t}\n\n\t_ = t.topicsManager.Publish(notifyMsg)\n\n\t// remove connected retained message\n\tnm, _ = mqttp.New(mqttp.ProtocolV311, mqttp.PUBLISH)\n\tnotifyMsg, _ = nm.(*mqttp.Publish)\n\tnotifyMsg.SetRetain(false)\n\t_ = notifyMsg.SetQoS(mqttp.QoS0)\n\t_ = notifyMsg.SetTopic(t.topic + id + \"/connected\")\n\t_ = t.topicsManager.Retain(notifyMsg)\n}", "func (b *Bootstrapper) Disconnected(nodeID ids.ShortID) error {\n\tif weight, ok := b.Beacons.GetWeight(nodeID); ok {\n\t\t// TODO: Account for weight changes in a more robust manner.\n\n\t\t// Sub64 should rarely error since only validators that have added their\n\t\t// weight can become disconnected. Because it is possible that there are\n\t\t// changes to the validators set, we utilize that Sub64 returns 0 on\n\t\t// error.\n\t\tb.weight, _ = math.Sub64(b.weight, weight)\n\t}\n\treturn nil\n}", "func (p *Pod) Disconnect() {\n\t// stop future messages from being sent and then indicate to the bus that disconnection is desired\n\t// The bus will close the busChan, which will cause the onFunc listener to quit.\n\tp.dead.Store(true)\n\tp.feedbackChan <- podFeedbackMsgDisconnect\n}", "func (k *KubernetesScheduler) SlaveLost(driver mesos.SchedulerDriver, slaveId *mesos.SlaveID) {\n\tlog.Infof(\"Slave %v is lost\\n\", slaveId)\n\t// TODO(yifan): Restart any unfinished tasks on that slave.\n}", "func (s *Slave) Close() error {\n\treturn s.disconnect()\n}", "func (h *EmptyNSMMonitorHandler) Closed(conn *connection.Connection) {}", "func (n *Node) disconnect() *NodeErr {\n\t// Send an error to Node.Error channel if the node is not connected\n\tif !n.IsConnected() {\n\t\treturn ConnErr(\"node not connected\", nil)\n\t}\n\n\t// Warn to other network peers about the disconnection\n\tmsg := new(message.Message).SetType(message.DisconnectType).SetFrom(n.Self)\n\tif err := n.broadcast(msg); err != nil {\n\t\treturn err\n\t}\n\n\t// Clean current member list\n\tn.Members = peer.NewMembers()\n\tn.setConnected(false)\n\treturn nil\n}", "func (c *Client) OnDisconnect(reason error, param client.Param) {\n\tc.mu.Lock()\n\tc.disconnectReason = reason\n\tc.mu.Unlock()\n}", "func (u *UnityServer) disconnect() {\n\tu.Logger.Info(\"Disconnecting unity\")\n\tu.conn.Close()\n\tu.connected = false\n}", "func (r *ProtocolIncus) Disconnect() {\n\tif r.ctxConnected.Err() != nil {\n\t\tr.ctxConnectedCancel()\n\t}\n}", "func (irc *Client) Disconnect() {\n\ttime.Sleep(time.Millisecond * 200)\n\tif irc.Conn != nil {\n\t\tlog.Println(\"Disconnecting...\")\n\t\t(*irc.Conn).Close()\n\t}\n}", "func (p *Plugin) Disconnect() error {\n\treturn nil\n}", "func (c *TestCluster) Disconnect(from, to string, err error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.errors[c.peerKey(from, to)] = err\n}", "func (mon *SocketMonitor) Disconnect() error {\n\tatomic.StoreInt32(mon.listeners, 0)\n\terr := mon.c.Close()\n\n\tif mon.stream != nil {\n\t\tfor range mon.stream {\n\t\t}\n\t}\n\n\treturn err\n}", "func (d *Device) Disconnect(result chan<- error) {\n\t// Wait 2 seconds and die\n\td.m.Disconnect(2000)\n}", "func (nc *NetClient) OnDisconnect(handler func(types.Connection)) {\n\tnc.disconnectHandler = handler\n}", "func (d *DirectMemifConnector) Disconnect(crossConnect *crossconnect.CrossConnect) {\n\tvalue, exist := d.proxyMap.Load(crossConnect.GetId())\n\tif !exist {\n\t\tlogrus.Warnf(\"Proxy for cross connect with id=%s doesn't exist. Nothing to stop\", crossConnect.GetId())\n\t\treturn\n\t}\n\n\tproxy := value.(memifproxy.Proxy)\n\tproxy.Stop()\n\n\td.proxyMap.Delete(crossConnect.Id)\n}", "func (cmd *commandDisconn) run() error {\n\treturn cmd.cli.Disconnect()\n}", "func (c *Communicator) Disconnect() error {\n\tc.client = nil\n\treturn nil\n}", "func WorkerShutDown(workerID int){\n\tworkerMsg := WorkerMessage{}\n\tworkerMsg.ID = workerID\n\n\tcall(\"Master.WorkerShutDown\", &workerMsg, &workerMsg)\n}", "func (d StaticAgentDiscovery) Unsubscribe(chan<- []string) { return }", "func (p *Peer) Disconnect() {\n\tif atomic.AddInt32(&p.disconnect, 1) != 1 {\n\t\treturn\n\t}\n\n\tlog.Tracef(\"Disconnecting %s\", p)\n\tif atomic.LoadInt32(&p.connected) != 0 {\n\t\tp.conn.Close()\n\t}\n\tclose(p.quit)\n}", "func (a *AbstractNetworkConnectionHandler) OnShutdown(_ context.Context) {}", "func (hs *HealthStatusInfo) DisconnectedFromDatabase() {\n\ths.lock()\n\tdefer hs.unLock()\n\tDBHealth.DisconnectedFromDB = true\n\tDBHealth.disconnectFromDBStartTime = time.Now()\n\tDBHealth.LastDisconnectFromDBDuration = 0\n}", "func (queueWriter *QueueWriter) Disconnect() {\n\tqueueWriter.isConnected = false\n\tqueueWriter.connection.Disconnect()\n\n\tlog.Printf(\"Disconnected\")\n}", "func (i *ServerInfo) OnDisconnect(client *Client) {\n\ti.mutex.Lock()\n\tdefer i.mutex.Unlock()\n\tdelete(i.clients, client.ID)\n}", "func (MGO) Disconnect() error {\n\treturn client.Disconnect(context.TODO())\n}", "func (node *Node) Disconnect() error {\n\tnode.Lock()\n\tdefer node.Unlock()\n\tnode.allowNetwork = false\n\treturn nil\n}", "func (ms *MqttSocket) Disconnect() {\n\tms.client.Disconnect(0)\n}", "func (k *KubernetesExecutor) Shutdown(driver bindings.ExecutorDriver) {\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.doShutdown(driver)\n}", "func (nc *NetClient) Disconnect() error {\n\terr := nc.ReadWriteCloser.Close()\n\tif nc.disconnectHandler != nil {\n\t\tgo nc.disconnectHandler(nc)\n\t}\n\tgo func() {\n\t\tnc.stopSending <- struct{}{}\n\t\tnc.stopReceiving <- struct{}{}\n\t}()\n\n\treturn err\n}", "func (g *Gateway) Disconnect(addr modules.NetAddress) error {\n\tid := g.mu.RLock()\n\tp, exists := g.peers[addr]\n\tg.mu.RUnlock(id)\n\tif !exists {\n\t\treturn errors.New(\"not connected to that node\")\n\t}\n\tp.sess.Close()\n\tid = g.mu.Lock()\n\tdelete(g.peers, addr)\n\tg.mu.Unlock(id)\n\n\tg.log.Println(\"INFO: disconnected from peer\", addr)\n\treturn nil\n}", "func NewDisconnectedEvent(cause error) *DisconnectedEvent {\n\treturn &DisconnectedEvent{Err: &disconnectedError{cause: cause}}\n}", "func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) {\n\tif l.Disconnect != nil {\n\t\tl.Disconnect(e)\n\t}\n}", "func (c *DefaultClient) Disconnect() {\n\tif !c.mqtt.IsConnected() {\n\t\treturn\n\t}\n\tc.ctx.Debug(\"Disconnecting from MQTT\")\n\tc.mqtt.Disconnect(25)\n}", "func (c *MQTTClient) Disconnect(pending uint) {\n\tc.client.Disconnect(pending)\n}", "func (sio *SocketIO) OnDisconnect(f func(*Conn)) os.Error {\n\tif sio.muxed {\n\t\treturn os.NewError(\"OnDisconnect: already muxed\")\n\t}\n\tsio.callbacks.onDisconnect = f\n\treturn nil\n}", "func (ch *Channel) Disconnect(c *Client) {\n ch.Clients.Delete(c.Id)\n}", "func (c *ConnectionManager) Disconnect(ctx context.Context) error {\n\tc.cancelCtx()\n\tselect {\n\tcase <-c.done: // wait for goroutine to exit\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (d *MongoConnector) Disconnect() error {\n\terr := d.mongoClient.Disconnect(context.TODO())\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (n *mockAgent) disconnect() error {\n\treturn nil\n}", "func (c *Client) HandleDisconnect(cb func()) {\n\tc.discCb = &cb\n}", "func (mn *MockNetwork) Disconnect(string) error {\n\treturn nil\n}" ]
[ "0.7777259", "0.6798982", "0.66713166", "0.65439236", "0.64857304", "0.63112164", "0.6266085", "0.62428963", "0.6222822", "0.62183905", "0.6036305", "0.60191613", "0.5995147", "0.5954083", "0.594486", "0.5891317", "0.58731556", "0.5858181", "0.58066237", "0.5801534", "0.57850355", "0.57843256", "0.57375675", "0.5675374", "0.56520575", "0.56477875", "0.5642232", "0.5636332", "0.5634012", "0.5626923", "0.5608238", "0.56033534", "0.5587798", "0.55726695", "0.5554631", "0.5498912", "0.545514", "0.5454548", "0.54482424", "0.54196036", "0.5397333", "0.53497756", "0.5345291", "0.53401995", "0.53377163", "0.53321254", "0.531023", "0.5308584", "0.52854514", "0.52801704", "0.5272576", "0.52681", "0.52680326", "0.52672565", "0.5261125", "0.5258847", "0.5245295", "0.5244357", "0.52434283", "0.51980877", "0.5195286", "0.51704293", "0.5163796", "0.5158552", "0.5155596", "0.51528883", "0.5139338", "0.5127915", "0.5111905", "0.5110937", "0.5108853", "0.50901127", "0.506584", "0.5062674", "0.50583214", "0.50506026", "0.5050567", "0.5035498", "0.50259304", "0.50135624", "0.4999897", "0.4995804", "0.49912333", "0.49903616", "0.49831367", "0.49736992", "0.4970251", "0.49701416", "0.49670246", "0.4966139", "0.49394092", "0.4936083", "0.49265015", "0.49160543", "0.49156886", "0.4915607", "0.49078292", "0.48958206", "0.48852795", "0.48794883" ]
0.78715014
0
LaunchTask is called when the executor receives a request to launch a task. The happens when the k8sm scheduler has decided to schedule the pod (which corresponds to a Mesos Task) onto the node where this executor is running, but the binding is not recorded in the Kubernetes store yet. This function is invoked to tell the executor to record the binding in the Kubernetes store and start the pod via the Kubelet.
func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) { if k.isDone() { return } log.Infof("Launch task %v\n", taskInfo) if !k.isConnected() { log.Errorf("Ignore launch task because the executor is disconnected\n") k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED, messages.ExecutorUnregistered)) return } obj, err := api.Codec.Decode(taskInfo.GetData()) if err != nil { log.Errorf("failed to extract yaml data from the taskInfo.data %v", err) k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED, messages.UnmarshalTaskDataFailure)) return } pod, ok := obj.(*api.Pod) if !ok { log.Errorf("expected *api.Pod instead of %T: %+v", pod, pod) k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED, messages.UnmarshalTaskDataFailure)) return } k.lock.Lock() defer k.lock.Unlock() taskId := taskInfo.GetTaskId().GetValue() if _, found := k.tasks[taskId]; found { log.Errorf("task already launched\n") // Not to send back TASK_RUNNING here, because // may be duplicated messages or duplicated task id. return } // remember this task so that: // (a) we ignore future launches for it // (b) we have a record of it so that we can kill it if needed // (c) we're leaving podName == "" for now, indicates we don't need to delete containers k.tasks[taskId] = &kuberTask{ mesosTaskInfo: taskInfo, } k.resetSuicideWatch(driver) go k.launchTask(driver, taskId, pod) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) launchTask(driver bindings.ExecutorDriver, taskId string, pod *api.BoundPod) {\n\n\t//HACK(jdef): cloned binding construction from k8s plugin/pkg/scheduler/scheduler.go\n\tbinding := &api.Binding{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tNamespace: pod.Namespace,\n\t\t\tAnnotations: make(map[string]string),\n\t\t},\n\t\tPodID: pod.Name,\n\t\tHost: pod.Annotations[meta.BindingHostKey],\n\t}\n\n\t// forward the bindings that the scheduler wants to apply\n\tfor k, v := range pod.Annotations {\n\t\tbinding.Annotations[k] = v\n\t}\n\n\tlog.Infof(\"Binding '%v' to '%v' with annotations %+v...\", binding.PodID, binding.Host, binding.Annotations)\n\tctx := api.WithNamespace(api.NewDefaultContext(), binding.Namespace)\n\terr := k.client.Post().Namespace(api.NamespaceValue(ctx)).Resource(\"bindings\").Body(binding).Do().Error()\n\tif err != nil {\n\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.CreateBindingFailure))\n\t\treturn\n\t}\n\n\tpodFullName := kubelet.GetPodFullName(&api.BoundPod{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: pod.Name,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tAnnotations: map[string]string{kubelet.ConfigSourceAnnotationKey: k.sourcename},\n\t\t},\n\t})\n\n\t// allow a recently failed-over scheduler the chance to recover the task/pod binding:\n\t// it may have failed and recovered before the apiserver is able to report the updated\n\t// binding information. replays of this status event will signal to the scheduler that\n\t// the apiserver should be up-to-date.\n\tdata, err := json.Marshal(api.PodStatusResult{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: podFullName,\n\t\t\tSelfLink: \"/podstatusresult\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"failed to marshal pod status result: %v\", err)\n\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED, err.Error()))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// Add the task.\n\ttask, found := k.tasks[taskId]\n\tif !found {\n\t\tlog.V(1).Infof(\"task %v no longer on record, probably killed, aborting launch sequence - reporting lost\", taskId)\n\t\tk.reportLostTask(driver, taskId, messages.LaunchTaskFailed)\n\t\treturn\n\t}\n\n\t// from here on, we need to delete containers associated with the task\n\t// upon it going into a terminal state\n\ttask.podName = podFullName\n\tk.pods[podFullName] = pod\n\n\t// Send the pod updates to the channel.\n\tupdate := kubelet.PodUpdate{Op: kubelet.SET}\n\tfor _, p := range k.pods {\n\t\tupdate.Pods = append(update.Pods, *p)\n\t}\n\tk.updateChan <- update\n\n\tstatusUpdate := &mesos.TaskStatus{\n\t\tTaskId: mutil.NewTaskID(taskId),\n\t\tState: mesos.TaskState_TASK_STARTING.Enum(),\n\t\tMessage: proto.String(messages.CreateBindingSuccess),\n\t\tData: data,\n\t}\n\tk.sendStatus(driver, statusUpdate)\n\n\t// Delay reporting 'task running' until container is up.\n\tgo k._launchTask(driver, taskId, podFullName)\n}", "func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Launch task %v\\n\", taskInfo)\n\n\tif !k.isConnected() {\n\t\tlog.Warningf(\"Ignore launch task because the executor is disconnected\\n\")\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.ExecutorUnregistered))\n\t\treturn\n\t}\n\n\tvar pod api.BoundPod\n\tif err := yaml.Unmarshal(taskInfo.GetData(), &pod); err != nil {\n\t\tlog.Warningf(\"Failed to extract yaml data from the taskInfo.data %v\\n\", err)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\ttaskId := taskInfo.GetTaskId().GetValue()\n\tif _, found := k.tasks[taskId]; found {\n\t\tlog.Warningf(\"task already launched\\n\")\n\t\t// Not to send back TASK_RUNNING here, because\n\t\t// may be duplicated messages or duplicated task id.\n\t\treturn\n\t}\n\t// remember this task so that:\n\t// (a) we ignore future launches for it\n\t// (b) we have a record of it so that we can kill it if needed\n\t// (c) we're leaving podName == \"\" for now, indicates we don't need to delete containers\n\tk.tasks[taskId] = &kuberTask{\n\t\tmesosTaskInfo: taskInfo,\n\t}\n\tgo k.launchTask(driver, taskId, &pod)\n}", "func (k *KubernetesExecutor) launchTask(driver bindings.ExecutorDriver, taskId string, pod *api.Pod) {\n\tdeleteTask := func() {\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tdelete(k.tasks, taskId)\n\t\tk.resetSuicideWatch(driver)\n\t}\n\n\t// TODO(k8s): use Pods interface for binding once clusters are upgraded\n\t// return b.Pods(binding.Namespace).Bind(binding)\n\tif pod.Spec.NodeName == \"\" {\n\t\t//HACK(jdef): cloned binding construction from k8s plugin/pkg/scheduler/scheduler.go\n\t\tbinding := &api.Binding{\n\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t\tName: pod.Name,\n\t\t\t\tAnnotations: make(map[string]string),\n\t\t\t},\n\t\t\tTarget: api.ObjectReference{\n\t\t\t\tKind: \"Node\",\n\t\t\t\tName: pod.Annotations[meta.BindingHostKey],\n\t\t\t},\n\t\t}\n\n\t\t// forward the annotations that the scheduler wants to apply\n\t\tfor k, v := range pod.Annotations {\n\t\t\tbinding.Annotations[k] = v\n\t\t}\n\n\t\t// create binding on apiserver\n\t\tlog.Infof(\"Binding '%v/%v' to '%v' with annotations %+v...\", pod.Namespace, pod.Name, binding.Target.Name, binding.Annotations)\n\t\tctx := api.WithNamespace(api.NewContext(), binding.Namespace)\n\t\terr := k.client.Post().Namespace(api.NamespaceValue(ctx)).Resource(\"bindings\").Body(binding).Do().Error()\n\t\tif err != nil {\n\t\t\tdeleteTask()\n\t\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\t\tmessages.CreateBindingFailure))\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// post annotations update to apiserver\n\t\tpatch := struct {\n\t\t\tMetadata struct {\n\t\t\t\tAnnotations map[string]string `json:\"annotations\"`\n\t\t\t} `json:\"metadata\"`\n\t\t}{}\n\t\tpatch.Metadata.Annotations = pod.Annotations\n\t\tpatchJson, _ := json.Marshal(patch)\n\t\tlog.V(4).Infof(\"Patching annotations %v of pod %v/%v: %v\", pod.Annotations, pod.Namespace, pod.Name, string(patchJson))\n\t\terr := k.client.Patch(api.MergePatchType).RequestURI(pod.SelfLink).Body(patchJson).Do().Error()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error updating annotations of ready-to-launch pod %v/%v: %v\", pod.Namespace, pod.Name, err)\n\t\t\tdeleteTask()\n\t\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\t\tmessages.AnnotationUpdateFailure))\n\t\t\treturn\n\t\t}\n\t}\n\n\tpodFullName := container.GetPodFullName(pod)\n\n\t// allow a recently failed-over scheduler the chance to recover the task/pod binding:\n\t// it may have failed and recovered before the apiserver is able to report the updated\n\t// binding information. replays of this status event will signal to the scheduler that\n\t// the apiserver should be up-to-date.\n\tdata, err := json.Marshal(api.PodStatusResult{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: podFullName,\n\t\t\tSelfLink: \"/podstatusresult\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tdeleteTask()\n\t\tlog.Errorf(\"failed to marshal pod status result: %v\", err)\n\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\terr.Error()))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// Add the task.\n\ttask, found := k.tasks[taskId]\n\tif !found {\n\t\tlog.V(1).Infof(\"task %v not found, probably killed: aborting launch, reporting lost\", taskId)\n\t\tk.reportLostTask(driver, taskId, messages.LaunchTaskFailed)\n\t\treturn\n\t}\n\n\t//TODO(jdef) check for duplicate pod name, if found send TASK_ERROR\n\n\t// from here on, we need to delete containers associated with the task\n\t// upon it going into a terminal state\n\ttask.podName = podFullName\n\tk.pods[podFullName] = pod\n\n\t// send the new pod to the kubelet which will spin it up\n\tupdate := kubelet.PodUpdate{\n\t\tOp: kubelet.ADD,\n\t\tPods: []*api.Pod{pod},\n\t}\n\tk.updateChan <- update\n\n\tstatusUpdate := &mesos.TaskStatus{\n\t\tTaskId: mutil.NewTaskID(taskId),\n\t\tState: mesos.TaskState_TASK_STARTING.Enum(),\n\t\tMessage: proto.String(messages.CreateBindingSuccess),\n\t\tData: data,\n\t}\n\tk.sendStatus(driver, statusUpdate)\n\n\t// Delay reporting 'task running' until container is up.\n\tpsf := podStatusFunc(func() (*api.PodStatus, error) {\n\t\tstatus, err := k.podStatusFunc(k.kl, pod)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstatus.Phase = kubelet.GetPhase(&pod.Spec, status.ContainerStatuses)\n\t\thostIP, err := k.kl.GetHostIP()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Cannot get host IP: %v\", err)\n\t\t} else {\n\t\t\tstatus.HostIP = hostIP.String()\n\t\t}\n\t\treturn status, nil\n\t})\n\n\tgo k._launchTask(driver, taskId, podFullName, psf)\n}", "func (k *KubernetesScheduler) Bind(binding *api.Binding) error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tpodId := binding.PodID\n\ttaskId, exists := k.podToTask[podId]\n\tif !exists {\n\t\treturn fmt.Errorf(\"Could not resolve pod '%s' to task id\", podId)\n\t}\n\n\ttask, exists := k.pendingTasks[taskId]\n\tif !exists {\n\t\treturn fmt.Errorf(\"Pod Task does not exist %v\\n\", taskId)\n\t}\n\n\t// TODO(jdef): ensure that the task hasAcceptedOffer(), it's possible that between\n\t// Schedule() and now that the offer for this task was rescinded or invalidated\n\n\t// TODO(k8s): move this to a watch/rectification loop.\n\tmanifest, err := k.makeManifest(binding.Host, *task.Pod)\n\tif err != nil {\n\t\tlog.Warningf(\"Failed to generate an updated manifest\")\n\t\treturn err\n\t}\n\n\t// update the manifest here to pick up things like environment variables that\n\t// pod containers will use for service discovery. the kubelet-executor uses this\n\t// manifest to instantiate the pods and this is the last update we make before\n\t// firing up the pod.\n\ttask.Pod.DesiredState.Manifest = manifest\n\ttask.TaskInfo.Data, err = yaml.Marshal(&manifest)\n\tif err != nil {\n\t\tlog.Warningf(\"Failed to marshal the updated manifest\")\n\t\treturn err\n\t}\n\n\t// TODO(yifan): By this time, there is a chance that the slave is disconnected.\n\tlog.V(2).Infof(\"Launching task : %v\", task)\n\tofferId := &mesos.OfferID{Value: proto.String(task.OfferIds[0])}\n\tif err := k.Driver.LaunchTasks(offerId, []*mesos.TaskInfo{task.TaskInfo}, nil); err != nil {\n\t\ttask.ClearTaskInfo()\n\t\t// TODO(jdef): decline the offer too?\n\t\treturn fmt.Errorf(\"Failed to launch task for pod %s: %v\", podId, err)\n\t}\n\ttask.Pod.DesiredState.Host = binding.Host\n\ttask.Launched = true\n\n\t// we *intentionally* do not record our binding to etcd since we're not using bindings\n\t// to manage pod lifecycle\n\treturn nil\n}", "func (b *binder) bind(ctx api.Context, binding *api.Binding, task *PodTask) (err error) {\n\t// sanity check: ensure that the task hasAcceptedOffer(), it's possible that between\n\t// Schedule() and now that the offer for this task was rescinded or invalidated.\n\t// ((we should never see this here))\n\tif !task.hasAcceptedOffer() {\n\t\treturn fmt.Errorf(\"task has not accepted a valid offer %v\", task.ID)\n\t}\n\n\t// By this time, there is a chance that the slave is disconnected.\n\tofferId := task.GetOfferId()\n\tif offer, ok := b.api.offers().Get(offerId); !ok || offer.HasExpired() {\n\t\t// already rescinded or timed out or otherwise invalidated\n\t\ttask.Offer.Release()\n\t\ttask.ClearTaskInfo()\n\t\treturn fmt.Errorf(\"failed prior to launchTask due to expired offer for task %v\", task.ID)\n\t}\n\n\tif err = b.prepareTaskForLaunch(ctx, binding.Host, task); err == nil {\n\t\tlog.V(2).Infof(\"Attempting to bind %v to %v\", binding.PodID, binding.Host)\n\t\tif err = b.client.Post().Namespace(api.Namespace(ctx)).Resource(\"bindings\").Body(binding).Do().Error(); err == nil {\n\t\t\tlog.V(2).Infof(\"launching task : %v\", task)\n\t\t\tif err = b.api.launchTask(task); err == nil {\n\t\t\t\tb.api.offers().Invalidate(offerId)\n\t\t\t\ttask.Pod.Status.Host = binding.Host\n\t\t\t\ttask.launched = true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\ttask.Offer.Release()\n\ttask.ClearTaskInfo()\n\treturn fmt.Errorf(\"Failed to launch task %v: %v\", task.ID, err)\n}", "func (h *Hub) StartTask(ctx context.Context, request *pb.HubStartTaskRequest) (*pb.HubStartTaskReply, error) {\n\tlog.G(h.ctx).Info(\"handling StartTask request\", zap.Any(\"req\", request))\n\n\ttaskID := uuid.New()\n\tminer, err := h.selectMiner(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar startRequest = &pb.MinerStartRequest{\n\t\tId: taskID,\n\t\tRegistry: request.Registry,\n\t\tImage: request.Image,\n\t\tAuth: request.Auth,\n\t\tPublicKeyData: request.PublicKeyData,\n\t\tCommitOnStop: request.CommitOnStop,\n\t\tEnv: request.Env,\n\t\tUsage: request.Requirements.GetResources(),\n\t\tRestartPolicy: &pb.ContainerRestartPolicy{\n\t\t\tName: \"\",\n\t\t\tMaximumRetryCount: 0,\n\t\t},\n\t}\n\n\tresp, err := miner.Client.Start(ctx, startRequest)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to start %v\", err)\n\t}\n\n\troutes := []extRoute{}\n\tfor k, v := range resp.Ports {\n\t\t_, protocol, err := decodePortBinding(k)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to decode miner's port mapping\",\n\t\t\t\tzap.String(\"mapping\", k),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\trealPort, err := strconv.ParseUint(v.Port, 10, 16)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to convert real port to uint16\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"port\", v.Port),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\troute, err := miner.router.RegisterRoute(taskID, protocol, v.IP, uint16(realPort))\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to register route\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\troutes = append(routes, extRoute{\n\t\t\tcontainerPort: k,\n\t\t\troute: route,\n\t\t})\n\t}\n\n\th.setMinerTaskID(miner.ID(), taskID)\n\n\tresources := request.GetRequirements().GetResources()\n\tcpuCount := resources.GetCPUCores()\n\tmemoryCount := resources.GetMaxMemory()\n\n\tvar usage = resource.NewResources(int(cpuCount), int64(memoryCount))\n\tif err := miner.Consume(taskID, &usage); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar reply = pb.HubStartTaskReply{\n\t\tId: taskID,\n\t}\n\n\tfor _, route := range routes {\n\t\treply.Endpoint = append(\n\t\t\treply.Endpoint,\n\t\t\tfmt.Sprintf(\"%s->%s:%d\", route.containerPort, route.route.Host, route.route.Port),\n\t\t)\n\t}\n\n\treturn &reply, nil\n}", "func (lenc *Lencak) StartTask(workSpaceName, taskName string, asService bool) bool {\n\treturn lenc.WithWorkspaceTask(workSpaceName, taskName, func(task *Task) {\n\t\tif asService {\n\t\t\ttask.serviceMu.Lock()\n\t\t\ttask.Service = true\n\t\t\ttask.serviceMu.Unlock()\n\t\t\tif task.ActiveTask == nil {\n\t\t\t\ttask.Start(lenc.sync)\n\t\t\t}\n\t\t} else {\n\t\t\ttask.Start(lenc.sync)\n\t\t}\n\t})\n}", "func (rm *ResponseManager) StartTask(task *peertask.Task, responseTaskDataChan chan<- ResponseTaskData) {\n\trm.send(&startTaskRequest{task, responseTaskDataChan}, nil)\n}", "func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) {\n\tif _, ok := d.tasks.Get(cfg.ID); ok {\n\t\treturn nil, nil, fmt.Errorf(\"task with ID %q already started\", cfg.ID)\n\t}\n\n\tvar driverConfig TaskConfig\n\tif err := cfg.DecodeDriverConfig(&driverConfig); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode driver config: %v\", err)\n\t}\n\n\thandle := drivers.NewTaskHandle(taskHandleVersion)\n\thandle.Config = cfg\n\n\tif driverConfig.Image == \"\" {\n\t\treturn nil, nil, fmt.Errorf(\"image name required\")\n\t}\n\n\tcreateOpts := api.SpecGenerator{}\n\tcreateOpts.ContainerBasicConfig.LogConfiguration = &api.LogConfig{}\n\tallArgs := []string{}\n\tif driverConfig.Command != \"\" {\n\t\tallArgs = append(allArgs, driverConfig.Command)\n\t}\n\tallArgs = append(allArgs, driverConfig.Args...)\n\n\tif driverConfig.Entrypoint != \"\" {\n\t\tcreateOpts.ContainerBasicConfig.Entrypoint = append(createOpts.ContainerBasicConfig.Entrypoint, driverConfig.Entrypoint)\n\t}\n\n\tcontainerName := BuildContainerName(cfg)\n\n\t// ensure to include port_map into tasks environment map\n\tcfg.Env = taskenv.SetPortMapEnvs(cfg.Env, driverConfig.PortMap)\n\n\t// Basic config options\n\tcreateOpts.ContainerBasicConfig.Name = containerName\n\tcreateOpts.ContainerBasicConfig.Command = allArgs\n\tcreateOpts.ContainerBasicConfig.Env = cfg.Env\n\tcreateOpts.ContainerBasicConfig.Hostname = driverConfig.Hostname\n\tcreateOpts.ContainerBasicConfig.Sysctl = driverConfig.Sysctl\n\n\tcreateOpts.ContainerBasicConfig.LogConfiguration.Path = cfg.StdoutPath\n\n\t// Storage config options\n\tcreateOpts.ContainerStorageConfig.Init = driverConfig.Init\n\tcreateOpts.ContainerStorageConfig.Image = driverConfig.Image\n\tcreateOpts.ContainerStorageConfig.InitPath = driverConfig.InitPath\n\tcreateOpts.ContainerStorageConfig.WorkDir = driverConfig.WorkingDir\n\tallMounts, err := d.containerMounts(cfg, &driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerStorageConfig.Mounts = allMounts\n\n\t// Resources config options\n\tcreateOpts.ContainerResourceConfig.ResourceLimits = &spec.LinuxResources{\n\t\tMemory: &spec.LinuxMemory{},\n\t\tCPU: &spec.LinuxCPU{},\n\t}\n\tif driverConfig.MemoryReservation != \"\" {\n\t\treservation, err := memoryInBytes(driverConfig.MemoryReservation)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Reservation = &reservation\n\t}\n\n\tif cfg.Resources.NomadResources.Memory.MemoryMB > 0 {\n\t\tlimit := cfg.Resources.NomadResources.Memory.MemoryMB * 1024 * 1024\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Limit = &limit\n\t}\n\tif driverConfig.MemorySwap != \"\" {\n\t\tswap, err := memoryInBytes(driverConfig.MemorySwap)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swap = &swap\n\t}\n\tif !d.cgroupV2 {\n\t\tswappiness := uint64(driverConfig.MemorySwappiness)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swappiness = &swappiness\n\t}\n\t// FIXME: can fail for nonRoot due to missing cpu limit delegation permissions,\n\t// see https://github.com/containers/podman/blob/master/troubleshooting.md\n\tif !d.systemInfo.Host.Rootless {\n\t\tcpuShares := uint64(cfg.Resources.LinuxResources.CPUShares)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.CPU.Shares = &cpuShares\n\t}\n\n\t// Security config options\n\tcreateOpts.ContainerSecurityConfig.CapAdd = driverConfig.CapAdd\n\tcreateOpts.ContainerSecurityConfig.CapDrop = driverConfig.CapDrop\n\tcreateOpts.ContainerSecurityConfig.User = cfg.User\n\n\t// Network config options\n\tfor _, strdns := range driverConfig.Dns {\n\t\tipdns := net.ParseIP(strdns)\n\t\tif ipdns == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"Invald dns server address\")\n\t\t}\n\t\tcreateOpts.ContainerNetworkConfig.DNSServers = append(createOpts.ContainerNetworkConfig.DNSServers, ipdns)\n\t}\n\t// Configure network\n\tif cfg.NetworkIsolation != nil && cfg.NetworkIsolation.Path != \"\" {\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.Value = cfg.NetworkIsolation.Path\n\t} else {\n\t\tif driverConfig.NetworkMode == \"\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"bridge\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"host\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Host\n\t\t} else if driverConfig.NetworkMode == \"none\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.NoNetwork\n\t\t} else if driverConfig.NetworkMode == \"slirp4netns\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp\n\t\t} else {\n\t\t\treturn nil, nil, fmt.Errorf(\"Unknown/Unsupported network mode: %s\", driverConfig.NetworkMode)\n\t\t}\n\t}\n\n\tportMappings, err := d.portMappings(cfg, driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerNetworkConfig.PortMappings = portMappings\n\n\tcontainerID := \"\"\n\trecoverRunningContainer := false\n\t// check if there is a container with same name\n\totherContainerInspect, err := d.podman.ContainerInspect(d.ctx, containerName)\n\tif err == nil {\n\t\t// ok, seems we found a container with similar name\n\t\tif otherContainerInspect.State.Running {\n\t\t\t// it's still running. So let's use it instead of creating a new one\n\t\t\td.logger.Info(\"Detect running container with same name, we reuse it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tcontainerID = otherContainerInspect.ID\n\t\t\trecoverRunningContainer = true\n\t\t} else {\n\t\t\t// let's remove the old, dead container\n\t\t\td.logger.Info(\"Detect stopped container with same name, removing it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tif err = d.podman.ContainerDelete(d.ctx, otherContainerInspect.ID, true, true); err != nil {\n\t\t\t\treturn nil, nil, nstructs.WrapRecoverable(fmt.Sprintf(\"failed to remove dead container: %v\", err), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\t// FIXME: there are more variations of image sources, we should handle it\n\t\t// e.g. oci-archive:/... etc\n\t\t// see also https://github.com/hashicorp/nomad-driver-podman/issues/69\n\t\t// do we already have this image in local storage?\n\t\thaveImage, err := d.podman.ImageExists(d.ctx, createOpts.Image)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to check for local image: %v\", err)\n\t\t}\n\t\tif !haveImage {\n\t\t\t// image is not in local storage, so we need to pull it\n\t\t\tif err = d.podman.ImagePull(d.ctx, createOpts.Image); err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to pull image %s: %v\", createOpts.Image, err)\n\t\t\t}\n\t\t}\n\n\t\tcreateResponse, err := d.podman.ContainerCreate(d.ctx, createOpts)\n\t\tfor _, w := range createResponse.Warnings {\n\t\t\td.logger.Warn(\"Create Warning\", \"warning\", w)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not create container: %v\", err)\n\t\t}\n\t\tcontainerID = createResponse.Id\n\t}\n\n\tcleanup := func() {\n\t\td.logger.Debug(\"Cleaning up\", \"container\", containerID)\n\t\tif err := d.podman.ContainerDelete(d.ctx, containerID, true, true); err != nil {\n\t\t\td.logger.Error(\"failed to clean up from an error in Start\", \"error\", err)\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\tif err = d.podman.ContainerStart(d.ctx, containerID); err != nil {\n\t\t\tcleanup()\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not start container: %v\", err)\n\t\t}\n\t}\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, containerID)\n\tif err != nil {\n\t\td.logger.Error(\"failed to inspect container\", \"err\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not inspect container : %v\", err)\n\t}\n\n\tnet := &drivers.DriverNetwork{\n\t\tPortMap: driverConfig.PortMap,\n\t\tIP: inspectData.NetworkSettings.IPAddress,\n\t\tAutoAdvertise: true,\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: containerID,\n\t\tdriver: d,\n\t\ttaskConfig: cfg,\n\t\tprocState: drivers.TaskStateRunning,\n\t\texitResult: &drivers.ExitResult{},\n\t\tstartedAt: time.Now().Round(time.Millisecond),\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tdriverState := TaskState{\n\t\tContainerID: containerID,\n\t\tTaskConfig: cfg,\n\t\tStartedAt: h.startedAt,\n\t\tNet: net,\n\t}\n\n\tif err := handle.SetDriverState(&driverState); err != nil {\n\t\td.logger.Error(\"failed to start task, error setting driver state\", \"error\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to set driver state: %v\", err)\n\t}\n\n\td.tasks.Set(cfg.ID, h)\n\n\tgo h.runContainerMonitor()\n\n\td.logger.Info(\"Completely started container\", \"taskID\", cfg.ID, \"container\", containerID, \"ip\", inspectData.NetworkSettings.IPAddress)\n\n\treturn handle, net, nil\n}", "func (i *TaskRegisterUpdater) StartTask(ctx context.Context, action string, age time.Duration) (models.Task, error) {\n\n\treturn i.repository.GetTask(ctx, action, age)\n}", "func (env *Env) Run(task Task) {\n env.session.SetIsPingTask(true)\n switch t := task.(type) {\n case *PingMessageTask:\n env.pingMessageTask = t\n }\n go task.run(env.channel)\n}", "func (s stressng) Launch() (executor.TaskHandle, error) {\n\treturn s.executor.Execute(fmt.Sprintf(\"stress-ng %s\", s.arguments))\n}", "func (s *Session) Start(tags map[string]interface{}) error {\n\tif s.task != nil {\n\t\treturn errors.New(\"task already running\")\n\t}\n\n\tt := &task{\n\t\tName: s.TaskName,\n\t\tVersion: 1,\n\t\tSchedule: s.Schedule,\n\t}\n\n\twf := wmap.NewWorkflowMap()\n\n\tsnapTags := make(map[string]string)\n\tfor key, value := range tags {\n\t\tsnapTags[key] = fmt.Sprintf(\"%v\", value)\n\t}\n\twf.CollectNode.Tags = map[string]map[string]string{\"\": snapTags}\n\n\tfor _, metric := range s.Metrics {\n\t\twf.CollectNode.AddMetric(metric, -1)\n\t}\n\n\tfor _, configItem := range s.CollectNodeConfigItems {\n\t\twf.CollectNode.AddConfigItem(configItem.Ns, configItem.Key, configItem.Value)\n\t}\n\n\tloaderConfig := DefaultPluginLoaderConfig()\n\tloaderConfig.SnapteldAddress = s.pClient.URL\n\n\t// Add specified publisher to workflow as well.\n\twf.CollectNode.Add(s.Publisher)\n\n\tt.Workflow = wf\n\n\tr := s.pClient.CreateTask(t.Schedule, t.Workflow, t.Name, t.Deadline, true, 10)\n\tif r.Err != nil {\n\t\treturn errors.Wrapf(r.Err, \"could not create task %q\", t.Name)\n\t}\n\n\t// Save a copy of the task so we can stop it again.\n\tt.ID = r.ID\n\tt.State = r.State\n\ts.task = t\n\n\treturn nil\n}", "func (c Control) ServeStartTask(w http.ResponseWriter, r *http.Request) {\n\tc.ServeTaskAction(w, r, true)\n}", "func StartDMTask(fw portforward.PortForward, ns, masterSvcName, taskConf, errSubStr string) error {\n\tapiPath := \"/apis/v1alpha1/tasks\"\n\n\ttype Req struct {\n\t\tTask string `json:\"task\"`\n\t}\n\ttype Resp struct {\n\t\tResult bool `json:\"result\"`\n\t\tMsg string `json:\"msg\"`\n\t\tCheckResult string `json:\"checkResult\"`\n\t}\n\n\tvar req = Req{\n\t\tTask: fmt.Sprintf(taskConf, DMTaskName(ns), v1alpha1.DefaultTiDBServerPort, DMTaskName(ns)),\n\t}\n\tdata, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal task start request, %v, %v\", req, err)\n\t}\n\n\treturn wait.Poll(5*time.Second, time.Minute, func() (bool, error) {\n\t\tlocalHost, localPort, cancel, err := portforward.ForwardOnePort(\n\t\t\tfw, ns, fmt.Sprintf(\"svc/%s\", masterSvcName), dmMasterSvcPort)\n\t\tif err != nil {\n\t\t\tlog.Logf(\"failed to forward dm-master svc: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tdefer cancel()\n\n\t\tbody, err := httputil.DoBodyOK(\n\t\t\t&http.Client{Transport: &http.Transport{}},\n\t\t\tfmt.Sprintf(\"http://%s:%d%s\", localHost, localPort, apiPath),\n\t\t\t\"POST\",\n\t\t\tbytes.NewReader(data))\n\t\tif err != nil {\n\t\t\tlog.Logf(\"failed to start DM task: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tvar resp Resp\n\t\tif err = json.Unmarshal(body, &resp); err != nil {\n\t\t\tlog.Logf(\"failed to unmarshal DM task start response, %s: %v\", string(body), err)\n\t\t\treturn false, nil\n\t\t} else if !resp.Result && !strings.Contains(resp.Msg, \"already exists\") {\n\t\t\tif errSubStr != \"\" && strings.Contains(resp.Msg, errSubStr) {\n\t\t\t\tlog.Logf(\"start DM task match the error sub string %q: %s\", errSubStr, resp.Msg)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tlog.Logf(\"failed to start DM task, msg: %s, err: %v, checkResult: %s\", resp.Msg, err, resp.CheckResult)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n}", "func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {\n\tcfg := ctl.Task().(*messages.GitilesTask)\n\n\tctl.DebugLog(\"Repo: %s, Refs: %s\", cfg.Repo, cfg.Refs)\n\tu, err := url.Parse(cfg.Repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twatchedRefs := watchedRefs{}\n\twatchedRefs.init(cfg.GetRefs())\n\n\tvar wg sync.WaitGroup\n\n\tvar heads map[string]string\n\tvar headsErr error\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\theads, headsErr = loadState(c, ctl.JobID(), u)\n\t}()\n\n\tvar refs map[string]string\n\tvar refsErr error\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\trefs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs)\n\t}()\n\n\twg.Wait()\n\n\tif headsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch heads - %s\", headsErr)\n\t\treturn fmt.Errorf(\"failed to fetch heads: %v\", headsErr)\n\t}\n\tif refsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch refs - %s\", refsErr)\n\t\treturn fmt.Errorf(\"failed to fetch refs: %v\", refsErr)\n\t}\n\n\trefsChanged := 0\n\n\t// Delete all previously known refs which are either no longer watched or no\n\t// longer exist in repo.\n\tfor ref := range heads {\n\t\tswitch {\n\t\tcase !watchedRefs.hasRef(ref):\n\t\t\tctl.DebugLog(\"Ref %s is no longer watched\", ref)\n\t\t\tdelete(heads, ref)\n\t\t\trefsChanged++\n\t\tcase refs[ref] == \"\":\n\t\t\tctl.DebugLog(\"Ref %s deleted\", ref)\n\t\t\tdelete(heads, ref)\n\t\t\trefsChanged++\n\t\t}\n\t}\n\t// For determinism, sort keys of current refs.\n\tsortedRefs := make([]string, 0, len(refs))\n\tfor ref := range refs {\n\t\tsortedRefs = append(sortedRefs, ref)\n\t}\n\tsort.Strings(sortedRefs)\n\n\temittedTriggers := 0\n\tmaxTriggersPerInvocation := m.maxTriggersPerInvocation\n\tif maxTriggersPerInvocation == 0 {\n\t\tmaxTriggersPerInvocation = defaultMaxTriggersPerInvocation\n\t}\n\t// Note, that current `refs` contain only watched refs (see getRefsTips).\n\tfor _, ref := range sortedRefs {\n\t\tnewHead := refs[ref]\n\t\toldHead, existed := heads[ref]\n\t\tswitch {\n\t\tcase !existed:\n\t\t\tctl.DebugLog(\"Ref %s is new: %s\", ref, newHead)\n\t\tcase oldHead != newHead:\n\t\t\tctl.DebugLog(\"Ref %s updated: %s => %s\", ref, oldHead, newHead)\n\t\tdefault:\n\t\t\t// No change.\n\t\t\tcontinue\n\t\t}\n\t\theads[ref] = newHead\n\t\trefsChanged++\n\t\temittedTriggers++\n\t\t// TODO(tandrii): actually look at commits between current and previously\n\t\t// known tips of each ref.\n\t\t// In current (v1) engine, all triggers emitted around the same time will\n\t\t// result in just 1 invocation of each triggered job. Therefore,\n\t\t// passing just HEAD's revision is good enough.\n\t\t// For the same reason, only 1 of the refs will actually be processed if\n\t\t// several refs changed at the same time.\n\t\tctl.EmitTrigger(c, &internal.Trigger{\n\t\t\tId: fmt.Sprintf(\"%s/+/%s@%s\", cfg.Repo, ref, newHead),\n\t\t\tTitle: newHead,\n\t\t\tUrl: fmt.Sprintf(\"%s/+/%s\", cfg.Repo, newHead),\n\t\t\tPayload: &internal.Trigger_Gitiles{\n\t\t\t\tGitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead},\n\t\t\t},\n\t\t})\n\n\t\t// Safeguard against too many changes such as the first run after\n\t\t// config change to watch many more refs than before.\n\t\tif emittedTriggers >= maxTriggersPerInvocation {\n\t\t\tctl.DebugLog(\"Emitted %d triggers, postponing the rest\", emittedTriggers)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif refsChanged == 0 {\n\t\tctl.DebugLog(\"No changes detected\")\n\t} else {\n\t\tctl.DebugLog(\"%d refs changed\", refsChanged)\n\t\t// Force save to ensure triggers are actually emitted.\n\t\tif err := ctl.Save(c); err != nil {\n\t\t\t// At this point, triggers have not been sent, so bail now and don't save\n\t\t\t// the refs' heads newest values.\n\t\t\treturn err\n\t\t}\n\t\tif err := saveState(c, ctl.JobID(), u, heads); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctl.DebugLog(\"Saved %d known refs\", len(heads))\n\t}\n\n\tctl.State().Status = task.StatusSucceeded\n\treturn nil\n}", "func (e *ECS) StartTask(req *StartTaskReq) (*StartTaskResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"StartTask\")\n\tif req.Cluster != \"\" {\n\t\tparams[\"cluster\"] = req.Cluster\n\t}\n\tif req.TaskDefinition != \"\" {\n\t\tparams[\"taskDefinition\"] = req.TaskDefinition\n\t}\n\tfor i, ci := range req.ContainerInstances {\n\t\tparams[fmt.Sprintf(\"containerInstances.member.%d\", i+1)] = ci\n\t}\n\tfor i, co := range req.Overrides.ContainerOverrides {\n\t\tkey := fmt.Sprintf(\"overrides.containerOverrides.member.%d\", i+1)\n\t\tparams[fmt.Sprintf(\"%s.name\", key)] = co.Name\n\t\tfor k, cmd := range co.Command {\n\t\t\tparams[fmt.Sprintf(\"%s.command.member.%d\", key, k+1)] = cmd\n\t\t}\n\t}\n\n\tresp := new(StartTaskResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func StartTaskService(brain *brain.Manager, errChan chan error) {\n\tlis, err := net.Listen(\"tcp\", taskServicePort)\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\n\tRegisterTaskServiceServer(grpcServer, TaskService{Manager: brain})\n\n\tlog.LogInfo(\"starting taask-server task service on :3688\")\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\terrChan <- err\n\t}\n}", "func (c *Client) StartTask(ctx context.Context, params *StartTaskInput, optFns ...func(*Options)) (*StartTaskOutput, error) {\n\tif params == nil {\n\t\tparams = &StartTaskInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"StartTask\", params, optFns, addOperationStartTaskMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*StartTaskOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *K8sSvc) RunTask(ctx context.Context, opts *containersvc.RunTaskOptions) (taskID string, err error) {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\ttaskID = opts.Common.ServiceName + common.NameSeparator + opts.TaskType\n\n\tlabels := make(map[string]string)\n\tlabels[serviceNameLabel] = opts.Common.ServiceName\n\tlabels[serviceUUIDLabel] = opts.Common.ServiceUUID\n\n\tenvs := make([]corev1.EnvVar, len(opts.Envkvs))\n\tfor i, e := range opts.Envkvs {\n\t\tenvs[i] = corev1.EnvVar{\n\t\t\tName: e.Name,\n\t\t\tValue: e.Value,\n\t\t}\n\t}\n\n\tjob := &batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: taskID,\n\t\t\tNamespace: s.namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tParallelism: utils.Int32Ptr(1),\n\t\t\tCompletions: utils.Int32Ptr(1),\n\t\t\t// allow restarting the job twice before mark the job failed.\n\t\t\tBackoffLimit: utils.Int32Ptr(2),\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: taskID,\n\t\t\t\t\tNamespace: s.namespace,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: taskID,\n\t\t\t\t\t\t\tImage: opts.Common.ContainerImage,\n\t\t\t\t\t\t\tEnv: envs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = s.cliset.BatchV1().Jobs(s.namespace).Create(job)\n\tif err != nil {\n\t\tif k8errors.IsAlreadyExists(err) {\n\t\t\tglog.Infoln(\"service task exist\", taskID, \"requuid\", requuid)\n\t\t\treturn taskID, nil\n\t\t}\n\t\tglog.Errorln(\"create service task error\", taskID, \"requuid\", requuid)\n\t\treturn \"\", err\n\t}\n\n\tglog.Infoln(\"created service task\", taskID, \"requuid\", requuid)\n\treturn taskID, nil\n}", "func (w *worker) taskLaunchStep(task concurrency.Task, params concurrency.TaskParameters) (_ concurrency.TaskResult, xerr fail.Error) {\n\tdefer fail.OnPanic(&xerr)\n\n\tif w == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif w.feature == nil {\n\t\treturn nil, fail.InvalidInstanceContentError(\"w.Feature\", \"cannot be nil\")\n\t}\n\tif task == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"task\")\n\t}\n\tif params == nil {\n\t\treturn nil, fail.InvalidParameterError(\"params\", \"can't be nil\")\n\t}\n\n\tvar (\n\t\tanon interface{}\n\t\tok bool\n\t)\n\tp := params.(taskLaunchStepParameters)\n\n\tif p.stepName == \"\" {\n\t\treturn nil, fail.InvalidParameterError(\"param.stepName\", \"cannot be empty string\")\n\t}\n\tif p.stepKey == \"\" {\n\t\treturn nil, fail.InvalidParameterError(\"param.stepKey\", \"cannot be empty string\")\n\t}\n\tif p.stepMap == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"params.stepMap\")\n\t}\n\tif p.variables == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"params[variables]\")\n\t}\n\n\tif task.Aborted() {\n\t\tif lerr, err := task.LastError(); err == nil {\n\t\t\treturn nil, fail.AbortedError(lerr, \"aborted\")\n\t\t}\n\t\treturn nil, fail.AbortedError(nil, \"aborted\")\n\t}\n\n\tdefer fail.OnExitLogError(&xerr, fmt.Sprintf(\"executed step '%s::%s'\", w.action.String(), p.stepName))\n\tdefer temporal.NewStopwatch().OnExitLogWithLevel(\n\t\tfmt.Sprintf(\"Starting execution of step '%s::%s'...\", w.action.String(), p.stepName),\n\t\tfmt.Sprintf(\"Ending execution of step '%s::%s' with error '%s'\", w.action.String(), p.stepName, xerr),\n\t\tlogrus.DebugLevel,\n\t)\n\n\tvar (\n\t\trunContent string\n\t\tstepT = stepTargets{}\n\t\t// options = map[string]string{}\n\t)\n\n\t// Determine list of hosts concerned by the step\n\tvar hostsList []resources.Host\n\tif w.target.TargetType() == featuretargettype.Host {\n\t\thostsList, xerr = w.identifyHosts(task.Context(), map[string]string{\"hosts\": \"1\"})\n\t} else {\n\t\tanon, ok = p.stepMap[yamlTargetsKeyword]\n\t\tif ok {\n\t\t\tfor i, j := range anon.(map[string]interface{}) {\n\t\t\t\tswitch j := j.(type) {\n\t\t\t\tcase bool:\n\t\t\t\t\tif j {\n\t\t\t\t\t\tstepT[i] = \"true\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstepT[i] = \"false\"\n\t\t\t\t\t}\n\t\t\t\tcase string:\n\t\t\t\t\tstepT[i] = j\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tmsg := `syntax error in Feature '%s' specification file (%s): no key '%s.%s' found`\n\t\t\treturn nil, fail.SyntaxError(msg, w.feature.GetName(), w.feature.GetDisplayFilename(), p.stepKey, yamlTargetsKeyword)\n\t\t}\n\n\t\thostsList, xerr = w.identifyHosts(task.Context(), stepT)\n\t}\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tif len(hostsList) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Marks hosts instances as released after use\n\tdefer func() {\n\t\tfor _, v := range hostsList {\n\t\t\tv.Released()\n\t\t}\n\t}()\n\n\t// Get the content of the action based on method\n\tvar keyword string\n\tswitch w.method {\n\tcase installmethod.Apt, installmethod.Yum, installmethod.Dnf:\n\t\tkeyword = yamlPackageKeyword\n\tdefault:\n\t\tkeyword = yamlRunKeyword\n\t}\n\trunContent, ok = p.stepMap[keyword].(string)\n\tif ok {\n\t\t// If 'run' content has to be altered, do it\n\t\tif w.commandCB != nil {\n\t\t\trunContent = w.commandCB(runContent)\n\t\t}\n\t} else {\n\t\tmsg := `syntax error in Feature '%s' specification file (%s): no key '%s.%s' found`\n\t\treturn nil, fail.SyntaxError(msg, w.feature.GetName(), w.feature.GetDisplayFilename(), p.stepKey, yamlRunKeyword)\n\t}\n\n\twallTime := temporal.GetLongOperationTimeout()\n\tif anon, ok = p.stepMap[yamlTimeoutKeyword]; ok {\n\t\tif _, ok := anon.(int); ok {\n\t\t\twallTime = time.Duration(anon.(int)) * time.Minute\n\t\t} else {\n\t\t\twallTimeConv, inner := strconv.Atoi(anon.(string))\n\t\t\tif inner != nil {\n\t\t\t\tlogrus.Warningf(\"Invalid value '%s' for '%s.%s', ignored.\", anon.(string), w.rootKey, yamlTimeoutKeyword)\n\t\t\t} else {\n\t\t\t\twallTime = time.Duration(wallTimeConv) * time.Minute\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplateCommand, xerr := normalizeScript(&p.variables, data.Map{\n\t\t\"reserved_Name\": w.feature.GetName(),\n\t\t\"reserved_Content\": runContent,\n\t\t\"reserved_Action\": strings.ToLower(w.action.String()),\n\t\t\"reserved_Step\": p.stepName,\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\t// Checks if step can be performed in parallel on selected hosts\n\tserial := false\n\tanon, ok = p.stepMap[yamlSerialKeyword]\n\tif ok {\n\t\tvalue, ok := anon.(string)\n\t\tif ok {\n\t\t\tif strings.ToLower(value) == \"yes\" || strings.ToLower(value) != \"true\" {\n\t\t\t\tserial = true\n\t\t\t}\n\t\t}\n\t}\n\n\tstepInstance := step{\n\t\tWorker: w,\n\t\tName: p.stepName,\n\t\tAction: w.action,\n\t\tScript: templateCommand,\n\t\tWallTime: wallTime,\n\t\t// OptionsFileContent: optionsFileContent,\n\t\tYamlKey: p.stepKey,\n\t\tSerial: serial,\n\t}\n\tr, xerr := stepInstance.Run(task, hostsList, p.variables, w.settings)\n\t// If an error occurred, do not execute the remaining steps, fail immediately\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tif !r.Successful() {\n\t\t// If there are some not completed steps, reports them and break\n\t\tif !r.Completed() {\n\t\t\tvar errpack []error\n\t\t\tfor _, key := range r.Keys() {\n\t\t\t\tcuk := r.ResultOfKey(key)\n\t\t\t\tif cuk != nil {\n\t\t\t\t\tif !cuk.Successful() && !cuk.Completed() {\n\t\t\t\t\t\t// TBR: It's one of those\n\t\t\t\t\t\tmsg := fmt.Errorf(\"execution unsuccessful and incomplete of step '%s::%s' failed on: %v with [%s]\", w.action.String(), p.stepName, cuk.Error(), spew.Sdump(cuk))\n\t\t\t\t\t\tlogrus.Warnf(msg.Error())\n\t\t\t\t\t\terrpack = append(errpack, msg)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(errpack) > 0 {\n\t\t\t\treturn &r, fail.NewErrorList(errpack)\n\t\t\t}\n\t\t}\n\n\t\t// not successful but completed, if action is check means the Feature is not installed, it's an information not a failure\n\t\tif w.action == installaction.Check {\n\t\t\treturn &r, nil\n\t\t}\n\n\t\tvar newerrpack []error\n\t\tfor _, key := range r.Keys() {\n\t\t\tcuk := r.ResultOfKey(key)\n\t\t\tif cuk != nil {\n\t\t\t\tif !cuk.Successful() && cuk.Completed() {\n\t\t\t\t\t// TBR: It's one of those\n\t\t\t\t\tmsg := fmt.Errorf(\"execution unsuccessful of step '%s::%s' failed on: %s with [%v]\", w.action.String(), p.stepName, key /*cuk.Error()*/, spew.Sdump(cuk))\n\t\t\t\t\tlogrus.Warnf(msg.Error())\n\t\t\t\t\tnewerrpack = append(newerrpack, msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(newerrpack) > 0 {\n\t\t\treturn &r, fail.NewErrorList(newerrpack)\n\t\t}\n\t}\n\n\treturn &r, nil\n}", "func HandleStartTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleStartTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStartTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleStartTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\ttaskCapacity, err := node.StartTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStartTask Start task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tif taskCapacity < 0 {\n\t\tlog.Root.Error(\"HandleStartTask Lack of computing resources\")\n\t\tHttpResponseError(w, ErrLackResources)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleStartTask END\")\n\tHttpResponseData(w, H{\n\t\t\"taskCapacity\": taskCapacity,\n\t})\n\treturn\n}", "func InitiateRakeTask(taskName string, settings *models.Settings) {\n\trakeTask := map[string]string{}\n\tb, err := json.Marshal(rakeTask)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\tencodedTaskName, err := url.Parse(taskName)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\thttpclient.Post(b, fmt.Sprintf(\"%s/v1/environments/%s/services/%s/rake/%s\", settings.PaasHost, settings.EnvironmentID, settings.ServiceID, encodedTaskName), true, settings)\n}", "func NewTask(cluster *api.Cluster, service *api.Service, slot uint64, nodeID string) *api.Task {\n\tvar logDriver *api.Driver\n\tif service.Spec.Task.LogDriver != nil {\n\t\t// use the log driver specific to the task, if we have it.\n\t\tlogDriver = service.Spec.Task.LogDriver\n\t} else if cluster != nil {\n\t\t// pick up the cluster default, if available.\n\t\tlogDriver = cluster.Spec.TaskDefaults.LogDriver // nil is okay here.\n\t}\n\n\ttaskID := identity.NewID()\n\ttask := api.Task{\n\t\tID: taskID,\n\t\tServiceAnnotations: service.Spec.Annotations,\n\t\tSpec: service.Spec.Task,\n\t\tServiceID: service.ID,\n\t\tSlot: slot,\n\t\tStatus: api.TaskStatus{\n\t\t\tState: api.TaskStateNew,\n\t\t\tTimestamp: ptypes.MustTimestampProto(time.Now()),\n\t\t\tMessage: \"created\",\n\t\t},\n\t\tEndpoint: &api.Endpoint{\n\t\t\tSpec: service.Spec.Endpoint.Copy(),\n\t\t},\n\t\tDesiredState: api.TaskStateRunning,\n\t\tLogDriver: logDriver,\n\t}\n\n\t// In global mode we also set the NodeID\n\tif nodeID != \"\" {\n\t\ttask.NodeID = nodeID\n\t}\n\n\treturn &task\n}", "func (b *binder) Bind(binding *api.Binding) error {\n\n\tctx := api.WithNamespace(api.NewContext(), binding.Namespace)\n\n\t// default upstream scheduler passes pod.Name as binding.PodID\n\tpodKey, err := makePodKey(ctx, binding.PodID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb.api.Lock()\n\tdefer b.api.Unlock()\n\n\ttaskId, exists := b.api.taskForPod(podKey)\n\tif !exists {\n\t\tlog.Infof(\"Could not resolve pod %s to task id\", podKey)\n\t\treturn noSuchPodErr\n\t}\n\n\tswitch task, state := b.api.getTask(taskId); state {\n\tcase statePending:\n\t\treturn b.bind(ctx, binding, task)\n\tdefault:\n\t\t// in this case it's likely that the pod has been deleted between Schedule\n\t\t// and Bind calls\n\t\tlog.Infof(\"No pending task for pod %s\", podKey)\n\t\treturn noSuchPodErr\n\t}\n}", "func (*container) AttachTask(context.Context, libcontainerdtypes.StdioCallback) (libcontainerdtypes.Task, error) {\n\treturn nil, errdefs.NotFound(cerrdefs.ErrNotImplemented)\n}", "func (c *ECS) StartTask(input *StartTaskInput) (output *StartTaskOutput, err error) {\n\treq, out := c.StartTaskRequest(input)\n\toutput = out\n\terr = req.Send()\n\treturn\n}", "func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {\n\tcfg := ctl.Task().(*messages.GitilesTask)\n\n\tu, err := url.Parse(cfg.Repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg := gerrit.NewGerrit(u)\n\n\tvar wg sync.WaitGroup\n\n\tvar heads map[string]string\n\tvar headsErr error\n\twg.Add(1)\n\tgo func() {\n\t\theads, headsErr = m.load(c, ctl.JobID(), u)\n\t\twg.Done()\n\t}()\n\n\tvar refs map[string]string\n\tvar refsErr error\n\twg.Add(1)\n\tgo func() {\n\t\trefs, refsErr = g.GetRefs(c, cfg.Refs)\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n\n\tif headsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch heads - %s\", headsErr)\n\t\treturn fmt.Errorf(\"failed to fetch heads: %v\", headsErr)\n\t}\n\tif refsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch refs - %s\", refsErr)\n\t\treturn fmt.Errorf(\"failed to fetch refs: %v\", refsErr)\n\t}\n\n\ttype result struct {\n\t\tref string\n\t\tlog gerrit.Log\n\t\terr error\n\t}\n\tch := make(chan result)\n\n\tfor ref, head := range refs {\n\t\tif val, ok := heads[ref]; !ok {\n\t\t\twg.Add(1)\n\t\t\tgo func(ref string) {\n\t\t\t\tl, err := g.GetLog(c, ref, fmt.Sprintf(\"%s~\", ref))\n\t\t\t\tch <- result{ref, l, err}\n\t\t\t\twg.Done()\n\t\t\t}(ref)\n\t\t} else if val != head {\n\t\t\twg.Add(1)\n\t\t\tgo func(ref, since string) {\n\t\t\t\tl, err := g.GetLog(c, ref, since)\n\t\t\t\tch <- result{ref, l, err}\n\t\t\t\twg.Done()\n\t\t\t}(ref, val)\n\t\t}\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\n\tvar log gerrit.Log\n\tfor r := range ch {\n\t\tif r.err != nil {\n\t\t\tctl.DebugLog(\"Failed to fetch log - %s\", r.err)\n\t\t\tif gerrit.IsNotFound(r.err) {\n\t\t\t\tdelete(heads, r.ref)\n\t\t\t} else {\n\t\t\t\treturn r.err\n\t\t\t}\n\t\t}\n\t\tif len(r.log) > 0 {\n\t\t\theads[r.ref] = r.log[len(r.log)-1].Commit\n\t\t}\n\t\tlog = append(log, r.log...)\n\t}\n\n\tsort.Sort(log)\n\tfor _, commit := range log {\n\t\t// TODO(phosek): Trigger buildbucket job here.\n\t\tctl.DebugLog(\"Trigger build for commit %s\", commit.Commit)\n\t}\n\tif err := m.save(c, ctl.JobID(), u, heads); err != nil {\n\t\treturn err\n\t}\n\n\tctl.State().Status = task.StatusSucceeded\n\treturn nil\n}", "func (trh *taskRestartHandler) Run(ctx context.Context) gimlet.Responder {\n\terr := resetTask(ctx, evergreen.GetEnvironment().Settings(), trh.taskId, trh.username, trh.FailedOnly)\n\tif err != nil {\n\t\treturn gimlet.MakeJSONErrorResponder(err)\n\t}\n\n\trefreshedTask, err := task.FindOneId(trh.taskId)\n\tif err != nil {\n\t\treturn gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, \"finding updated task '%s'\", trh.taskId))\n\t}\n\tif refreshedTask == nil {\n\t\treturn gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"task '%s' not found\", trh.taskId),\n\t\t})\n\t}\n\n\ttaskModel := &model.APITask{}\n\terr = taskModel.BuildFromService(ctx, refreshedTask, &model.APITaskArgs{IncludeProjectIdentifier: true, IncludeAMI: true})\n\tif err != nil {\n\t\treturn gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, \"converting task '%s' to API model\", trh.taskId))\n\t}\n\treturn gimlet.NewJSONResponse(taskModel)\n}", "func (p *Pool) Start(task interface{}) error {\n\tswitch t := task.(type) {\n\tcase func():\n\t\tvar w funcWrapper = t\n\t\tp.taskQueue <- &w\n\n\tcase Runnable:\n\t\tp.taskQueue <- t\n\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid task type for Pool.Start, Runnable or func() expected, %T given\", t)\n\t}\n\n\treturn nil\n}", "func RequestTask() RequestTaskReply {\n\targs := RequestTaskArgs{}\n\treply := RequestTaskReply{}\n\tcall(\"Master.RequestTask\", &args, &reply)\n\treturn reply\n}", "func (s *Worker) Start() error {\n\tclient, err := worker.InitRPCChannel(*s.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.rc = client\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif client != nil {\n\t\t\t\t// we dont really care about the error here...\n\t\t\t\thostname, _ := os.Hostname()\n\t\t\t\terrStr := fmt.Sprintf(\"A panic occurred. Check logs on %s for more details\", hostname)\n\t\t\t\tclient.ChangeTaskStatus(rpc.ChangeTaskStatusRequest{\n\t\t\t\t\tTaskID: s.taskid,\n\t\t\t\t\tNewStatus: storage.TaskStatusError,\n\t\t\t\t\tError: &errStr,\n\t\t\t\t})\n\t\t\t}\n\t\t\tlog.Error().Str(\"task_id\", s.taskid).Msg(\"A critical error occurred while running task (panic)\")\n\t\t}\n\t}()\n\n\ts.t = NewTask(s.taskid, s.devices, s.cfg, s.rc) //Get the task in order to collect the task duration\n\tresp, err := s.t.c.GetTask(rpc.RequestTaskPayload{\n\t\tTaskID: s.t.taskid,\n\t})\n\n\tif resp.TaskDuration != 0 { //If the task duration is 0 (not set), we don't run the timer\n\t\ttimer := time.NewTimer(time.Second * time.Duration(resp.TaskDuration))\n\t\tgo func() {\n\t\t\t<-timer.C\n\t\t\tlog.Warn().Msg(\"Timer expired, stopping task\")\n\t\t\ts.t.Stop()\n\t\t\ttimer.Stop()\n\t\t}()\n\t}\n\n\tif err := s.t.Start(); err != nil {\n\t\tlog.Error().Err(err).Str(\"task_id\", s.taskid).Msg(\"An error occurred while processing a task\")\n\t\terrptr := err.Error()\n\t\tif rpcerr := client.ChangeTaskStatus(rpc.ChangeTaskStatusRequest{\n\t\t\tTaskID: s.taskid,\n\t\t\tNewStatus: storage.TaskStatusError,\n\t\t\tError: &errptr,\n\t\t}); rpcerr != nil {\n\t\t\tlog.Error().Err(rpcerr).Msg(\"Failed to change tasks status to error\")\n\t\t}\n\t}\n\treturn nil\n}", "func NewKoolTask(message string, service KoolService) *DefaultKoolTask {\n\treturn &DefaultKoolTask{service, message, shell.NewShell()}\n}", "func (client *Client) StartRecordTask(request *StartRecordTaskRequest) (response *StartRecordTaskResponse, err error) {\n\tresponse = CreateStartRecordTaskResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (p SourceProvider) TaskStarted(t *provider.Task) error {\n\tt.Running = true\n\tif !p.Config.Enabled {\n\t\treturn nil\n\t}\n\tif p.Connection.KAPI == nil {\n\t\tif err := p.Connection.Connect(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := p.Connection.WriteTask(t); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Master) RequestTask(args *RequestTaskArgs, reply *RequestTaskReply) error {\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tswitch m.state {\n\tcase Initializing:\n\t\treply.WorkerNextState = Idle\n\tcase MapPhase:\n\t\tfor i, task := range m.mapTasks {\n\t\t\tif task.State == UnScheduled {\n\t\t\t\t//schedule unassigned task\n\t\t\t\ttask.State = InProgress\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\n\t\t\t\tm.mapTasks[i].State = InProgress\n\t\t\t\tm.mapTasks[i].TimeStamp = time.Now()\n\t\t\t\treturn nil\n\t\t\t} else if task.State == InProgress && time.Now().Sub(task.TimeStamp) > 10*time.Second {\n\t\t\t\t//reassign tasks due to timeout\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\t\t\t\t//update TimeStamp\n\t\t\t\tm.mapTasks[i].TimeStamp = time.Now()\n\n\t\t\t\treturn nil\n\t\t\t} else if task.State == Done {\n\t\t\t\t//ignore the task\n\t\t\t\t//TODO: array for task is not efficient, maybe change to map?\n\t\t\t}\n\t\t}\n\t\t//no more mapWork, wait for other tasks\n\t\treply.WorkerNextState = Idle\n\n\tcase ReducePhase:\n\t\tfor i, task := range m.reduceTasks {\n\t\t\tif task.State == UnScheduled {\n\t\t\t\t//schedule unassigned task\n\t\t\t\ttask.State = InProgress\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\n\t\t\t\tm.reduceTasks[i].State = InProgress\n\t\t\t\tm.reduceTasks[i].TimeStamp = time.Now()\n\n\t\t\t\treturn nil\n\t\t\t} else if task.State == InProgress && time.Now().Sub(task.TimeStamp) > 10*time.Second {\n\t\t\t\t//reassign tasks due to timeout\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\t\t\t\t//update TimeStamp\n\t\t\t\tm.reduceTasks[i].TimeStamp = time.Now()\n\t\t\t\treturn nil\n\t\t\t} else if task.State == Done {\n\t\t\t\t//ignore the task\n\t\t\t\t//TODO: array for task is not efficient, maybe change to map?\n\t\t\t}\n\t\t}\n\t\t//no more reduceWork, wait for other tasks\n\t\treply.WorkerNextState = Idle\n\tdefault:\n\t\t//master gonna be teared down, shut down worker\n\t\t//or something weng wrong\n\t\treply.WorkerNextState = NoMoreWork\n\t}\n\n\treturn nil\n}", "func (c *Client) StartBkOpsTask(url string, paras *TaskPathParas,\n\trequest *StartTaskRequest) (*StartTaskResponse, error) {\n\tif c == nil {\n\t\treturn nil, ErrServerNotInit\n\t}\n\n\tvar (\n\t\treqURL = fmt.Sprintf(\"/start_task/%s/%s/\", paras.TaskID, paras.BkBizID)\n\t\trespData = &StartTaskResponse{}\n\t)\n\n\trequest.Scope = string(CmdbBizScope)\n\tuserAuth, err := c.generateGateWayAuth(paras.Operator)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"bksops StartBkOpsTask generateGateWayAuth failed: %v\", err)\n\t}\n\n\t_, _, errs := gorequest.New().\n\t\tTimeout(defaultTimeOut).\n\t\tPost(c.server+reqURL).\n\t\tSet(\"Content-Type\", \"application/json\").\n\t\tSet(\"Accept\", \"application/json\").\n\t\tSet(\"X-Bkapi-Authorization\", userAuth).\n\t\tSetDebug(c.serverDebug).\n\t\tSend(request).\n\t\tEndStruct(&respData)\n\tif len(errs) > 0 {\n\t\tblog.Errorf(\"call api StartBkOpsTask failed: %v\", errs[0])\n\t\treturn nil, errs[0]\n\t}\n\n\tif !respData.Result {\n\t\tblog.Errorf(\"call api StartBkOpsTask failed: %v\", respData.Message)\n\t\treturn nil, fmt.Errorf(respData.Message)\n\t}\n\n\t//successfully request\n\tblog.Infof(\"call api StartBkOpsTask with url(%s) successfully\", reqURL)\n\treturn respData, nil\n}", "func (d *Driver) ExecTask(taskID string, cmd []string, timeout time.Duration) (*drivers.ExecTaskResult, error) {\n\treturn nil, fmt.Errorf(\"Podman driver does not support exec\")\n}", "func (ts *TaskService) Start(ctx context.Context, req *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"start\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.Start(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"start failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).WithField(\"pid\", resp.Pid).Debug(\"start succeeded\")\n\treturn resp, nil\n}", "func (c *ECS) StartTaskRequest(input *StartTaskInput) (req *aws.Request, output *StartTaskOutput) {\n\toprw.Lock()\n\tdefer oprw.Unlock()\n\n\tif opStartTask == nil {\n\t\topStartTask = &aws.Operation{\n\t\t\tName: \"StartTask\",\n\t\t\tHTTPMethod: \"POST\",\n\t\t\tHTTPPath: \"/\",\n\t\t}\n\t}\n\n\treq = c.newRequest(opStartTask, input, output)\n\toutput = &StartTaskOutput{}\n\treq.Data = output\n\treturn\n}", "func (s *Supervisor) AddTask(name string, startStopper StartStopper, policyOptions ...PolicyOption) {\n\tkey := fmt.Sprintf(\"%s-%s\", \"task\", name)\n\ts.mux.Lock()\n\tdefer s.mux.Unlock()\n\n\tif _, exists := s.processes[key]; exists {\n\t\ts.logger(Error, loggerData{\"name\": name}, \"task already exists\")\n\t\treturn\n\t}\n\n\tt := &task{\n\t\tStartStopper: startStopper,\n\t\tname: name,\n\t\tlogger: s.logger,\n\t}\n\n\tp := Policy{\n\t\tRestart: s.policy.Restart,\n\t}\n\tp.Reconfigure(policyOptions...)\n\n\tt.restartPolicy = p.Restart\n\n\ts.processes[key] = t\n}", "func (taskBolt *TaskBolt) RunTask(ctx context.Context, task *ga4gh_task_exec.Task) (*ga4gh_task_exec.JobID, error) {\n\tjobID := GenJobID()\n\tlog := log.WithFields(\"jobID\", jobID)\n\n\tlog.Debug(\"RunTask called\", \"task\", task)\n\n\tif len(task.Docker) == 0 {\n\t\tlog.Error(\"No docker commands found\")\n\t\treturn nil, fmt.Errorf(\"No docker commands found\")\n\t}\n\n\t// Check inputs of the task\n\tfor _, input := range task.GetInputs() {\n\t\tdiskFound := false\n\t\tfor _, res := range task.Resources.Volumes {\n\t\t\tif strings.HasPrefix(input.Path, res.MountPoint) {\n\t\t\t\tdiskFound = true\n\t\t\t}\n\t\t}\n\t\tif !diskFound {\n\t\t\tlog.Error(\"RunTask: required volume not found in resources\",\n\t\t\t\t\"path\", input.Path)\n\t\t\treturn nil, fmt.Errorf(\"Required volume '%s' not found in resources\", input.Path)\n\t\t}\n\t\t//Fixing blank value to File by default... Is this too much hand holding?\n\t\tif input.Class == \"\" {\n\t\t\tinput.Class = \"File\"\n\t\t}\n\t}\n\n\tfor _, output := range task.GetOutputs() {\n\t\tif output.Class == \"\" {\n\t\t\toutput.Class = \"File\"\n\t\t}\n\t}\n\n\tjwt := getJWT(ctx)\n\tlog.Debug(\"JWT\", \"token\", jwt)\n\n\tch := make(chan *ga4gh_task_exec.JobID, 1)\n\terr := taskBolt.db.Update(func(tx *bolt.Tx) error {\n\t\tidBytes := []byte(jobID)\n\n\t\ttaskopB := tx.Bucket(TaskBucket)\n\t\tv, err := proto.Marshal(task)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttaskopB.Put(idBytes, v)\n\n\t\ttx.Bucket(JobState).Put(idBytes, []byte(ga4gh_task_exec.State_Queued.String()))\n\n\t\ttaskopA := tx.Bucket(TaskAuthBucket)\n\t\ttaskopA.Put(idBytes, []byte(jwt))\n\n\t\tqueueB := tx.Bucket(JobsQueued)\n\t\tqueueB.Put(idBytes, []byte{})\n\t\tch <- &ga4gh_task_exec.JobID{Value: jobID}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Error(\"Error processing task\", err)\n\t\treturn nil, err\n\t}\n\ta := <-ch\n\treturn a, err\n}", "func (c *ContainerController) LaunchContainer(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tcontid := p.ByName(\"id\")\n\n\tcontainer, err := database.GetContainer(contid)\n\n\tif err != nil {\n\t\tc.JSON(rw, http.StatusNotFound, \"Container doesn't exist\")\n\t\treturn\n\t}\n\n\t//this is where we would tell the server to launch the container\n\t//we would want to flag the container as 'launching'\n\t//and check whether it's launching before attempting another launch\n\t//\n\t//\n\n\t//Alright it's flagged as launching\n\t//now let's tell it to launch...\n\t//wait, reverse that order\n\n\twatcher.TaskHandler.AddJob(watcher.Launch,\n\t\tcontainer.ApplicationID,\n\t\tcontainer.Id,\n\t\tcontainer.Name,\n\t\t\"\")\n\n\t//this is where we would tell the server to launch the container\n\tcontainer.Status = \"LAUNCHING\"\n\n\tdatabase.UpdateContainer(container)\n\n\t//I think that's all we need to launch the container\n\t//let's put that into our UI. and then get the backend cooperating\n\n\t//Actually... I think I'll add the launch button to the UI later.\n\tc.JSON(rw, http.StatusOK, container)\n\n}", "func (e *ECS) RunTask(req *RunTaskReq) (*RunTaskResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"RunTask\")\n\tif req.Count > 0 {\n\t\tparams[\"count\"] = strconv.Itoa(int(req.Count))\n\t}\n\tif req.Cluster != \"\" {\n\t\tparams[\"cluster\"] = req.Cluster\n\t}\n\tif req.TaskDefinition != \"\" {\n\t\tparams[\"taskDefinition\"] = req.TaskDefinition\n\t}\n\n\tfor i, co := range req.Overrides.ContainerOverrides {\n\t\tkey := fmt.Sprintf(\"overrides.containerOverrides.member.%d\", i+1)\n\t\tparams[fmt.Sprintf(\"%s.name\", key)] = co.Name\n\t\tfor k, cmd := range co.Command {\n\t\t\tparams[fmt.Sprintf(\"%s.command.member.%d\", key, k+1)] = cmd\n\t\t}\n\t\tfor k, env := range co.Environment {\n\t\t\tparams[fmt.Sprintf(\"%s.environment.member.%d.name\", key, k+1)] = env.Name\n\t\t\tparams[fmt.Sprintf(\"%s.environment.member.%d.value\", key, k+1)] = env.Value\n\t\t}\n\t}\n\n\tresp := new(RunTaskResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (jm *JobManager) RunTask(task Task) error {\n\tjm.Lock()\n\tdefer jm.Unlock()\n\n\treturn jm.runTaskUnsafe(task)\n}", "func Run(task structs.Task) {\n\tmsg := structs.Response{}\n\tmsg.TaskID = task.TaskID\n\tparts := strings.SplitAfterN(task.Params, \" \", 2)\n\tparts[0] = strings.TrimSpace(parts[0])\n\tparts[1] = strings.TrimSpace(parts[1])\n\tif len(parts) != 2 {\n\t\tmsg.UserOutput = \"Not enough parameters\"\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\terr := os.Setenv(parts[0], parts[1])\n\tif err != nil {\n\t\tmsg.UserOutput = err.Error()\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\tmsg.Completed = true\n\tmsg.UserOutput = fmt.Sprintf(\"Set %s=%s\", parts[0], parts[1])\n\tresp, _ := json.Marshal(msg)\n\tmu.Lock()\n\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\tmu.Unlock()\n\treturn\n}", "func buildPodMapTask(task *idlCore.TaskTemplate, metadata core.TaskExecutionMetadata) (v1.Pod, error) {\n\tif task.GetK8SPod() == nil || task.GetK8SPod().PodSpec == nil {\n\t\treturn v1.Pod{}, errors.Errorf(errors.BadTaskSpecification, \"Missing pod spec for task\")\n\t}\n\tvar podSpec = &v1.PodSpec{}\n\terr := utils.UnmarshalStructToObj(task.GetK8SPod().PodSpec, &podSpec)\n\tif err != nil {\n\t\treturn v1.Pod{}, errors.Errorf(errors.BadTaskSpecification,\n\t\t\t\"Unable to unmarshal task custom [%v], Err: [%v]\", task.GetCustom(), err.Error())\n\t}\n\tprimaryContainerName, ok := task.GetConfig()[primaryContainerKey]\n\tif !ok {\n\t\treturn v1.Pod{}, errors.Errorf(errors.BadTaskSpecification,\n\t\t\t\"invalid TaskSpecification, config missing [%s] key in [%v]\", primaryContainerKey, task.GetConfig())\n\t}\n\n\tvar pod = v1.Pod{\n\t\tSpec: *podSpec,\n\t}\n\tif task.GetK8SPod().Metadata != nil {\n\t\tif task.GetK8SPod().Metadata.Annotations != nil {\n\t\t\tpod.Annotations = task.GetK8SPod().Metadata.Annotations\n\t\t}\n\t\tif task.GetK8SPod().Metadata.Labels != nil {\n\t\t\tpod.Labels = task.GetK8SPod().Metadata.Labels\n\t\t}\n\t}\n\tif len(pod.Annotations) == 0 {\n\t\tpod.Annotations = make(map[string]string)\n\t}\n\tpod.Annotations[primaryContainerKey] = primaryContainerName\n\n\t// Set the restart policy to *not* inherit from the default so that a completed pod doesn't get caught in a\n\t// CrashLoopBackoff after the initial job completion.\n\tpod.Spec.RestartPolicy = v1.RestartPolicyNever\n\tflytek8s.GetServiceAccountNameFromTaskExecutionMetadata(metadata)\n\treturn pod, nil\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 (c *ECS) RunTaskRequest(input *RunTaskInput) (req *aws.Request, output *RunTaskOutput) {\n\toprw.Lock()\n\tdefer oprw.Unlock()\n\n\tif opRunTask == nil {\n\t\topRunTask = &aws.Operation{\n\t\t\tName: \"RunTask\",\n\t\t\tHTTPMethod: \"POST\",\n\t\t\tHTTPPath: \"/\",\n\t\t}\n\t}\n\n\treq = c.newRequest(opRunTask, input, output)\n\toutput = &RunTaskOutput{}\n\treq.Data = output\n\treturn\n}", "func (self *TaskBolt) RunTask(ctx context.Context, task *ga4gh_task_exec.Task) (*ga4gh_task_exec.JobId, error) {\n\tlog.Println(\"Recieving Task for Queue\", task)\n\n\ttaskopId, _ := uuid.NewV4()\n\n\ttask.TaskId = taskopId.String()\n\tif len(task.Docker) == 0 {\n\t\treturn nil, fmt.Errorf(\"No docker commands found\")\n\t}\n\n\t// Check inputs of the task\n\tfor _, input := range task.GetInputs() {\n\t\tdisk_found := false\n\t\tfor _, res := range task.Resources.Volumes {\n\t\t\tif strings.HasPrefix(input.Path, res.MountPoint) {\n\t\t\t\tdisk_found = true\n\t\t\t}\n\t\t}\n\t\tif !disk_found {\n\t\t\treturn nil, fmt.Errorf(\"Required volume '%s' not found in resources\", input.Path)\n\t\t}\n\t}\n\n\tch := make(chan *ga4gh_task_exec.JobId, 1)\n\terr := self.db.Update(func(tx *bolt.Tx) error {\n\n\t\ttaskop_b := tx.Bucket(TASK_BUCKET)\n\t\tv, _ := proto.Marshal(task)\n\t\ttaskop_b.Put([]byte(taskopId.String()), v)\n\n\t\tqueue_b := tx.Bucket(JOBS_QUEUED)\n\t\tqueue_b.Put([]byte(taskopId.String()), []byte(ga4gh_task_exec.State_Queued.String()))\n\t\tch <- &ga4gh_task_exec.JobId{Value: taskopId.String()}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := <-ch\n\treturn a, err\n}", "func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode task state from handle: %v\", err)\n\t}\n\td.logger.Debug(\"Checking for recoverable task\", \"task\", handle.Config.Name, \"taskid\", handle.Config.ID, \"container\", taskState.ContainerID)\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, taskState.ContainerID)\n\tif err != nil {\n\t\td.logger.Warn(\"Recovery lookup failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: taskState.ContainerID,\n\t\tdriver: d,\n\t\ttaskConfig: taskState.TaskConfig,\n\t\tprocState: drivers.TaskStateUnknown,\n\t\tstartedAt: taskState.StartedAt,\n\t\texitResult: &drivers.ExitResult{},\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tif inspectData.State.Running {\n\t\td.logger.Info(\"Recovered a still running container\", \"container\", inspectData.State.Pid)\n\t\th.procState = drivers.TaskStateRunning\n\t} else if inspectData.State.Status == \"exited\" {\n\t\t// are we allowed to restart a stopped container?\n\t\tif d.config.RecoverStopped {\n\t\t\td.logger.Debug(\"Found a stopped container, try to start it\", \"container\", inspectData.State.Pid)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery restart failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\t\t} else {\n\t\t\t\td.logger.Info(\"Restarted a container during recovery\", \"container\", inspectData.ID)\n\t\t\t\th.procState = drivers.TaskStateRunning\n\t\t\t}\n\t\t} else {\n\t\t\t// no, let's cleanup here to prepare for a StartTask()\n\t\t\td.logger.Debug(\"Found a stopped container, removing it\", \"container\", inspectData.ID)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery cleanup failed\", \"task\", handle.Config.ID, \"container\", inspectData.ID)\n\t\t\t}\n\t\t\th.procState = drivers.TaskStateExited\n\t\t}\n\t} else {\n\t\td.logger.Warn(\"Recovery restart failed, unknown container state\", \"state\", inspectData.State.Status, \"container\", taskState.ContainerID)\n\t\th.procState = drivers.TaskStateUnknown\n\t}\n\n\td.tasks.Set(taskState.TaskConfig.ID, h)\n\n\tgo h.runContainerMonitor()\n\td.logger.Debug(\"Recovered container handle\", \"container\", taskState.ContainerID)\n\n\treturn nil\n}", "func (s *Scheduler) taskFitNode(ctx context.Context, t *api.Task, nodeID string) *api.Task {\n\tnodeInfo, err := s.nodeSet.nodeInfo(nodeID)\n\tif err != nil {\n\t\t// node does not exist in set (it may have been deleted)\n\t\treturn nil\n\t}\n\tnewT := *t\n\ts.pipeline.SetTask(t)\n\tif !s.pipeline.Process(&nodeInfo) {\n\t\t// this node cannot accommodate this task\n\t\tnewT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())\n\t\tnewT.Status.Err = s.pipeline.Explain()\n\t\ts.allTasks[t.ID] = &newT\n\n\t\treturn &newT\n\t}\n\n\t// before doing all of the updating logic, get the volume attachments\n\t// for the task on this node. this should always succeed, because we\n\t// should already have filtered nodes based on volume availability, but\n\t// just in case we missed something and it doesn't, we have an error\n\t// case.\n\tattachments, err := s.volumes.chooseTaskVolumes(t, &nodeInfo)\n\tif err != nil {\n\t\tnewT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())\n\t\tnewT.Status.Err = err.Error()\n\t\ts.allTasks[t.ID] = &newT\n\n\t\treturn &newT\n\t}\n\n\tnewT.Volumes = attachments\n\n\tnewT.Status = api.TaskStatus{\n\t\tState: api.TaskStateAssigned,\n\t\tTimestamp: ptypes.MustTimestampProto(time.Now()),\n\t\tMessage: \"scheduler confirmed task can run on preassigned node\",\n\t}\n\ts.allTasks[t.ID] = &newT\n\n\tif nodeInfo.addTask(&newT) {\n\t\ts.nodeSet.updateNode(nodeInfo)\n\t}\n\treturn &newT\n}", "func NewTask(service *Service, request *userdata.ProcessRequest, userpastelid string) *Task {\n\treturn &Task{\n\t\tTask: task.New(StatusTaskStarted),\n\t\tService: service,\n\t\trequest: request,\n\t\tuserpastelid: userpastelid,\n\t\tresultChan: make(chan *userdata.ProcessResult),\n\t\tresultChanGet: make(chan *userdata.ProcessRequest),\n\t}\n}", "func (item *CatalogItem) LaunchSync() (*Task, error) {\n\tutil.Logger.Printf(\"[TRACE] LaunchSync '%s' \\n\", item.CatalogItem.Name)\n\terr := WaitResource(func() (*types.TasksInProgress, error) {\n\t\tif item.CatalogItem.Tasks == nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr := item.Refresh()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn item.CatalogItem.Tasks, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn elementLaunchSync(item.client, item.CatalogItem.HREF, \"catalog item\")\n}", "func runTask(ctx context.Context, cfg *taskConfig, f TaskFunc, args ...interface{}) *Task {\n\ttask := newTask(ctx, cfg, f, args...)\n\ttask.Start()\n\treturn task\n}", "func NewTask(task string, context *Context, loadedTasks map[string]Task) {\n\tdir, t, tasks := FetchTask(task, context, loadedTasks)\n\n\t// register plugins ...\n\tplugin(t, context, tasks)\n\tevent.Trigger(\"dir\", &dir)\n\tevent.Trigger(\"t\", &t)\n\tevent.Trigger(\"tasks\", &tasks)\n\n\t// Skip the task, if we need to skip\n\tif t.Skip {\n\t\treturn\n\t}\n\n\t// innocent until proven guilty\n\tcontext.Ok = true\n\n\t// set our taskname\n\t_, context.TaskName = TaskParser(task, \"alfred:list\")\n\n\t// interactive mode?\n\tcontext.Interactive = t.Interactive\n\n\tif !context.hasBeenInited {\n\t\tcontext.hasBeenInited = true\n\t\tNewTask(MagicTaskURL(task)+\"__init\", context, tasks)\n\t}\n\n\tcomponents := []Component{\n\t\tComponent{\"log\", log},\n\t\tComponent{\"summary\", summary},\n\t\tComponent{\"prompt\", prompt},\n\t\tComponent{\"register\", register},\n\t\tComponent{\"defaults\", defaults},\n\t\tComponent{\"stdin\", stdin},\n\t\tComponent{\"config\", configC},\n\t\tComponent{\"env\", env},\n\t\tComponent{\"check\", check},\n\t\tComponent{\"watch\", watch},\n\t\tComponent{\"serve\", serve},\n\t\tComponent{\"setup\", setup},\n\t\tComponent{\"include\", include},\n\t\tComponent{\"multitask\", multitask},\n\t\tComponent{\"tasks\", tasksC},\n\t\tComponent{\"for\", forC},\n\t\tComponent{\"command\", commandC},\n\t\tComponent{\"commands\", commands},\n\t\tComponent{\"httptasks\", httptasks},\n\t\tComponent{\"result\", result},\n\t\tComponent{\"ok\", ok},\n\t\tComponent{\"fail\", fail},\n\t\tComponent{\"wait\", wait},\n\t\tComponent{\"every\", every},\n\t}\n\n\t// cycle through our components ...\n\tevent.Trigger(\"task.started\", t, context, tasks)\n\tfor _, component := range components {\n\t\tcontext.Component = component.Name\n\t\tevent.Trigger(\"before.\"+component.Name, context)\n\t\tcomponent.F(t, context, tasks)\n\t\tevent.Trigger(\"after.\"+component.Name, context)\n\n\t\tif context.Skip != \"\" {\n\t\t\toutOK(context.Skip, \"skipped\", context)\n\t\t\tevent.Trigger(\"task.skipped\", context)\n\t\t\treturn\n\t\t}\n\t}\n\tevent.Trigger(\"task.completed\", context)\n}", "func (s *Stopper) RunTask(ctx context.Context, taskName string, f func(context.Context)) error {\n\tif !s.runPrelude() {\n\t\treturn ErrUnavailable\n\t}\n\n\t// Call f.\n\tdefer s.Recover(ctx)\n\tdefer s.runPostlude()\n\n\tf(ctx)\n\treturn nil\n}", "func TrackTaskStart(payload string, duration int64) {\n\tpersist.SetValue(taskPayloadKey, payload)\n\tpersist.SetValue(taskEndTimeKey, time.Now().Unix()+duration)\n}", "func (c *BasicECSClient) RunTask(ctx context.Context, in *ecs.RunTaskInput) (*ecs.RunTaskOutput, error) {\n\tif err := c.setup(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"setting up client\")\n\t}\n\n\tvar out *ecs.RunTaskOutput\n\tvar err error\n\tmsg := awsutil.MakeAPILogMessage(\"RunTask\", in)\n\tif err := utility.Retry(ctx,\n\t\tfunc() (bool, error) {\n\t\t\tout, err = c.ecs.RunTaskWithContext(ctx, in)\n\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\tgrip.Debug(message.WrapError(awsErr, msg))\n\t\t\t\tif c.isNonRetryableErrorCode(awsErr.Code()) {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, err\n\t\t}, *c.opts.RetryOpts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func Launch(addr, localDir, filename string,\n\targs []string, logDir string, retry int) error {\n\n\tfields := strings.Split(addr, \":\")\n\tif len(fields) != 2 || len(fields[0]) <= 0 || len(fields[1]) <= 0 {\n\t\treturn fmt.Errorf(\"Launch addr %s not in form of host:port\")\n\t}\n\n\tc, e := connect(fields[0])\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer c.Close()\n\n\te = c.Call(\"Prism.Launch\",\n\t\t&Cmd{addr, localDir, filename, args, logDir, retry}, nil)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Prism.Launch failed: %v\", e)\n\t}\n\treturn nil\n}", "func (d *Driver) SignalTask(taskID string, signal string) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\treturn d.podman.ContainerKill(d.ctx, handle.containerID, signal)\n}", "func RegisterTask(t Task) {\n\t// check if valid\n\tif !taskSlugRegex.MatchString(t.Slug) {\n\t\tpanic(fmt.Sprintf(\"Task slug for '%v' with '%v' not valid.\", t.Name, t.Slug))\n\t}\n\t// check if enabled\n\tif !utils.CONFIG.IsEnabled(t.Slug) {\n\t\tlog.Debug(\"Task '%v' disabled.\", t.Slug)\n\t\treturn\n\t}\n\t// overwrite default interval with custom from config\n\tt.Interval = utils.CONFIG.GetInterval(t.Slug, t.Interval)\n\t// init private variables of task\n\tt.Init()\n\t// append to registered tasks\n\tregisteredTasks = append(registeredTasks, t)\n\t// register in scheduler\n\tclockwerkInstance.Every(t.Interval).Do(t)\n\t// debug message\n\tlog.Debug(\"Task '%v' enabled. Every %vseconds.\", t.Slug, t.Interval.Seconds())\n}", "func (c *Client) CreateTask(tr TaskRequest) (task Task, err error) {\n\tbodyReader, err := createReader(tr)\n\tif err != nil {\n\t\treturn task, err\n\t}\n\n\trequest := fmt.Sprintf(\"/v3/apps/%s/tasks\", tr.DropletGUID)\n\treq := c.NewRequestWithBody(\"POST\", request, bodyReader)\n\n\tresp, err := c.DoRequest(req)\n\tif err != nil {\n\t\treturn task, errors.Wrap(err, \"Error creating task\")\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn task, errors.Wrap(err, \"Error reading task after creation\")\n\t}\n\n\terr = json.Unmarshal(body, &task)\n\tif err != nil {\n\t\treturn task, errors.Wrap(err, \"Error unmarshaling task\")\n\t}\n\treturn task, err\n}", "func (s *Stopper) RunTask(ctx context.Context, taskName string, f func(context.Context)) error {\n\tif !s.runPrelude(taskName) {\n\t\treturn errUnavailable\n\t}\n\n\t// Call f.\n\tdefer s.Recover(ctx)\n\tdefer s.runPostlude(taskName)\n\n\tf(ctx)\n\treturn nil\n}", "func (k *kubeScheduler) Schedule(pod api.Pod, unused algorithm.MinionLister) (string, error) {\n\tlog.Infof(\"Try to schedule pod %v\\n\", pod.Name)\n\tctx := api.WithNamespace(api.NewDefaultContext(), pod.Namespace)\n\n\t// default upstream scheduler passes pod.Name as binding.PodID\n\tpodKey, err := makePodKey(ctx, pod.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tk.api.Lock()\n\tdefer k.api.Unlock()\n\n\tif taskID, ok := k.api.taskForPod(podKey); !ok {\n\t\t// There's a bit of a potential race here, a pod could have been yielded() but\n\t\t// and then before we get *here* it could be deleted. We use meta to index the pod\n\t\t// in the store since that's what k8s client/cache/reflector does.\n\t\tmeta, err := meta.Accessor(&pod)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"aborting Schedule, unable to understand pod object %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\tif deleted := k.podStore.Poll(meta.Name(), queue.DELETE_EVENT); deleted {\n\t\t\t// avoid scheduling a pod that's been deleted between yieldPod() and Schedule()\n\t\t\tlog.Infof(\"aborting Schedule, pod has been deleted %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\treturn k.doSchedule(k.api.registerPodTask(k.api.createPodTask(ctx, &pod)))\n\t} else {\n\t\tswitch task, state := k.api.getTask(taskID); state {\n\t\tcase statePending:\n\t\t\tif task.launched {\n\t\t\t\treturn \"\", fmt.Errorf(\"task %s has already been launched, aborting schedule\", taskID)\n\t\t\t} else {\n\t\t\t\treturn k.doSchedule(task, nil)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"task %s is not pending, nothing to schedule\", taskID)\n\t\t}\n\t}\n}", "func (c *Client) StartImportTask(ctx context.Context, params *StartImportTaskInput, optFns ...func(*Options)) (*StartImportTaskOutput, error) {\n\tif params == nil {\n\t\tparams = &StartImportTaskInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"StartImportTask\", params, optFns, addOperationStartImportTaskMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*StartImportTaskOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func LsTask(c *cli.Context) (*gomarathon.Response, error) {\n\tm, _ := MarathonClient(c.GlobalString(\"host\"))\n\n\tvar resp *gomarathon.Response\n\tvar err error\n\n\t//if an arg is supplied, just look for tasks for that app\n\tif len(c.Args()) > 0 {\n\t\tresp, err = m.GetAppTasks(c.Args().First())\n\t} else {\n\t\tresp, err = m.ListTasks()\n\t}\n\n\tif err != nil {\n\t\tlog.Error(\"Error fetching tasks: \", err)\n\t\treturn nil, err\n\t}\n\treturn resp, err\n}", "func Launch(config *Config, tasks *map[string]interface{}) error {\n\tgores := NewGores(config)\n\tif gores == nil {\n\t\treturn errors.New(\"Gores launch failed: Gores is nil\")\n\t}\n\n\tinSlice := make([]interface{}, len(config.Queues))\n\tfor i, q := range config.Queues {\n\t\tinSlice[i] = q\n\t}\n\tqueuesSet := mapset.NewSetFromSlice(inSlice)\n\n\tdispatcher := NewDispatcher(gores, config, queuesSet)\n\tif dispatcher == nil {\n\t\treturn errors.New(\"Gores launch failed: Dispatcher is nil\")\n\t}\n\n\terr := dispatcher.Start(tasks)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Gores launch failed: %s\", err)\n\t}\n\n\treturn nil\n}", "func bind(client kubernetes.Interface, p corev1.Pod, NodeName string, discoverTime time.Duration, schedTime time.Time) error{\r\n\r\n if p.Annotations != nil {\r\n p.Annotations[\"epsilon.discover.time\"]=discoverTime.String()\r\n p.Annotations[\"epsilon.scheduling.time\"]=time.Since(schedTime).String()\r\n }else{\r\n p.Annotations=map[string]string{\r\n \"epsilon.discover.time\": discoverTime.String(),\r\n \"epsilon.scheduling.time\": time.Since(schedTime).String(),\r\n }\r\n }\r\n\r\n log.Infof(\"Attempting to bind %v/%v to %v\", p.Namespace, p.Name, NodeName)\r\n\tbinding := &corev1.Binding{\r\n\t\tObjectMeta: metav1.ObjectMeta{\r\n Namespace: p.Namespace,\r\n Name: p.Name,\r\n UID: p.UID,\r\n Annotations: p.Annotations,\r\n },\r\n\t\tTarget: corev1.ObjectReference{Kind: \"Node\", Name: NodeName},\r\n\t}\r\n\r\n\terr := client.CoreV1().Pods(binding.Namespace).Bind(context.TODO(), binding, metav1.CreateOptions{})\r\n\tif err != nil {\r\n //key, _ := cache.MetaNamespaceKeyFunc(p)\r\n\r\n\r\n // Resend pod for reschedule\r\n\r\n\t\treturn errors.New(err.Error())\r\n\t}\r\n\treturn nil\r\n}", "func (p *Pool) Schedule(ctx context.Context, task Task) error {\n\tif err := p.isShutdown(); err != nil {\n\t\treturn err\n\t}\n\n\tp.wg.Add(1)\n\tt := &taskWrapper{task, ctx}\n\tp.queue <- t\n\treturn nil\n}", "func (context Context) CreateTask(task Task) (result Task, err error) {\n\n\t// Validate that the job exists and is running.\n\tvar job Job\n\tjob, err = context.GetJobByID(task.Job)\n\tif err != nil && err != ErrNotFound {\n\t\terr = errors.Wrap(err, \"error while trying to access the referenced job\")\n\t\treturn\n\t} else if err == ErrNotFound || job.Status != JobRunning {\n\t\terr = errors.Wrapf(ErrBadInput,\n\t\t\t\"the referenced objective \\\"%s\\\" does not exist or is running\", task.Job)\n\t}\n\n\t// Validate that the models exist and are active.\n\tvar found bool\n\tfor i := range job.Models {\n\t\tif task.Model == job.Models[i] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif found == false {\n\t\terr = errors.Wrapf(ErrBadInput,\n\t\t\t\"the referenced model \\\"%s\\\" does not appear in the models list of the parent job \\\"%s\\\"\",\n\t\t\ttask.Model, job.ID)\n\t}\n\n\t// Give default values to some fields. Copy some from the job.\n\ttask.ObjectID = bson.NewObjectId()\n\ttask.User = job.User\n\ttask.Dataset = job.Dataset\n\ttask.Objective = job.Objective\n\ttask.AltObjectives = job.AltObjectives\n\ttask.CreationTime = time.Now()\n\ttask.Status = TaskScheduled\n\ttask.Stage = TaskStageBegin\n\ttask.StageTimes = TaskStageIntervals{}\n\ttask.StageDurations = TaskStageDurations{}\n\ttask.RunningDuration = 0\n\ttask.Quality = 0.0\n\ttask.AltQualities = make([]float64, len(task.AltObjectives))\n\n\t// Get next ID.\n\tc := context.Session.DB(context.DBName).C(\"tasks\")\n\tquery := bson.M{\"job\": bson.M{\"$eq\": task.Job}}\n\tvar resultSize int\n\tresultSize, err = c.Find(query).Count()\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"mongo find failed\")\n\t\treturn\n\t}\n\ttask.ID = fmt.Sprintf(\"%s/%010d\", task.Job.Hex(), resultSize+1)\n\n\terr = c.Insert(task)\n\tif err != nil {\n\t\tlastError := err.(*mgo.LastError)\n\t\tif lastError.Code == 11000 {\n\t\t\terr = ErrIdentifierTaken\n\t\t\treturn\n\t\t}\n\t\terr = errors.Wrap(err, \"mongo insert failed\")\n\t\treturn\n\t}\n\n\treturn task, nil\n\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 (r *runtime) Run() error {\n\tip, err := getHostIP()\n\tif err != nil {\n\t\tr.state = server.Failed\n\t\treturn fmt.Errorf(\"cannot get server's ip address, error: %s\", err)\n\t}\n\n\thostName, err := hostName()\n\tif err != nil {\n\t\tr.logger.Error(\"get host name with error\", logger.Error(err))\n\t\thostName = \"unknown\"\n\t}\n\tr.node = &models.StatelessNode{\n\t\tHostIP: ip,\n\t\tHostName: hostName,\n\t\tGRPCPort: r.config.BrokerBase.GRPC.Port,\n\t\tHTTPPort: r.config.BrokerBase.HTTP.Port,\n\t\tOnlineTime: timeutil.Now(),\n\t\tVersion: config.Version,\n\t}\n\n\tr.logger.Info(\"starting broker\", logger.String(\"host\", hostName), logger.String(\"ip\", ip),\n\t\tlogger.Uint16(\"http\", r.node.HTTPPort), logger.Uint16(\"grpc\", r.node.GRPCPort))\n\n\t// start state repository\n\terr = r.startStateRepo()\n\tif err != nil {\n\t\tr.logger.Error(\"failed to startStateRepo\", logger.Error(err))\n\t\tr.state = server.Failed\n\t\treturn err\n\t}\n\tr.globalKeyValues = tag.Tags{\n\t\t{Key: []byte(\"node\"), Value: []byte(r.node.Indicator())},\n\t\t{Key: []byte(\"role\"), Value: []byte(constants.BrokerRole)},\n\t}\n\tr.BaseRuntime = app.NewBaseRuntimeFn(r.ctx, r.config.Monitor, linmetric.BrokerRegistry, r.globalKeyValues)\n\n\ttackClientFct := newTaskClientFactory(r.ctx, r.node, rpc.GetBrokerClientConnFactory())\n\tr.factory = factory{\n\t\ttaskClient: tackClientFct,\n\t\ttaskServer: rpc.NewTaskServerFactory(),\n\t\tconnectionMgr: rpc.NewConnectionManager(tackClientFct),\n\t}\n\n\tr.stateMgr = newStateManager(\n\t\tr.ctx,\n\t\t*r.node,\n\t\tr.factory.connectionMgr,\n\t\tr.factory.taskClient)\n\n\tr.buildServiceDependency()\n\n\t// start tcp server\n\tr.startGRPCServer()\n\n\tdiscoveryFactory := discovery.NewFactory(r.repo)\n\n\tmasterCfg := &coordinator.MasterCfg{\n\t\tCtx: r.ctx,\n\t\tRepo: r.repo,\n\t\tNode: r.node,\n\t\tTTL: int64(r.config.Coordinator.LeaseTTL.Duration().Seconds()),\n\t\tDiscoveryFactory: discoveryFactory,\n\t\tRepoFactory: r.repoFactory,\n\t}\n\tr.master = newMasterController(masterCfg)\n\n\t// register broker node info\n\tr.registry = newRegistry(r.repo, constants.LiveNodesPath, r.config.Coordinator.LeaseTTL.Duration())\n\terr = r.registry.Register(r.node)\n\tif err != nil {\n\t\tr.state = server.Failed\n\t\treturn fmt.Errorf(\"register broker node error:%s\", err)\n\t}\n\n\tvar wait sync.WaitGroup\n\twait.Add(1)\n\tvar errStore atomic.Value\n\tvar stateMachineStarted atomic.Bool\n\n\tr.master.WatchMasterElected(func(_ *models.Master) {\n\t\tif stateMachineStarted.CAS(false, true) {\n\t\t\t// if state machine is not started, after 5 second when master elected, wait master state sync.\n\t\t\ttime.AfterFunc(5*time.Second, func() {\n\t\t\t\tdefer wait.Done()\n\t\t\t\t// finally, start all state machine\n\t\t\t\tr.stateMachineFactory = newStateMachineFactory(r.ctx, discoveryFactory, r.stateMgr)\n\t\t\t\tif err0 := r.stateMachineFactory.Start(); err0 != nil {\n\t\t\t\t\terrStore.Store(err0)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n\n\terr = r.master.Start()\n\tif err != nil {\n\t\tr.state = server.Failed\n\t\treturn fmt.Errorf(\"start master controller error:%s\", err)\n\t}\n\n\tr.logger.Info(\"waiting broker state machine start\")\n\t// waiting broker state machine started\n\twait.Wait()\n\t// check if it has error when start state machine\n\tif errVal := errStore.Load(); errVal != nil {\n\t\tr.state = server.Failed\n\t\treturn fmt.Errorf(\"start state machines error: %v\", errVal)\n\t}\n\tr.logger.Info(\"broker state machine started successfully\")\n\n\t// start http server\n\tr.startHTTPServer()\n\n\tif r.enableSystemMonitor {\n\t\t// start system collector\n\t\tr.SystemCollector()\n\t}\n\t// start stat monitoring\n\tr.NativePusher()\n\n\tr.state = server.Running\n\treturn nil\n}", "func (g *Gossiper) RunTimerTask() {\n\t// currently it runs every 1 min\n\tfor {\n\t\tg.runTask()\n\t\ttime.Sleep(time.Millisecond * time.Duration(g.intervalInMillis))\n\t}\n}", "func (d *dispatcher) ExecuteTask() {\n\tlogutil.BgLogger().Info(\"execute one task\", zap.Int64(\"task ID\", d.task.ID),\n\t\tzap.String(\"state\", d.task.State), zap.Uint64(\"concurrency\", d.task.Concurrency))\n\td.scheduleTask(d.task.ID)\n}", "func (m *Miner) Start(ctx context.Context, request *pb.StartRequest) (*pb.StartReply, error) {\n\tvar d = Description{\n\t\tImage: request.Image,\n\t\tRegistry: request.Registry,\n\t}\n\tlog.G(ctx).Info(\"handle Start request\", zap.Any(\"req\", request))\n\n\tm.setStatus(&pb.TaskStatus{pb.TaskStatus_SPOOLING}, request.Id)\n\n\tlog.G(ctx).Info(\"spooling an image\")\n\terr := m.ovs.Spool(ctx, d)\n\tif err != nil {\n\t\tlog.G(ctx).Error(\"failed to Spool an image\", zap.Error(err))\n\t\tm.setStatus(&pb.TaskStatus{pb.TaskStatus_BROKEN}, request.Id)\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to Spool %v\", err)\n\t}\n\n\tm.setStatus(&pb.TaskStatus{pb.TaskStatus_SPAWNING}, request.Id)\n\tlog.G(ctx).Info(\"spawning an image\")\n\tstatusListener, cinfo, err := m.ovs.Spawn(ctx, d)\n\tif err != nil {\n\t\tlog.G(ctx).Error(\"failed to spawn an image\", zap.Error(err))\n\t\tm.setStatus(&pb.TaskStatus{pb.TaskStatus_BROKEN}, request.Id)\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to Spawn %v\", err)\n\t}\n\t// TODO: clean it\n\tm.mu.Lock()\n\tm.containers[request.Id] = &cinfo\n\tm.mu.Unlock()\n\tgo m.listenForStatus(statusListener, request.Id)\n\n\tvar rpl = pb.StartReply{\n\t\tContainer: cinfo.ID,\n\t\tPorts: make(map[string]*pb.StartReplyPort),\n\t}\n\tfor port, v := range cinfo.Ports {\n\t\tif len(v) > 0 {\n\t\t\treplyport := &pb.StartReplyPort{\n\t\t\t\tIP: m.pubAddress,\n\t\t\t\tPort: v[0].HostPort,\n\t\t\t}\n\t\t\trpl.Ports[string(port)] = replyport\n\t\t}\n\t}\n\treturn &rpl, nil\n}", "func (t *task) patchTask(ctx context.Context, diff jobmgrcommon.RuntimeDiff) error {\n\tif diff == nil {\n\t\treturn yarpcerrors.InvalidArgumentErrorf(\n\t\t\t\"unexpected nil diff\")\n\t}\n\n\tif _, ok := diff[jobmgrcommon.RevisionField]; ok {\n\t\treturn yarpcerrors.InvalidArgumentErrorf(\n\t\t\t\"unexpected Revision field in diff\")\n\t}\n\n\tvar runtimeCopy *pbtask.RuntimeInfo\n\tvar labelsCopy []*peloton.Label\n\n\t// notify listeners after dropping the lock\n\tdefer func() {\n\t\tt.jobFactory.notifyTaskRuntimeChanged(\n\t\t\tt.JobID(),\n\t\t\tt.ID(),\n\t\t\tt.jobType,\n\t\t\truntimeCopy,\n\t\t\tlabelsCopy,\n\t\t)\n\t}()\n\tt.Lock()\n\tdefer t.Unlock()\n\n\t// reload cache if there is none\n\tif t.runtime == nil {\n\t\t// fetch runtime from db if not present in cache\n\t\terr := t.updateRuntimeFromDB(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// make a copy of runtime since patch() would update runtime in place\n\tnewRuntime := *t.runtime\n\tnewRuntimePtr := &newRuntime\n\tif err := patch(newRuntimePtr, diff); err != nil {\n\t\treturn err\n\t}\n\n\t// validate if the patched runtime is valid,\n\t// if not ignore the diff, since the runtime has already been updated by\n\t// other threads and the change in diff is no longer valid\n\tif !t.validateState(newRuntimePtr) {\n\t\treturn nil\n\t}\n\n\tt.updateRevision(newRuntimePtr)\n\n\terr := t.jobFactory.taskStore.UpdateTaskRuntime(\n\t\tctx,\n\t\tt.jobID,\n\t\tt.id,\n\t\tnewRuntimePtr,\n\t\tt.jobType)\n\tif err != nil {\n\t\t// clean the runtime in cache on DB write failure\n\t\tt.cleanTaskCache()\n\t\treturn err\n\t}\n\n\terr = t.updateConfig(ctx, newRuntimePtr.GetConfigVersion())\n\tif err != nil {\n\t\tt.cleanTaskCache()\n\t\treturn err\n\t}\n\tt.logStateTransitionMetrics(newRuntimePtr)\n\n\t// Store the new runtime in cache\n\tt.runtime = newRuntimePtr\n\truntimeCopy = proto.Clone(t.runtime).(*pbtask.RuntimeInfo)\n\tlabelsCopy = t.copyLabelsInCache()\n\treturn nil\n}", "func (server *Server) SendTask(s *TaskSignature) error {\n\tmessage, err := json.Marshal(s)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"JSON Encode Message: %v\", err)\n\t}\n\n\tif err := server.connection.PublishMessage(\n\t\t[]byte(message), s.RoutingKey,\n\t); err != nil {\n\t\treturn fmt.Errorf(\"Publish Message: %v\", err)\n\t}\n\n\treturn nil\n}", "func (s *Session) SendTask(t util.Task) error {\n\t// Checking taskID. re-enqueued task will be skipped\n\tif t.TaskID == \"\" {\n\t\tt.TaskID = uuid.New().String()\n\t\tif t.OriginalTaskID == \"\" {\n\t\t\tt.OriginalTaskID = t.TaskID\n\t\t}\n\n\t\tif err := s.taskRepo.CreateTask(&t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Checking AMQP connection. Task will be logged for no connection. Re-enqueued later.\n\ts.mu.RLock()\n\tif !s.connected {\n\t\ts.lgr.Warn(\"No connection. Task enqueued.\", util.Object{Key: \"TaskID\", Val: t.TaskID})\n\t\treturn ErrNotConnected\n\t}\n\ts.mu.RUnlock()\n\n\tif !t.Priority.Valid() {\n\t\treturn ErrInvalidPriority\n\t}\n\n\tch, err := s.conn.Channel()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ch.Close()\n\n\tif err := ch.Confirm(false); err != nil {\n\t\treturn err\n\t}\n\n\tcloseNotification := ch.NotifyClose(make(chan *amqp.Error, 1))\n\tpublish := ch.NotifyPublish(make(chan amqp.Confirmation, 1))\n\tpublishErr := make(chan error, 1)\n\n\tQueue, err := s.GetQueueName(t.Priority)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\terr := ch.Publish(\n\t\t\ts.cfg.AMQP.Exchange,\n\t\t\tQueue,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tamqp.Publishing{\n\t\t\t\tHeaders: map[string]interface{}{\n\t\t\t\t\t\"TaskName\": t.Name,\n\t\t\t\t\t\"TaskID\": t.TaskID,\n\t\t\t\t},\n\t\t\t\tMessageId: t.TaskID,\n\t\t\t\tDeliveryMode: amqp.Persistent,\n\t\t\t\tBody: t.Payload,\n\t\t\t},\n\t\t)\n\n\t\tif err != nil {\n\t\t\tpublishErr <- err\n\t\t\treturn\n\t\t}\n\n\t\ts.taskRepo.UpdateTaskStatus(context.Background(), t.TaskID, util.StatusQueued)\n\t}()\n\n\tdone := (<-chan time.Time)(make(chan time.Time, 1))\n\tif s.cfg.RequestTimeout != 0 {\n\t\tdone = time.After(s.cfg.RequestTimeout)\n\t}\n\n\tvar errs error\n\n\tselect {\n\tcase errs = <-closeNotification:\n\n\tcase errs = <-publishErr:\n\n\tcase p := <-publish:\n\t\tif !p.Ack {\n\t\t\ts.lgr.Warn(\"Task deliver failed\", util.Object{Key: \"TaskID\", Val: t.TaskID})\n\t\t\terrs = ErrNotPublished\n\t\t\tbreak\n\t\t}\n\t\ts.lgr.Info(\"Task delivered\", util.Object{Key: \"TaskID\", Val: t.TaskID})\n\tcase <-done:\n\t\terrs = ErrRequestTimeout\n\t}\n\n\t// For any kind of error, task will be retried if retry count non zero.\n\t// TODO: retry count only reduce for task processing related error.\n\tif errs != nil {\n\t\tif orgTask, err := s.taskRepo.GetTask(t.OriginalTaskID); err != nil {\n\t\t\ts.lgr.Error(\"failed to get task\", err, util.Object{Key: \"TaskID\", Val: t.OriginalTaskID})\n\t\t} else if orgTask.Retry != 0 {\n\t\t\tgo s.RetryTask(t)\n\t\t}\n\n\t\ts.taskRepo.UpdateTaskStatus(context.Background(), t.TaskID, util.StatusFailed, errs)\n\t}\n\n\treturn errs\n}", "func (conf *Confirmer) StartConfirmerTask(bundleTrytes []Trytes) (chan *ConfirmerUpdate, func(), error) {\n\tconf.runningMutex.Lock()\n\tdefer conf.runningMutex.Unlock()\n\n\tif conf.running {\n\t\treturn nil, nil, fmt.Errorf(\"Confirmer task is already running\")\n\t}\n\n\ttail, err := utils.TailFromBundleTrytes(bundleTrytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tbundleHash := tail.Bundle\n\tnowis := time.Now()\n\n\t// no need to lock state because no routine is running\n\tconf.lastBundleTrytes = bundleTrytes\n\tconf.bundleHash = bundleHash\n\tconf.nextForceReattachTime = nowis.Add(time.Duration(conf.ForceReattachAfterMin) * time.Minute)\n\tconf.nextPromoTime = nowis\n\tconf.nextTailHashToPromote = tail.Hash\n\tconf.isNotPromotable = false\n\tconf.chanUpdate = make(chan *ConfirmerUpdate, 1) // not to block each time\n\tconf.numAttach = 0\n\tconf.numPromote = 0\n\tconf.totalDurationGTTAMsec = 0\n\tconf.totalDurationATTMsec = 0\n\tif conf.AEC == nil {\n\t\tconf.AEC = &utils.DummyAEC{}\n\t}\n\tif conf.SlowDownThreshold == 0 {\n\t\tconf.SlowDownThreshold = defaultSlowDownThresholdNumGoroutine\n\t}\n\n\t// starting 3 routines\n\tcancelPromoCheck := conf.goPromotabilityCheck()\n\tcancelPromo := conf.goPromote()\n\tcancelReattach := conf.goReattach()\n\n\t// confirmation monitor starts yet another routine\n\tconf.confMon.OnConfirmation(bundleHash, func(nowis time.Time) {\n\t\tconf.postConfirmerUpdate(UPD_CONFIRM, \"\", nil)\n\t})\n\n\tconf.running = true\n\n\treturn conf.chanUpdate, func() {\n\t\tconf.stopConfirmerTask(cancelPromoCheck, cancelPromo, cancelReattach)\n\t\tconf.confMon.CancelConfirmationPolling(bundleHash)\n\t}, nil\n}", "func (p k8sPodResources) Start(\n\tctx *actor.System, logCtx logger.Context, spec tasks.TaskSpec, rri sproto.ResourcesRuntimeInfo,\n) error {\n\tp.setPosition(&spec)\n\tspec.ContainerID = string(p.containerID)\n\tspec.ResourcesID = string(p.containerID)\n\tspec.AllocationID = string(p.req.AllocationID)\n\tspec.AllocationSessionToken = rri.Token\n\tspec.TaskID = string(p.req.TaskID)\n\tspec.UseHostMode = rri.IsMultiAgent\n\tspec.ResourcesConfig.SetPriority(p.group.Priority)\n\tif spec.LoggingFields == nil {\n\t\tspec.LoggingFields = map[string]string{}\n\t}\n\tspec.LoggingFields[\"allocation_id\"] = spec.AllocationID\n\tspec.LoggingFields[\"task_id\"] = spec.TaskID\n\tspec.ExtraEnvVars[sproto.ResourcesTypeEnvVar] = string(sproto.ResourcesTypeK8sPod)\n\tspec.ExtraEnvVars[resourcePoolEnvVar] = p.req.ResourcePool\n\treturn ctx.Ask(p.podsActor, StartTaskPod{\n\t\tAllocationID: p.req.AllocationID,\n\t\tSpec: spec,\n\t\tSlots: p.slots,\n\t\tRank: rri.AgentRank,\n\t\tNamespace: p.namespace,\n\t\tLogContext: logCtx,\n\t}).Error()\n}", "func (op *AddonOperator) logTaskStart(logEntry *log.Entry, tsk sh_task.Task) {\n\t// Prevent excess messages for highly frequent tasks.\n\tif tsk.GetType() == task.GlobalHookWaitKubernetesSynchronization {\n\t\treturn\n\t}\n\tif tsk.GetType() == task.ModuleRun {\n\t\thm := task.HookMetadataAccessor(tsk)\n\t\tmodule := op.ModuleManager.GetModule(hm.ModuleName)\n\t\tif module.State.Phase == module_manager.WaitForSynchronization {\n\t\t\treturn\n\t\t}\n\t}\n\n\tlogger := logEntry.\n\t\tWithField(\"task.flow\", \"start\").\n\t\tWithFields(utils.LabelsToLogFields(tsk.GetLogLabels()))\n\tif triggeredBy, ok := tsk.GetProp(\"triggered-by\").(log.Fields); ok {\n\t\tlogger = logger.WithFields(triggeredBy)\n\t}\n\n\tlogger.Infof(taskDescriptionForTaskFlowLog(tsk, \"start\", op.taskPhase(tsk), \"\"))\n}", "func (k *KubernetesScheduler) Schedule(pod api.Pod, unused algorithm.MinionLister) (string, error) {\n\tlog.Infof(\"Try to schedule pod %v\\n\", pod.ID)\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tif taskID, ok := k.podToTask[pod.ID]; !ok {\n\t\treturn \"\", fmt.Errorf(\"Pod %s cannot be resolved to a task\", pod.ID)\n\t} else {\n\t\tif task, found := k.pendingTasks[taskID]; !found {\n\t\t\treturn \"\", fmt.Errorf(\"Task %s is not pending, nothing to schedule\", taskID)\n\t\t} else {\n\t\t\treturn k.doSchedule(task)\n\t\t}\n\t}\n}", "func (jm *JobManager) TaskBound(task *api.TaskInfo) {\n\tif taskName := getTaskName(task); taskName != \"\" {\n\t\tset, ok := jm.nodeTaskSet[task.NodeName]\n\t\tif !ok {\n\t\t\tset = make(map[string]int)\n\t\t\tjm.nodeTaskSet[task.NodeName] = set\n\t\t}\n\t\tset[taskName]++\n\t}\n\n\tbucket := jm.GetBucket(task)\n\tif bucket != nil {\n\t\tbucket.TaskBound(task)\n\t}\n}", "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.killPodForTask(driver, taskId.GetValue(), messages.TaskKilled)\n}", "func (bot *botContext) callTask(t interface{}, command string, args ...string) (errString string, retval TaskRetVal) {\n\tbot.currentTask = t\n\tr := bot.makeRobot()\n\ttask, plugin, _ := getTask(t)\n\tisPlugin := plugin != nil\n\t// This should only happen in the rare case that a configured authorizer or elevator is disabled\n\tif task.Disabled {\n\t\tmsg := fmt.Sprintf(\"callTask failed on disabled task %s; reason: %s\", task.name, task.reason)\n\t\tLog(Error, msg)\n\t\tbot.debug(msg, false)\n\t\treturn msg, ConfigurationError\n\t}\n\tif bot.logger != nil {\n\t\tvar desc string\n\t\tif len(task.Description) > 0 {\n\t\t\tdesc = fmt.Sprintf(\"Starting task: %s\", task.Description)\n\t\t} else {\n\t\t\tdesc = \"Starting task\"\n\t\t}\n\t\tbot.logger.Section(task.name, desc)\n\t}\n\n\tif !(task.name == \"builtInadmin\" && command == \"abort\") {\n\t\tdefer checkPanic(r, fmt.Sprintf(\"Plugin: %s, command: %s, arguments: %v\", task.name, command, args))\n\t}\n\tLog(Debug, fmt.Sprintf(\"Dispatching command '%s' to plugin '%s' with arguments '%#v'\", command, task.name, args))\n\tif isPlugin && plugin.taskType == taskGo {\n\t\tif command != \"init\" {\n\t\t\temit(GoPluginRan)\n\t\t}\n\t\tLog(Debug, fmt.Sprintf(\"Call go plugin: '%s' with args: %q\", task.name, args))\n\t\treturn \"\", pluginHandlers[task.name].Handler(r, command, args...)\n\t}\n\tvar fullPath string // full path to the executable\n\tvar err error\n\tfullPath, err = getTaskPath(task)\n\tif err != nil {\n\t\temit(ScriptPluginBadPath)\n\t\treturn fmt.Sprintf(\"Error getting path for %s: %v\", task.name, err), MechanismFail\n\t}\n\tinterpreter, err := getInterpreter(fullPath)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"looking up interpreter for %s: %s\", fullPath, err)\n\t\tLog(Error, fmt.Sprintf(\"Unable to call external plugin %s, no interpreter found: %s\", fullPath, err))\n\t\terrString = \"There was a problem calling an external plugin\"\n\t\temit(ScriptPluginBadInterpreter)\n\t\treturn errString, MechanismFail\n\t}\n\texternalArgs := make([]string, 0, 5+len(args))\n\t// on Windows, we exec the interpreter with the script as first arg\n\tif runtime.GOOS == \"windows\" {\n\t\texternalArgs = append(externalArgs, fullPath)\n\t}\n\texternalArgs = append(externalArgs, command)\n\texternalArgs = append(externalArgs, args...)\n\texternalArgs = fixInterpreterArgs(interpreter, externalArgs)\n\tLog(Debug, fmt.Sprintf(\"Calling '%s' with interpreter '%s' and args: %q\", fullPath, interpreter, externalArgs))\n\tvar cmd *exec.Cmd\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd = exec.Command(interpreter, externalArgs...)\n\t} else {\n\t\tcmd = exec.Command(fullPath, externalArgs...)\n\t}\n\tbot.Lock()\n\tbot.taskName = task.name\n\tbot.taskDesc = task.Description\n\tbot.osCmd = cmd\n\tbot.Unlock()\n\tenvhash := make(map[string]string)\n\tif len(bot.environment) > 0 {\n\t\tfor k, v := range bot.environment {\n\t\t\tenvhash[k] = v\n\t\t}\n\t}\n\n\t// Pull stored env vars specific to this task and supply to this task only.\n\t// No effect if already defined. Useful mainly for specific tasks to have\n\t// secrets passed in but not handed to everything in the pipeline.\n\tif !bot.pipeStarting {\n\t\tstoredEnv := make(map[string]string)\n\t\t_, exists, _ := checkoutDatum(paramPrefix+task.NameSpace, &storedEnv, false)\n\t\tif exists {\n\t\t\tfor key, value := range storedEnv {\n\t\t\t\t// Dynamically provided and configured parameters take precedence over stored parameters\n\t\t\t\t_, exists := envhash[key]\n\t\t\t\tif !exists {\n\t\t\t\t\tenvhash[key] = value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbot.pipeStarting = false\n\t}\n\n\tenvhash[\"GOPHER_CHANNEL\"] = bot.Channel\n\tenvhash[\"GOPHER_USER\"] = bot.User\n\tenvhash[\"GOPHER_PROTOCOL\"] = fmt.Sprintf(\"%s\", bot.Protocol)\n\tenv := make([]string, 0, len(envhash))\n\tkeys := make([]string, 0, len(envhash))\n\tfor k, v := range envhash {\n\t\tif len(k) == 0 {\n\t\t\tLog(Error, fmt.Sprintf(\"Empty Name value while populating environment for '%s', skipping\", task.name))\n\t\t\tcontinue\n\t\t}\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", k, v))\n\t\tkeys = append(keys, k)\n\t}\n\tcmd.Env = env\n\tLog(Debug, fmt.Sprintf(\"Running '%s' with environment vars: '%s'\", fullPath, strings.Join(keys, \"', '\")))\n\tvar stderr, stdout io.ReadCloser\n\t// hold on to stderr in case we need to log an error\n\tstderr, err = cmd.StderrPipe()\n\tif err != nil {\n\t\tLog(Error, fmt.Errorf(\"Creating stderr pipe for external command '%s': %v\", fullPath, err))\n\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\treturn errString, MechanismFail\n\t}\n\tif bot.logger == nil {\n\t\t// close stdout on the external plugin...\n\t\tcmd.Stdout = nil\n\t} else {\n\t\tstdout, err = cmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tLog(Error, fmt.Errorf(\"Creating stdout pipe for external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\treturn errString, MechanismFail\n\t\t}\n\t}\n\tif err = cmd.Start(); err != nil {\n\t\tLog(Error, fmt.Errorf(\"Starting command '%s': %v\", fullPath, err))\n\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\treturn errString, MechanismFail\n\t}\n\tif command != \"init\" {\n\t\temit(ScriptTaskRan)\n\t}\n\tif bot.logger == nil {\n\t\tvar stdErrBytes []byte\n\t\tif stdErrBytes, err = ioutil.ReadAll(stderr); err != nil {\n\t\t\tLog(Error, fmt.Errorf(\"Reading from stderr for external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\treturn errString, MechanismFail\n\t\t}\n\t\tstdErrString := string(stdErrBytes)\n\t\tif len(stdErrString) > 0 {\n\t\t\tLog(Warn, fmt.Errorf(\"Output from stderr of external command '%s': %s\", fullPath, stdErrString))\n\t\t\terrString = fmt.Sprintf(\"There was error output while calling external task '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\temit(ScriptPluginStderrOutput)\n\t\t}\n\t} else {\n\t\tclosed := make(chan struct{})\n\t\tgo func() {\n\t\t\tscanner := bufio.NewScanner(stdout)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\tbot.logger.Log(\"OUT \" + line)\n\t\t\t}\n\t\t\tclosed <- struct{}{}\n\t\t}()\n\t\tgo func() {\n\t\t\tscanner := bufio.NewScanner(stderr)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\tbot.logger.Log(\"ERR \" + line)\n\t\t\t}\n\t\t\tclosed <- struct{}{}\n\t\t}()\n\t\thalfClosed := false\n\tcloseLoop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\tif halfClosed {\n\t\t\t\t\tbreak closeLoop\n\t\t\t\t}\n\t\t\t\thalfClosed = true\n\t\t\t}\n\t\t}\n\t}\n\tif err = cmd.Wait(); err != nil {\n\t\tretval = Fail\n\t\tsuccess := false\n\t\tif exitstatus, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := exitstatus.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tretval = TaskRetVal(status.ExitStatus())\n\t\t\t\tif retval == Success {\n\t\t\t\t\tsuccess = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !success {\n\t\t\tLog(Error, fmt.Errorf(\"Waiting on external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\temit(ScriptPluginErrExit)\n\t\t}\n\t}\n\treturn errString, retval\n}", "func (atr *ActiveTaskRun) Start() (int, time.Duration, error) {\n var env []string\n var err error\n\n for _, param := range atr.Task.Params {\n env = append(env, fmt.Sprintf(\"%s=%s\", param.Name, param.Value))\n }\n\n env = append(env, fmt.Sprintf(\"WAYFINDER_TOTAL_CORES=%d\", len(atr.CoreIds)))\n env = append(env, fmt.Sprintf(\"WAYFINDER_CORES=%s\", strings.Trim(\n strings.Join(strings.Fields(fmt.Sprint(atr.CoreIds)), \" \"), \"[]\",\n )))\n for i, coreId := range atr.CoreIds {\n env = append(env, fmt.Sprintf(\"WAYFINDER_CORE_ID%d=%d\", i, coreId))\n }\n\n config := &run.RunnerConfig{\n Log: atr.log,\n CacheDir: atr.Task.cacheDir,\n ResultsDir: atr.Task.resultsDir,\n AllowOverride: atr.Task.AllowOverride,\n Name: atr.run.Name,\n Image: atr.run.Image,\n CoreIds: atr.CoreIds,\n Devices: atr.run.Devices,\n Inputs: atr.Task.Inputs,\n Outputs: atr.Task.Outputs,\n Env: env,\n Capabilities: atr.run.Capabilities,\n }\n if atr.run.Path != \"\" {\n config.Path = atr.run.Path\n } else if atr.run.Cmd != \"\" {\n config.Cmd = atr.run.Cmd\n } else {\n return 1, -1, fmt.Errorf(\"Run did not specify path or cmd: %s\", atr.run.Name)\n }\n\n atr.Runner, err = run.NewRunner(config, atr.bridge, atr.dryRun)\n if err != nil {\n return 1, -1, err\n }\n\n atr.log.Infof(\"Starting run...\")\n exitCode, timeElapsed, err := atr.Runner.Run()\n atr.Runner.Destroy()\n if err != nil {\n return 1, -1, fmt.Errorf(\"Could not start runner: %s\", err)\n }\n\n return exitCode, timeElapsed, nil\n}", "func (s *Scheduler) Run(pctx context.Context) error {\n\tctx := log.WithModule(pctx, \"scheduler\")\n\tdefer close(s.doneChan)\n\n\ts.pipeline.AddFilter(&VolumesFilter{vs: s.volumes})\n\n\tupdates, cancel, err := store.ViewAndWatch(s.store, s.setupTasksList)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Errorf(\"snapshot store update failed\")\n\t\treturn err\n\t}\n\tdefer cancel()\n\n\t// Validate resource for tasks from preassigned tasks\n\t// do this before other tasks because preassigned tasks like\n\t// global service should start before other tasks\n\ts.processPreassignedTasks(ctx)\n\n\t// Queue all unassigned tasks before processing changes.\n\ts.tick(ctx)\n\n\tconst (\n\t\t// commitDebounceGap is the amount of time to wait between\n\t\t// commit events to debounce them.\n\t\tcommitDebounceGap = 50 * time.Millisecond\n\t\t// maxLatency is a time limit on the debouncing.\n\t\tmaxLatency = time.Second\n\t)\n\tvar (\n\t\tdebouncingStarted time.Time\n\t\tcommitDebounceTimer *time.Timer\n\t\tcommitDebounceTimeout <-chan time.Time\n\t)\n\n\ttickRequired := false\n\n\tschedule := func() {\n\t\tif len(s.pendingPreassignedTasks) > 0 {\n\t\t\ts.processPreassignedTasks(ctx)\n\t\t}\n\t\tif tickRequired {\n\t\t\ts.tick(ctx)\n\t\t\ttickRequired = false\n\t\t}\n\t}\n\n\t// Watch for changes.\n\tfor {\n\t\tselect {\n\t\tcase event := <-updates:\n\t\t\tswitch v := event.(type) {\n\t\t\tcase api.EventCreateTask:\n\t\t\t\tif s.createTask(ctx, v.Task) {\n\t\t\t\t\ttickRequired = true\n\t\t\t\t}\n\t\t\tcase api.EventUpdateTask:\n\t\t\t\tif s.updateTask(ctx, v.Task) {\n\t\t\t\t\ttickRequired = true\n\t\t\t\t}\n\t\t\tcase api.EventDeleteTask:\n\t\t\t\tif s.deleteTask(v.Task) {\n\t\t\t\t\t// deleting tasks may free up node resource, pending tasks should be re-evaluated.\n\t\t\t\t\ttickRequired = true\n\t\t\t\t}\n\t\t\tcase api.EventCreateNode:\n\t\t\t\ts.createOrUpdateNode(v.Node)\n\t\t\t\ttickRequired = true\n\t\t\tcase api.EventUpdateNode:\n\t\t\t\ts.createOrUpdateNode(v.Node)\n\t\t\t\ttickRequired = true\n\t\t\tcase api.EventDeleteNode:\n\t\t\t\ts.nodeSet.remove(v.Node.ID)\n\t\t\tcase api.EventUpdateVolume:\n\t\t\t\t// there is no need for a EventCreateVolume case, because\n\t\t\t\t// volumes are not ready to use until they've passed through\n\t\t\t\t// the volume manager and been created with the plugin\n\t\t\t\t//\n\t\t\t\t// as such, only addOrUpdateVolume if the VolumeInfo exists and\n\t\t\t\t// has a nonempty VolumeID\n\t\t\t\tif v.Volume.VolumeInfo != nil && v.Volume.VolumeInfo.VolumeID != \"\" {\n\t\t\t\t\t// TODO(dperny): verify that updating volumes doesn't break\n\t\t\t\t\t// scheduling\n\t\t\t\t\tlog.G(ctx).WithField(\"volume.id\", v.Volume.ID).Debug(\"updated volume\")\n\t\t\t\t\ts.volumes.addOrUpdateVolume(v.Volume)\n\t\t\t\t\ttickRequired = true\n\t\t\t\t}\n\t\t\tcase state.EventCommit:\n\t\t\t\tif commitDebounceTimer != nil {\n\t\t\t\t\tif time.Since(debouncingStarted) > maxLatency {\n\t\t\t\t\t\tcommitDebounceTimer.Stop()\n\t\t\t\t\t\tcommitDebounceTimer = nil\n\t\t\t\t\t\tcommitDebounceTimeout = nil\n\t\t\t\t\t\tschedule()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcommitDebounceTimer.Reset(commitDebounceGap)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcommitDebounceTimer = time.NewTimer(commitDebounceGap)\n\t\t\t\t\tcommitDebounceTimeout = commitDebounceTimer.C\n\t\t\t\t\tdebouncingStarted = time.Now()\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-commitDebounceTimeout:\n\t\t\tschedule()\n\t\t\tcommitDebounceTimer = nil\n\t\t\tcommitDebounceTimeout = nil\n\t\tcase <-s.stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (cl *tektonClient) StartTaskRun(taskrun *v1alpha1.TaskRun) (string, error) {\n\tnewTaskRun, err := cl.pipelineClient.TaskRuns(cl.namespace).Create(taskrun)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttime.Sleep(5 * time.Second)\n\ti := 0\n\tfor i < BuildTimeout {\n\t\ttaskrun, err = cl.pipelineClient.TaskRuns(cl.namespace).Get(newTaskRun.Name, metav1.GetOptions{})\n\t\tif taskrun.Status.Conditions[0].Type == apis.ConditionSucceeded && taskrun.Status.Conditions[0].Status == \"True\" {\n\t\t\tfmt.Println(\"[INFO] Build task run\", taskrun.Name, \"is ready from\", taskrun.Status.StartTime, \"to\", taskrun.Status.CompletionTime)\n\t\t\treturn taskrun.Name, nil\n\t\t} else {\n\t\t\tfmt.Println(\"[INFO] Build task run\", taskrun.Name, \"is still\", taskrun.Status.Conditions[0].Reason, \", waiting\")\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t\ti += 5\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\treturn taskrun.Name, fmt.Errorf(\"the build taskrun is not ready after timeout\")\n}", "func addTask(applicationMap map[string]Application, appId string, task Task) bool {\n app, ok := applicationMap[appId]\n if !ok {\n loadExistingApps(applicationMap)\n app, ok = applicationMap[appId]\n if !ok {\n log.Printf(\"ERR Unknown application %s\\n\", appId)\n return false\n }\n return true\n }\n _, ok = app.ApplicationInstances[task.Id]\n if ok {\n return false\n }\n app.ApplicationInstances[task.Id] = task\n var port = \"\"\n if len(task.Ports) != 0 {\n port = fmt.Sprintf(\":%d\", task.Ports[0])\n }\n log.Printf(\"INFO Found task for %s on %s%s [%s]\\n\", appId, task.Host, port, task.Id)\n return true\n}", "func (c Control) ServeTaskAction(w http.ResponseWriter, r *http.Request, start bool) {\n\tid, err := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc.Config.Lock()\n\tdefer c.Config.Unlock()\n\t_, task := c.findTaskById(id)\n\tif task == nil {\n\t\thttp.Error(w, \"Invalid task ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif start {\n\t\ttask.Start()\n\t} else {\n\t\ttask.Stop()\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}", "func (t *task) createTask(ctx context.Context, runtime *pbtask.RuntimeInfo, owner string) error {\n\tvar runtimeCopy *pbtask.RuntimeInfo\n\tvar labelsCopy []*peloton.Label\n\n\t// notify listeners after dropping the lock\n\tdefer func() {\n\t\tt.jobFactory.notifyTaskRuntimeChanged(\n\t\t\tt.JobID(),\n\t\t\tt.ID(),\n\t\t\tt.jobType,\n\t\t\truntimeCopy,\n\t\t\tlabelsCopy,\n\t\t)\n\t}()\n\tt.Lock()\n\tdefer t.Unlock()\n\n\t// First create the runtime in DB and then store in the cache if DB create is successful\n\terr := t.jobFactory.taskStore.CreateTaskRuntime(\n\t\tctx,\n\t\tt.jobID,\n\t\tt.id,\n\t\truntime,\n\t\towner,\n\t\tt.jobType)\n\tif err != nil {\n\t\tt.cleanTaskCache()\n\t\treturn err\n\t}\n\n\t// Update the config in cache only after creating the runtime in DB\n\t// so that cache is not populated if runtime write fails.\n\terr = t.updateConfig(ctx, runtime.GetConfigVersion())\n\tif err != nil {\n\t\tt.cleanTaskCache()\n\t\treturn err\n\t}\n\tt.logStateTransitionMetrics(runtime)\n\n\tt.runtime = runtime\n\truntimeCopy = proto.Clone(t.runtime).(*pbtask.RuntimeInfo)\n\tlabelsCopy = t.copyLabelsInCache()\n\treturn nil\n}", "func (e *Eval) retryTask(ctx context.Context, f *Flow, resources reflow.Resources, retryType, msg string) (*sched.Task, error) {\n\t// Apply ExecReset so that the exec can be resubmitted to the scheduler with the flow's\n\t// exec runtime parameters reset.\n\tf.ExecReset()\n\tcappedR, capped, err := e.capMemory(resources)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase capped:\n\t\te.Log.Printf(\"flow %s: retryTask (reason: %s): capping resources from %s to %s (max available %s)\", f.Digest().Short(), retryType, resources, cappedR, e.MaxResources)\n\t\tresources.Set(cappedR)\n\t}\n\te.Mutate(f, SetReserved(resources), Execing)\n\ttask := e.newTask(f)\n\te.Log.Printf(\"flow %s: retryTask (reason: %s): re-submitting task with %s\", f.Digest().Short(), retryType, msg)\n\te.Scheduler.Submit(task)\n\treturn task, e.taskWait(ctx, f, task)\n}", "func (c *Job) BeforeExecuteTask() *Job {\n\tif c.delayUnit == delayNone {\n\t\tc.timingMode = beforeExecuteTask\n\t}\n\treturn c\n}", "func NewTask(service *Service) *Task {\n\treturn &Task{\n\t\tTask: task.New(StatusTaskStarted),\n\t\tService: service,\n\t}\n}", "func (client *Client) CreateEvaluateTask(request *CreateEvaluateTaskRequest) (response *CreateEvaluateTaskResponse, err error) {\n\tresponse = CreateCreateEvaluateTaskResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (service *Service) NewTask() *Task {\n\ttask := NewTask(service)\n\tservice.Worker.AddTask(task)\n\n\treturn task\n}", "func (c *CheckpointAdvancer) StartTaskListener(ctx context.Context) {\n\tcx, cancel := context.WithCancel(ctx)\n\tvar ch <-chan TaskEvent\n\tfor {\n\t\tif cx.Err() != nil {\n\t\t\t// make linter happy.\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\t\tvar err error\n\t\tch, err = c.beginListenTaskChange(cx)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Warn(\"failed to begin listening, retrying...\", logutil.ShortError(err))\n\t\ttime.Sleep(c.cfg.BackoffTime)\n\t}\n\n\tgo func() {\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase e, ok := <-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlog.Info(\"meet task event\", zap.Stringer(\"event\", &e))\n\t\t\t\tif err := c.onTaskEvent(ctx, e); err != nil {\n\t\t\t\t\tif errors.Cause(e.Err) != context.Canceled {\n\t\t\t\t\t\tlog.Error(\"listen task meet error, would reopen.\", logutil.ShortError(err))\n\t\t\t\t\t\ttime.AfterFunc(c.cfg.BackoffTime, func() { c.StartTaskListener(ctx) })\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func (rm *ExchangeSvc) OpenTaskPartition(\n\tch chan *zbsubscriptions.SubscriptionEvent,\n\tpartitionID uint16,\n\tlockOwner,\n\ttaskType string,\n\tlockDuration uint64,\n\tcredits int32) *zbmsgpack.TaskSubscriptionInfo {\n\n\tmessage := rm.OpenTaskSubscriptionRequest(partitionID, lockOwner, taskType, lockDuration, credits)\n\trequest := zbsocket.NewRequestWrapper(message)\n\tresp, err := rm.ExecuteRequest(request)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tif taskSubInfo := rm.UnmarshalTaskSubscriptionInfo(resp); taskSubInfo != nil {\n\t\trequest.Sock.AddTaskSubscription(taskSubInfo.SubscriberKey, ch)\n\t\treturn taskSubInfo\n\t}\n\treturn nil\n}", "func PutTask(task *Task) {\n\ttask.Run, task.Arg = nil, nil\n\ttaskPool.Put(task)\n}" ]
[ "0.7151628", "0.6997699", "0.6953215", "0.64792854", "0.61711955", "0.61174685", "0.5406098", "0.5249409", "0.52027667", "0.5174867", "0.507748", "0.50657153", "0.505682", "0.5042173", "0.5036232", "0.5027475", "0.50242066", "0.49648792", "0.49447122", "0.4936511", "0.49021584", "0.489714", "0.489099", "0.48880363", "0.4811992", "0.4746012", "0.4730319", "0.47260466", "0.47083163", "0.47021225", "0.47008955", "0.46933582", "0.4625406", "0.460953", "0.4604076", "0.45837983", "0.45824125", "0.45741558", "0.4556891", "0.45560005", "0.45529467", "0.45510426", "0.45282033", "0.45188087", "0.45171317", "0.45164603", "0.45163426", "0.4499236", "0.44984487", "0.44733673", "0.4471853", "0.44706154", "0.44491917", "0.44188124", "0.4409823", "0.4397865", "0.43956745", "0.4381817", "0.43769228", "0.43645582", "0.43639642", "0.4362248", "0.43621272", "0.43562013", "0.4340582", "0.4338253", "0.4335197", "0.43171403", "0.4315532", "0.43152046", "0.4307445", "0.43013737", "0.43007624", "0.4294038", "0.42916793", "0.4284944", "0.4279376", "0.42768714", "0.42760244", "0.4267161", "0.42632908", "0.42572898", "0.4257243", "0.4256171", "0.42515472", "0.42456657", "0.42377934", "0.42337295", "0.42223534", "0.4217899", "0.42161763", "0.42127532", "0.4205089", "0.42002493", "0.41987014", "0.41982043", "0.41970173", "0.419463", "0.4180794", "0.41805485" ]
0.7106327
1
determine whether we need to start a suicide countdown. if so, then start a timer that, upon expiration, causes this executor to commit suicide. this implementation runs asynchronously. callers that wish to wait for the reset to complete may wait for the returned signal chan to close.
func (k *KubernetesExecutor) resetSuicideWatch(driver bindings.ExecutorDriver) <-chan struct{} { ch := make(chan struct{}) go func() { defer close(ch) k.lock.Lock() defer k.lock.Unlock() if k.suicideTimeout < 1 { return } if k.suicideWatch != nil { if len(k.tasks) > 0 { k.suicideWatch.Stop() return } if k.suicideWatch.Reset(k.suicideTimeout) { // valid timer, reset was successful return } } //TODO(jdef) reduce verbosity here once we're convinced that suicide watch is working properly log.Infof("resetting suicide watch timer for %v", k.suicideTimeout) k.suicideWatch = k.suicideWatch.Next(k.suicideTimeout, driver, jumper(k.attemptSuicide)) }() return ch }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestRetryTimerSimple(t *testing.T) {\n\tdoneCh := make(chan struct{})\n\tattemptCh := newRetryTimerSimple(doneCh)\n\ti := <-attemptCh\n\tif i != 0 {\n\t\tclose(doneCh)\n\t\tt.Fatalf(\"Invalid attempt counter returned should be 0, found %d instead\", i)\n\t}\n\ti = <-attemptCh\n\tif i <= 0 {\n\t\tclose(doneCh)\n\t\tt.Fatalf(\"Invalid attempt counter returned should be greater than 0, found %d instead\", i)\n\t}\n\tclose(doneCh)\n\t_, ok := <-attemptCh\n\tif ok {\n\t\tt.Fatal(\"Attempt counter should be closed\")\n\t}\n}", "func (r *FailBack) startResetTimer() chan struct{} {\n\tfailCh := make(chan struct{}, 1)\n\tgo func() {\n\t\ttimer := time.NewTimer(r.opt.ResetAfter)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-failCh:\n\t\t\t\tif !timer.Stop() {\n\t\t\t\t\t<-timer.C\n\t\t\t\t}\n\t\t\tcase <-timer.C:\n\t\t\t\tr.mu.Lock()\n\t\t\t\tr.active = 0\n\t\t\t\tLog.WithField(\"resolver\", r.resolvers[r.active].String()).Debug(\"failing back to resolver\")\n\t\t\t\tr.mu.Unlock()\n\t\t\t\tr.metrics.available.Add(1)\n\t\t\t\t// we just reset to the first resolver, let's wait for another failure before running again\n\t\t\t\t<-failCh\n\t\t\t}\n\t\t\ttimer.Reset(r.opt.ResetAfter)\n\t\t}\n\t}()\n\treturn failCh\n}", "func (opcTimer *OPCTimer) Run(wg *sync.WaitGroup) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tforceTimerDuration := opcTimer.intervalForce\n\t\ttimerDuration := opcTimer.interval\n\t\tvar forceTimer <-chan time.Time\n\t\tif forceTimerDuration > 0 {\n\t\t\tforceTimer = time.NewTimer(forceTimerDuration).C\n\t\t}\n\t\tvar timer <-chan time.Time\n\t\tif timerDuration > 0 {\n\t\t\ttimer = time.NewTimer(timerDuration).C\n\t\t}\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-forceTimer:\n\t\t\t\tforceTimer = time.NewTimer(forceTimerDuration).C\n\t\t\t\tprintf(\"**** FORCE!!! ****\\n\")\n\t\t\t\tfor e := opcTimer.trackers.Front(); e != nil; e = e.Next() {\n\t\t\t\t\tif e.Value.(*Tracker).force == false {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tsuccess, data := e.Value.(*Tracker).ReadValue()\n\t\t\t\t\tif success {\n\t\t\t\t\t\te.Value.(*Tracker).WriteValue(data)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintf(\"**** **** ****\\n\")\n\t\t\tcase <-timer:\n\t\t\t\ttimer = time.NewTimer(timerDuration).C\n\t\t\t\tprintf(\"**** TIMER ****\\n\")\n\t\t\t\tfor e := opcTimer.trackers.Front(); e != nil; e = e.Next() {\n\t\t\t\t\tsuccess, data := e.Value.(*Tracker).ReadValue()\n\t\t\t\t\tif success {\n\t\t\t\t\t\tif e.Value.(*Tracker).lastValue != data.Value {\n\t\t\t\t\t\t\te.Value.(*Tracker).force = false\n\t\t\t\t\t\t\te.Value.(*Tracker).WriteValue(data)\n\t\t\t\t\t\t\te.Value.(*Tracker).lastValue = data.Value\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprintf(\"%s not changed\\n\", data.Name)\n\t\t\t\t\t\t\te.Value.(*Tracker).force = true\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te.Value.(*Tracker).force = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintf(\"**** **** ****\\n\")\n\t\t\t}\n\t\t}\n\t}()\n}", "func cancel() {\n\tch := make(chan string, 1)\n\n\tfor i := 1; i <= 10; i++ {\n\t\tfmt.Println(\"Trial \", i)\n\t\t// worker\n\t\tgo func() {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)\n\t\t\tch <- \"paperwork\"\n\t\t\tfmt.Println(\"employee: sent paperwork\")\n\t\t}()\n\n\t\t// create a timer channel which will ping us 100ms in the future\n\t\ttc := time.After(100 * time.Millisecond)\n\n\t\tselect {\n\t\tcase p := <-ch:\n\t\t\tfmt.Println(\"manager: received signal from worker:\", p)\n\t\tcase t := <-tc:\n\t\t\tfmt.Println(\"manager: timeout. Done waiting. (msg:\", t, \")\")\n\t\t}\n\t}\n\n\ttime.Sleep(time.Second)\n}", "func (ctx *DeferredContext) KickTimer() {\n\tctx.Ticker.TickNow()\n}", "func (qp *quotaPool) cancel() {\n\tqp.lock.Lock()\n\tdefer qp.lock.Unlock()\n\tselect {\n\tcase n := <-qp.acquireChannel:\n\t\tqp.quota += n\n\tdefault:\n\t}\n}", "func (s *Stopper) Quiesce(ctx context.Context) {\n\tdefer s.Recover(ctx)\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, cancel := range s.mu.qCancels {\n\t\tcancel()\n\t}\n\tif !s.mu.quiescing {\n\t\ts.mu.quiescing = true\n\t\tclose(s.quiescer)\n\t}\n\tfor s.mu.numTasks > 0 {\n\t\tlog.Infof(ctx, \"quiescing; tasks left:\\n%s\", s.runningTasksLocked())\n\t\t// Unlock s.mu, wait for the signal, and lock s.mu.\n\t\ts.mu.quiesce.Wait()\n\t}\n}", "func (client *TimeClient) worker() {\n\tclient.locker.Lock()\n\tif client.running {\n\t\tclient.locker.Unlock()\n\t\treturn\n\t}\n\tclient.running = true\n\tclient.locker.Unlock()\n\ttimeout := time.Duration(1)\n\n\tfor {\n\t\tselect {\n\t\tcase <-client.stopChannel:\n\t\t\tbreak\n\t\tcase <-time.After(timeout):\n\t\t\t// run the client\n\t\t\terr, errcode, timeresp := client.getTime()\n\t\t\ttimeout = client.checkTimeInterval\n\t\t\tif err != nil {\n\t\t\t\tif client.backingOff {\n\t\t\t\t\tclient.backoff = client.backoff * time.Duration(2)\n\t\t\t\t} else {\n\t\t\t\t\tclient.backoff = initialBackoff\n\t\t\t\t}\n\t\t\t\tif client.backoff > maxBackoff {\n\t\t\t\t\tclient.backoff = maxBackoff\n\t\t\t\t}\n\t\t\t\tclient.backingOff = true\n\t\t\t\ttimeout = client.backoff\n\t\t\t\t// analyze errors and send to status channel\n\t\t\t\tclient.sendToStatusChannel(errcode)\n\t\t\t} else {\n\t\t\t\tclient.backingOff = false\n\t\t\t\tclient.backoff = 0\n\t\t\t\tclient.locker.Lock()\n\t\t\t\ttimeout = client.checkTimeInterval\n\t\t\t\tclient.locker.Unlock()\n\n\t\t\t\t// set the time\n\t\t\t\tif timeresp.Time > recentTime {\n\t\t\t\t\ttimespec := timeToTimeval(timeresp.Time)\n\t\t\t\t\tnow := time.Now().UnixNano() / 1000000\n\t\t\t\t\tlog.MaestroInfof(\"Time: time being adjusted. Skew is %d ms\\n\", now-timeresp.Time)\n\t\t\t\t\tif client.pretend {\n\t\t\t\t\t\tlog.MaestroInfof(\"Time: time would be set to %d s %d us - but prentending only.\\n\", timespec.Sec, timespec.Usec)\n\t\t\t\t\t} else {\n\t\t\t\t\t\terrno := syscall.Settimeofday(&timespec)\n\t\t\t\t\t\tif errno != nil {\n\t\t\t\t\t\t\tlog.MaestroErrorf(\"Time: settimeofday failed: %s\\n\", errno.Error())\n\t\t\t\t\t\t\tclient.sendToStatusChannel(SycallFailed)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.MaestroSuccess(\"Time: time of day updated.\")\n\t\t\t\t\t\t\tclient.sendToStatusChannel(SetTimeOk)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.MaestroErrorf(\"Time server reported INSANE time value (%ld) - ignoring.\\n\", timeresp.Time)\n\t\t\t\t\tclient.sendToStatusChannel(InsaneResponse)\n\t\t\t\t}\n\t\t\t\t// send to status channel\n\t\t\t}\n\t\t}\n\t}\n\n\tclient.locker.Lock()\n\tclient.running = false\n\tclient.locker.Unlock()\n}", "func (clock Timer) Countdown() {\n\tticker := newTicker()\n\tclock.runCountdown(ticker)\n}", "func (c *Consumer) signalLoop() error {\n\tclaims := make(Claims)\n\tfor {\n\n\t\t// Check if shutdown was requested\n\t\tselect {\n\t\tcase <-c.closer.Dying():\n\t\t\treturn c.shutdown(claims)\n\t\tdefault:\n\t\t}\n\n\t\t// Start a rebalance cycle\n\t\twatch, err := c.rebalance(claims)\n\t\tif err != nil {\n\t\t\tc.config.Notifier.RebalanceError(c, err)\n\t\t\tc.reset(claims)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Start a goroutine for each partition\n\t\tdone := make(chan struct{})\n\t\terrs := make(chan struct{}, len(claims))\n\t\twait := new(sync.WaitGroup)\n\t\tfor _, pcsm := range claims {\n\t\t\twait.Add(1)\n\t\t\tgo c.consumeLoop(done, errs, wait, pcsm)\n\t\t}\n\n\t\t// Wait for signals\n\t\tselect {\n\t\tcase <-c.closer.Dying(): // on Close()\n\t\t\tclose(done)\n\t\t\twait.Wait()\n\t\t\treturn c.shutdown(claims)\n\t\tcase <-watch: // on rebalance signal\n\t\t\tclose(done)\n\t\t\twait.Wait()\n\t\tcase <-errs: // on consume errors\n\t\t\tclose(done)\n\t\t\twait.Wait()\n\t\t}\n\t}\n}", "func (tk *timekeeper) run() {\n\n\t//main timekeeper loop\nloop:\n\tfor {\n\t\tselect {\n\n\t\tcase cmd, ok := <-tk.supvCmdch:\n\t\t\tif ok {\n\t\t\t\tif cmd.GetMsgType() == TK_SHUTDOWN {\n\t\t\t\t\tcommon.Infof(\"Timekeeper::run Shutting Down\")\n\t\t\t\t\ttk.supvCmdch <- &MsgSuccess{}\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t\ttk.handleSupvervisorCommands(cmd)\n\t\t\t} else {\n\t\t\t\t//supervisor channel closed. exit\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t}\n\t}\n}", "func quiesce() {\n\t// The kernel will deliver a signal as a thread returns\n\t// from a syscall. If the only active thread is sleeping,\n\t// and the system is busy, the kernel may not get around\n\t// to waking up a thread to catch the signal.\n\t// We try splitting up the sleep to give the kernel\n\t// many chances to deliver the signal.\n\tstart := time.Now()\n\tfor time.Since(start) < settleTime {\n\t\ttime.Sleep(settleTime / 10)\n\t}\n}", "func (t *PCPTimer) Reset() error {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\tif t.started {\n\t\treturn errors.New(\"trying to reset an already started timer\")\n\t}\n\n\treturn t.set(float64(0))\n}", "func (i *idlenessManagerImpl) handleIdleTimeout() {\n\tif i.isClosed() {\n\t\treturn\n\t}\n\n\tif atomic.LoadInt32(&i.activeCallsCount) > 0 {\n\t\ti.resetIdleTimer(time.Duration(i.timeout))\n\t\treturn\n\t}\n\n\t// There has been activity on the channel since we last got here. Reset the\n\t// timer and return.\n\tif atomic.LoadInt32(&i.activeSinceLastTimerCheck) == 1 {\n\t\t// Set the timer to fire after a duration of idle timeout, calculated\n\t\t// from the time the most recent RPC completed.\n\t\tatomic.StoreInt32(&i.activeSinceLastTimerCheck, 0)\n\t\ti.resetIdleTimer(time.Duration(atomic.LoadInt64(&i.lastCallEndTime) + i.timeout - time.Now().UnixNano()))\n\t\treturn\n\t}\n\n\t// This CAS operation is extremely likely to succeed given that there has\n\t// been no activity since the last time we were here. Setting the\n\t// activeCallsCount to -math.MaxInt32 indicates to onCallBegin() that the\n\t// channel is either in idle mode or is trying to get there.\n\tif !atomic.CompareAndSwapInt32(&i.activeCallsCount, 0, -math.MaxInt32) {\n\t\t// This CAS operation can fail if an RPC started after we checked for\n\t\t// activity at the top of this method, or one was ongoing from before\n\t\t// the last time we were here. In both case, reset the timer and return.\n\t\ti.resetIdleTimer(time.Duration(i.timeout))\n\t\treturn\n\t}\n\n\t// Now that we've set the active calls count to -math.MaxInt32, it's time to\n\t// actually move to idle mode.\n\tif i.tryEnterIdleMode() {\n\t\t// Successfully entered idle mode. No timer needed until we exit idle.\n\t\treturn\n\t}\n\n\t// Failed to enter idle mode due to a concurrent RPC that kept the channel\n\t// active, or because of an error from the channel. Undo the attempt to\n\t// enter idle, and reset the timer to try again later.\n\tatomic.AddInt32(&i.activeCallsCount, math.MaxInt32)\n\ti.resetIdleTimer(time.Duration(i.timeout))\n}", "func (c *canceler) Cancel(ctx context.Context, id string) error {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.cancelled[id] = time.Now().Add(5 * time.Minute)\n\tif sub, ok := c.subsciber[id]; ok {\n\t\tclose(sub)\n\t}\n\tc.clear()\n\treturn nil\n}", "func (f *failoverStatus) cancel() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.timer != nil {\n\t\tf.timer.Stop()\n\t}\n}", "func (s *Stopper) Quiesce(ctx context.Context) {\n\tdefer time.AfterFunc(5*time.Second, func() {\n\t\tlog.Infof(ctx, \"quiescing...\")\n\t}).Stop()\n\tdefer s.Recover(ctx)\n\n\tfunc() {\n\t\ts.mu.Lock()\n\t\tdefer s.mu.Unlock()\n\t\tif !s.mu.quiescing {\n\t\t\ts.mu.quiescing = true\n\t\t\tclose(s.quiescer)\n\t\t}\n\n\t\ts.mu.qCancels.Range(func(k, v interface{}) (wantMore bool) {\n\t\t\tcancel := v.(func())\n\t\t\tcancel()\n\t\t\ts.mu.qCancels.Delete(k)\n\t\t\treturn true\n\t\t})\n\t}()\n\n\tfor s.NumTasks() > 0 {\n\t\ttime.Sleep(5 * time.Millisecond)\n\t}\n}", "func (th *Throttler) resetCounterLoop(after time.Duration) {\n\tticker := time.NewTicker(after)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif th.quotaHit() {\n\t\t\t\tatomic.StoreUint64(&th.counter, 0)\n\t\t\t\tth.doNotify()\n\t\t\t}\n\n\t\tcase <-th.done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (hb *heartbeat) reset() {\n\tselect {\n\tcase hb.resetChan <- struct{}{}:\n\tdefault:\n\t}\n}", "func (qp *quotaPool) reset(v int) {\n\tqp.lock.Lock()\n\tdefer qp.lock.Unlock()\n\tselect {\n\tcase n := <-qp.acquireChannel:\n\t\tqp.quota += n\n\tdefault:\n\t}\n\tqp.quota += v\n\tif qp.quota <= 0 {\n\t\treturn\n\t}\n\tselect {\n\tcase qp.acquireChannel <- qp.quota:\n\t\tqp.quota = 0\n\tdefault:\n\t}\n}", "func (t *Uint64Tracker) Run(initialValue uint64) {\n\tt.value = initialValue\n\tt.pending = nil\n\tinputChan := make(chan inquiry, 10)\n\tt.input = inputChan\n\tgo func() {\n\t\tfor i := range inputChan {\n\t\t\tif i.Return == nil {\n\t\t\t\tt.handleSet(i.NewValue)\n\t\t\t} else {\n\t\t\t\tt.handleGet(i)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (c *Timer) Run() {\n\t//c.active = true\n\tc.ticker = time.NewTicker(c.options.TickerInternal)\n\tc.lastTick = time.Now()\n\tif !c.started {\n\t\tc.started = true\n\t\tc.options.OnRun(true)\n\t} else {\n\t\tc.options.OnRun(false)\n\t}\n\tc.options.OnTick()\n\tfor tickAt := range c.ticker.C {\n\t\tc.passed += tickAt.Sub(c.lastTick)\n\t\tc.lastTick = time.Now()\n\t\tc.options.OnTick()\n\t\tif c.Remaining() <= 0 {\n\t\t\tc.ticker.Stop()\n\t\t\tc.options.OnDone(false)\n\t\t} else if c.Remaining() <= c.options.TickerInternal {\n\t\t\tc.ticker.Stop()\n\t\t\ttime.Sleep(c.Remaining())\n\t\t\tc.passed = c.options.Duration\n\t\t\tc.options.OnTick()\n\t\t\tc.options.OnDone(false)\n\n\t\t}\n\t}\n}", "func alarmOnce(ns int64) <-chan int {\n\tbackchan := make(chan int)\n\tgo func() {\n\t\ttime.Sleep(time.Duration(ns))\n\t\tbackchan <- 1\n\t\tclose(backchan)\n\t}()\n\treturn backchan\n}", "func (p *Chip) Tick() error {\n\tif !p.tickDone {\n\t\tp.opDone = true\n\t\treturn InvalidCPUState{\"called Tick() without calling TickDone() at end of last cycle\"}\n\t}\n\tp.tickDone = false\n\n\t// If RDY is held high we do nothing and just return (time doesn't advance in the CPU).\n\t// TODO(jchacon): Ok, this technically only works like this in combination with SYNC being held high as well.\n\t// Otherwise it acts like a single step and continues after the next clock.\n\t// But, the only use known right now was atari 2600 which tied SYNC high and RDY low at the same\n\t// time so \"good enough\".\n\tif p.rdy != nil && p.rdy.Raised() {\n\t\treturn nil\n\t}\n\tp.clocks++\n\n\t// Institute delay up front since we can return in N places below.\n\ttimes := p.timeRuns\n\tif p.timeNeedAdjust {\n\t\t// Only add time if incrementing tick didn't jump by more than a single digit.\n\t\t// i.e. if we're at 1.3 we tick at 0, 1.3, 2.6, 3.9 but not 5.2 as a result.\n\t\to := int(p.timerTicks) + 1\n\t\tp.timerTicks += p.timeAdjustCnt\n\t\tif o != int(p.timerTicks) {\n\t\t\ttimes++\n\t\t}\n\t\tif int(p.timerTicks) >= p.timerTicksReset {\n\t\t\tp.timerTicks = 0\n\t\t}\n\t}\n\tfor i := 0; i < times; i++ {\n\t\t_ = time.Now()\n\t}\n\tif p.irqRaised < kIRQ_NONE || p.irqRaised >= kIRQ_MAX {\n\t\tp.opDone = true\n\t\treturn InvalidCPUState{fmt.Sprintf(\"p.irqRaised is invalid: %d\", p.irqRaised)}\n\t}\n\t// Fast path if halted. The PC won't advance. i.e. we just keep returning the same error.\n\tif p.halted {\n\t\tp.opDone = true\n\t\treturn HaltOpcode{p.haltOpcode}\n\t}\n\n\t// Increment up front so we're not zero based per se. i.e. each new instruction then\n\t// starts at opTick == 1.\n\tp.opTick++\n\n\t// If we get a new interrupt while running one then NMI always wins until it's done.\n\tvar irq, nmi bool\n\tif p.irq != nil {\n\t\tirq = p.irq.Raised()\n\t}\n\tif p.nmi != nil {\n\t\tnmi = p.nmi.Raised()\n\t}\n\tif irq || nmi {\n\t\tswitch p.irqRaised {\n\t\tcase kIRQ_NONE:\n\t\t\tp.irqRaised = kIRQ_IRQ\n\t\t\tif nmi {\n\t\t\t\tp.irqRaised = kIRQ_NMI\n\t\t\t}\n\t\tcase kIRQ_IRQ:\n\t\t\tif nmi {\n\t\t\t\tp.irqRaised = kIRQ_NMI\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch {\n\tcase p.opTick == 1:\n\t\t// If opTick is 1 it means we're starting a new instruction based on the PC value so grab the opcode now.\n\t\tp.op = p.ram.Read(p.PC)\n\n\t\t// Reset done state\n\t\tp.opDone = false\n\t\tp.addrDone = false\n\n\t\t// PC always advances on every opcode start except IRQ/HMI (unless we're skipping to run one more instruction).\n\t\tif p.irqRaised == kIRQ_NONE || p.skipInterrupt {\n\t\t\tp.PC++\n\t\t\tp.runningInterrupt = false\n\t\t}\n\t\tif p.irqRaised != kIRQ_NONE && !p.skipInterrupt {\n\t\t\tp.runningInterrupt = true\n\t\t}\n\t\treturn nil\n\tcase p.opTick == 2:\n\t\t// All instructions fetch the value after the opcode (though some like BRK/PHP/etc ignore it).\n\t\t// We keep it since some instructions such as absolute addr then require getting one\n\t\t// more byte. So cache at this stage since we no idea if it's needed.\n\t\t// NOTE: the PC doesn't increment here as that's dependent on addressing mode which will handle it.\n\t\tp.opVal = p.ram.Read(p.PC)\n\n\t\t// We've started a new instruction so no longer skipping interrupt processing.\n\t\tp.prevSkipInterrupt = false\n\t\tif p.skipInterrupt {\n\t\t\tp.skipInterrupt = false\n\t\t\tp.prevSkipInterrupt = true\n\t\t}\n\tcase p.opTick > 8:\n\t\t// This is impossible on a 65XX as all instructions take no more than 8 ticks.\n\t\t// Technically documented instructions max at 7 ticks but a RMW indirect X/Y will take 8.\n\t\tp.opDone = true\n\t\treturn InvalidCPUState{fmt.Sprintf(\"opTick %d too large (> 8)\", p.opTick)}\n\t}\n\n\tvar err error\n\tif p.runningInterrupt {\n\t\taddr := IRQ_VECTOR\n\t\tif p.irqRaised == kIRQ_NMI {\n\t\t\taddr = NMI_VECTOR\n\t\t}\n\t\tp.opDone, err = p.runInterrupt(addr, true)\n\t} else {\n\t\tp.opDone, err = p.processOpcode()\n\t}\n\n\tif p.halted {\n\t\tp.haltOpcode = p.op\n\t\tp.opDone = true\n\t\treturn HaltOpcode{p.op}\n\t}\n\tif err != nil {\n\t\t// Still consider this a halt since it's an internal precondition check.\n\t\tp.haltOpcode = p.op\n\t\tp.halted = true\n\t\tp.opDone = true\n\t\treturn err\n\t}\n\tif p.opDone {\n\t\t// So the next tick starts a new instruction\n\t\t// It'll handle doing start of instruction reset on state (which includes resetting p.opDone, p.addrDone).\n\t\tp.opTick = 0\n\t\t// If we're currently running one clear state so we don't loop trying to run it again.\n\t\tif p.runningInterrupt {\n\t\t\tp.irqRaised = kIRQ_NONE\n\t\t}\n\t\tp.runningInterrupt = false\n\t}\n\treturn nil\n}", "func (c *controller) setupSignalChannel(cancel context.CancelFunc) {\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, syscall.SIGTERM)\n\n\tgo func() {\n\t\t<-sigchan\n\t\tlogger.Info(\"Received SIGTERM signal. Initiating shutdown.\")\n\t\tcancel()\n\t}()\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 (rp *Reprovider) Run(tick time.Duration) {\n\t// dont reprovide immediately.\n\t// may have just started the daemon and shutting it down immediately.\n\t// probability( up another minute | uptime ) increases with uptime.\n\tafter := time.After(time.Minute)\n\tvar done doneFunc\n\tfor {\n\t\tif tick == 0 {\n\t\t\tafter = make(chan time.Time)\n\t\t}\n\n\t\tselect {\n\t\tcase <-rp.ctx.Done():\n\t\t\treturn\n\t\tcase done = <-rp.trigger:\n\t\tcase <-after:\n\t\t}\n\n\t\t//'mute' the trigger channel so when `ipfs bitswap reprovide` is called\n\t\t//a 'reprovider is already running' error is returned\n\t\tunmute := rp.muteTrigger()\n\n\t\terr := rp.Reprovide()\n\t\tif err != nil {\n\t\t\tlog.Debug(err)\n\t\t}\n\n\t\tif done != nil {\n\t\t\tdone(err)\n\t\t}\n\n\t\tunmute()\n\n\t\tafter = time.After(tick)\n\t}\n}", "func main() {\n\tcloseChan := make(chan os.Signal, 1)\n\tsignal.Notify(closeChan, syscall.SIGINT)\n\n var wg sync.WaitGroup\n wg.Add(1) // HLwg\n\tsig := boring(&wg)\n\t<-closeChan\n\n\tsig<-1\n\twg.Wait() // HLwg\n}", "func (reporter *RedisReporter) Run() {\n\treporter.running = true\n\n\tfor {\n\t\tselect {\n\t\tcase t := <-reporter.channel.Channel():\n\t\t\treceivers, err := report(reporter.client, t)\n\n\t\t\tif err != nil {\n\t\t\t\treporter.running = false\n\n\t\t\t\t_, ok := err.(*retryingRedis.ClientClosedError)\n\t\t\t\tif ok {\n\t\t\t\t\tlog.Println(\"retry client was closed\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// TODO proper error handling\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tif receivers == 0 {\n\t\t\t\t// TODO: if there are no subscribers, we could pause this ticker for X seconds and try again\n\t\t\t}\n\t\tcase <-reporter.stopChan:\n\t\t\treporter.running = false\n\t\t\treturn\n\t\t}\n\t}\n}", "func Schedule(timeout time.Duration, noDelay bool, callback func()) chan<- struct{} {\n\tticker := time.NewTicker(timeout)\n\tquit := make(chan struct{})\n\tgo func() {\n\t\tif noDelay {\n\t\t\tcallback()\n\t\t}\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tcallback()\n\t\t\tcase <-quit:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn quit\n}", "func (f *Fetcher) processChan(outChanCommands <-chan Command, routineIndex int) {\n var (\n agent *robotstxt.Group\n ttl <-chan time.Time\n // add some random seconds for each channel\n delay = f.CrawlDelay\n httpClient = f.NewClient(true, true)\n httpClientCommands = 0\n restartClient = false\n )\n\n // tata tata\n logs.Info(\"Channel %d is starting..\", routineIndex)\n if routineIndex < 10 {\n time.Sleep(time.Duration(routineIndex) + 2*time.Second)\n }\n\nloop:\n for {\n select {\n case <-f.queue.cancelled:\n break loop\n case command, ok := <-outChanCommands:\n if !ok {\n logs.Info(\"Channel %d was closed, terminating..\", routineIndex)\n // Terminate this goroutine, channel is closed\n break loop\n }\n\n // was it stop during the wait? check again\n select {\n case <-f.queue.cancelled:\n logs.Info(\"Channel %d was cancelled, terminating..\", routineIndex)\n break loop\n default:\n // go on\n }\n\n restartClient = false\n\n logs.Debug(\"Channel %d received new command %s\", routineIndex, command.Url())\n\n if !f.DisablePoliteness {\n agent = f.getRobotAgent(command.Url())\n // Initialize the crawl delay\n if agent != nil && agent.CrawlDelay > 0 {\n delay = agent.CrawlDelay\n }\n }\n\n if command.HttpClient() == nil {\n command.SetHttpClient(httpClient)\n }\n\n if f.DisablePoliteness || agent == nil || agent.Test(command.Url().Path) {\n\n // path allowed, process the request\n res, err, isCached := f.Request(command, delay)\n\n if !isCached {\n httpClientCommands++\n\n var statusCode int\n if res != nil {\n statusCode = res.StatusCode\n }\n logs.Info(\"[%d][%d] %s %s\", routineIndex, statusCode, command.Method(), command.Url())\n }\n\n restartClient = f.visit(command, res, err, isCached)\n\n } else {\n // path disallowed by robots.txt\n f.visit(command, nil, ErrDisallowed, false)\n }\n\n f.snapshot.removeCommandInQueue(f.uniqueId(command.Url(), command.Method()))\n\n // Every time a command is received, reset the ttl channel\n ttl = time.After(f.WorkerIdleTTL)\n\n if restartClient || httpClientCommands > f.MaxCommandsPerClient {\n if f.LogLevel < logs.LevelNotice {\n fmt.Print(\"👅\")\n }\n logs.Info(\"Channel %d needs restart after %d commands..\", routineIndex, httpClientCommands)\n go f.processChan(outChanCommands, routineIndex)\n return\n }\n\n case <-ttl:\n if f.snapshot.queueLength() != 0 {\n logs.Debug(\"Channel %d was trying to timeout while queue length is %d\", routineIndex, f.snapshot.queueLength())\n ttl = time.After(f.WorkerIdleTTL)\n continue\n }\n logs.Alert(\"Channel %d with %d unique urls\", routineIndex, f.snapshot.uniqueUrlsLength())\n go f.Shutdown()\n break loop\n }\n }\n for range outChanCommands {\n }\n\n f.workersWaitGroup.Done()\n}", "func Orchestrate(name string) {\n\n\tvar wg sync.WaitGroup\n\n\tgo func() {\n\t\tfor {\n\t\t\twg.Add(1)\n\t\t\trunPool(wg, name)\n\t\t}\n\t}()\n\n\t//this works\n\ttermChan := make(chan os.Signal)\n\tsignal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)\n\n\t<-termChan //block until interrupted\n\n\twg.Done()\n}", "func (t *Broadcaster) Signal(ctx context.Context) error {\n\tif !t.mutex.RTryLock(ctx) {\n\t\treturn context.DeadlineExceeded\n\t}\n\tdefer t.mutex.RUnlock()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn context.DeadlineExceeded\n\tcase t.channel <- struct{}{}:\n\tdefault:\n\t}\n\n\treturn nil\n}", "func TestTCPSpuriousConnSetupCompletionWithCancel(t *testing.T) {\n\tmustHaveExternalNetwork(t)\n\n\tdefer dnsWaitGroup.Wait()\n\tt.Parallel()\n\tconst tries = 10000\n\tvar wg sync.WaitGroup\n\twg.Add(tries * 2)\n\tsem := make(chan bool, 5)\n\tfor i := 0; i < tries; i++ {\n\t\tsem <- true\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\ttime.Sleep(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))\n\t\t\tcancel()\n\t\t}()\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tvar dialer Dialer\n\t\t\t// Try to connect to a real host on a port\n\t\t\t// that it is not listening on.\n\t\t\t_, err := dialer.DialContext(ctx, \"tcp\", \"golang.org:3\")\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"Dial to unbound port succeeded on attempt %d\", i)\n\t\t\t}\n\t\t\t<-sem\n\t\t}(i)\n\t}\n\twg.Wait()\n}", "func ResetKillClock(t *time.Timer, d time.Duration) {\n\tif d == 0 {\n\t\treturn\n\t}\n\tif !t.Stop() {\n\t\t<-t.C\n\t}\n\tt.Reset(d)\n}", "func setupSigtermHandler() chan int {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan,\n\t\tsyscall.SIGTSTP,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGQUIT)\n\texitChan := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\ts := <-signalChan\n\t\t\tswitch s {\n\t\t\tcase syscall.SIGINT:\n\t\t\t\tlog.Println(\"signal received: SIGINT\")\n\t\t\t\tserverEnding() // cmd-c on mac\n\t\t\t\texitChan <- 0\n\n\t\t\t// called when a systemd service is stopped \"systemctl stop myservice\"\n\t\t\tcase syscall.SIGTERM:\n\t\t\t\tlog.Println(\"signal received: SIGTERM\")\n\t\t\t\tserverEnding()\n\t\t\t\texitChan <- 0\n\n\t\t\tcase syscall.SIGTSTP:\n\t\t\t\tlog.Println(\"signal received: SIGTSTP\")\n\t\t\t\tserverEnding()\n\t\t\t\texitChan <- 0\n\n\t\t\tcase syscall.SIGQUIT:\n\t\t\t\tlog.Println(\"signal received: SIGQUIT\")\n\t\t\t\tserverEnding()\n\t\t\t\texitChan <- 0\n\t\t\t\t\n\t\t\tdefault:\n\t\t\t\tlog.Println(\"signal received: Unknown signal\")\n\t\t\t\tserverEnding()\n\t\t\t\texitChan <- 1\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn exitChan\n}", "func (r *ResetReady) Signal() {\n\tr.lock.Lock()\n\tr.ready.Signal()\n\tr.lock.Unlock()\n}", "func (r *Renewer) Run(done <-chan struct{}) error {\n\tticker := time.NewTicker(time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := r.tick(); err != nil {\n\t\t\t\tticker.Stop()\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-done:\n\t\t\tticker.Stop()\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (t *Timer) tick(initialDelay time.Duration, fixedDelay time.Duration, fixedRate time.Duration, work func(t *Timer)) {\n\t// logger.Debug(\"start timer\")\n\tdefer func() {\n\t\t// logger.Debug(\"stop timer\")\n\t}()\n\ttime.Sleep(initialDelay)\n\tif t.close {\n\t\treturn\n\t}\n\tif fixedDelay <= 0 {\n\t\ttim := time.NewTicker(fixedRate)\n\t\tfor {\n\t\t\tif t.close {\n\t\t\t\ttim.Stop()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgox.Try(func() {\n\t\t\t\twork(t)\n\t\t\t}, func(i interface{}) {\n\t\t\t\tlogger.Error(\"error execute timer job:\", i)\n\t\t\t})\n\t\t\t<-tim.C\n\t\t}\n\t} else {\n\t\tfor {\n\t\t\tif t.close {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgox.Try(func() {\n\t\t\t\twork(t)\n\t\t\t}, func(i interface{}) {\n\t\t\t\tlogger.Error(\"error execute timer job:\", i)\n\t\t\t})\n\t\t\ttime.Sleep(fixedDelay)\n\t\t}\n\t}\n}", "func (self *ShadowRedisSlave) wait() {\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, os.Interrupt, os.Kill)\n\n\t// Block until a signal is received.\n\ts := <-sigChan\n\tlog.Debugf(\"Got signal:%v\", s)\n\tself.Close()\n}", "func (fti *fakeTimer) send() {\n\tdone := fti.renewDone()\n\n\tgo func() {\n\t\tselect {\n\t\tcase t := <-fti.inch:\n\t\t\tif fti.fun != nil {\n\t\t\t\tgo fti.fun()\n\t\t\t} else {\n\t\t\t\tfti.ch <- t\n\t\t\t}\n\t\tcase <-done:\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tselect {\n\t\tcase fti.inch <- func() time.Time {\n\t\t\tfti.T.Sleep(fti.triggerAt.Sub(fti.T.Now()))\n\t\t\treturn fti.triggerAt\n\t\t}():\n\t\tcase <-fti.stop:\n\t\t}\n\t\tclose(done)\n\t}()\n}", "func (gs *ShutdownHandler) Run() {\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-gs.gracefulStop:\n\t\t\tgs.log.Warnf(\"Received shutdown request - waiting (max %d seconds) to finish processing ...\", waitToKillTimeInSeconds)\n\t\tcase msg := <-gs.nodeSelfShutdown:\n\t\t\tgs.log.Warnf(\"Node self-shutdown: %s; waiting (max %d seconds) to finish processing ...\", msg, waitToKillTimeInSeconds)\n\t\t}\n\n\t\tgo func() {\n\t\t\tstart := time.Now()\n\t\t\tfor x := range time.Tick(1 * time.Second) {\n\t\t\t\tsecondsSinceStart := x.Sub(start).Seconds()\n\n\t\t\t\tif secondsSinceStart <= waitToKillTimeInSeconds {\n\t\t\t\t\tprocessList := \"\"\n\t\t\t\t\trunningBackgroundWorkers := gs.daemon.GetRunningBackgroundWorkers()\n\t\t\t\t\tif len(runningBackgroundWorkers) >= 1 {\n\t\t\t\t\t\tprocessList = \"(\" + strings.Join(runningBackgroundWorkers, \", \") + \") \"\n\t\t\t\t\t}\n\n\t\t\t\t\tgs.log.Warnf(\"Received shutdown request - waiting (max %d seconds) to finish processing %s...\", waitToKillTimeInSeconds-int(secondsSinceStart), processList)\n\t\t\t\t} else {\n\t\t\t\t\tgs.log.Fatal(\"Background processes did not terminate in time! Forcing shutdown ...\")\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgs.daemon.ShutdownAndWait()\n\t}()\n}", "func (e *AutoResetEvent) Signal() {\n\te.l.Lock()\n\tif len(e.c) == 0 {\n\t\te.c <- struct{}{}\n\t}\n\te.l.Unlock()\n}", "func waitForFinished() {\n\tch := make(chan struct{}) // blocking channel with no data\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)\n\t\tclose(ch)\n\t\tfmt.Println(\"worker: send signal by closing channel\")\n\t}()\n\n\t_, wd := <-ch // want for slgnal\n\tfmt.Println(\"manager: signal received: WithDataFlag =\", wd)\n\n\ttime.Sleep(time.Second)\n\tfmt.Println(\"------------ done ---------\")\n}", "func (r *Runner) Run(signals <-chan os.Signal, ready chan<- struct{}) error {\n\tlogger := r.logger.Session(\"garden-health\")\n\thealthcheckTimeout := r.clock.NewTimer(r.timeoutInterval)\n\thealthcheckComplete := make(chan error, 1)\n\n\tlogger.Info(\"starting\")\n\n\tgo r.healthcheckCycle(logger, healthcheckComplete)\n\n\tselect {\n\tcase signal := <-signals:\n\t\tlogger.Info(\"signalled\", lager.Data{\"signal\": signal.String()})\n\t\treturn nil\n\n\tcase <-healthcheckTimeout.C():\n\t\tr.setUnhealthy(logger)\n\t\tr.checker.Cancel(logger)\n\t\tlogger.Info(\"timed-out\")\n\t\treturn HealthcheckTimeoutError{}\n\n\tcase err := <-healthcheckComplete:\n\t\tif err != nil {\n\t\t\tr.setUnhealthy(logger)\n\t\t\treturn err\n\t\t}\n\t\thealthcheckTimeout.Stop()\n\t}\n\n\tr.setHealthy(logger)\n\n\tclose(ready)\n\tlogger.Info(\"started\")\n\n\tstartHealthcheck := r.clock.NewTimer(r.checkInterval)\n\temitInterval := r.clock.NewTicker(r.emissionInterval)\n\tdefer emitInterval.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase signal := <-signals:\n\t\t\tlogger.Info(\"signalled-complete\", lager.Data{\"signal\": signal.String()})\n\t\t\treturn nil\n\n\t\tcase <-startHealthcheck.C():\n\t\t\thealthcheckTimeout.Reset(r.timeoutInterval)\n\t\t\tgo r.healthcheckCycle(logger, healthcheckComplete)\n\n\t\tcase <-healthcheckTimeout.C():\n\t\t\tr.setUnhealthy(logger)\n\t\t\tr.checker.Cancel(logger)\n\t\t\tr.metronClient.SendMetric(CellUnhealthyMetric, 1)\n\n\t\tcase <-emitInterval.C():\n\t\t\tr.emitUnhealthyCellMetric(logger)\n\n\t\tcase err := <-healthcheckComplete:\n\t\t\ttimeoutOk := healthcheckTimeout.Stop()\n\t\t\tswitch err.(type) {\n\t\t\tcase nil:\n\t\t\t\tif timeoutOk {\n\t\t\t\t\tr.setHealthy(logger)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tr.setUnhealthy(logger)\n\t\t\t}\n\n\t\t\tstartHealthcheck.Reset(r.checkInterval)\n\t\t}\n\t}\n}", "func (s *StanServer) performAckExpirationRedelivery(sub *subState, isStartup bool) {\n\t// If server has been shutdown, clear timer and be done (will happen only in tests)\n\ts.mu.RLock()\n\tshutdown := s.shutdown\n\ts.mu.RUnlock()\n\tif shutdown {\n\t\tsub.Lock()\n\t\tsub.clearAckTimer()\n\t\tsub.Unlock()\n\t\treturn\n\t}\n\tsub.Lock()\n\t// Subscriber could have been closed\n\tif sub.ackTimer == nil {\n\t\tsub.Unlock()\n\t\treturn\n\t}\n\t// Sort our messages outstanding from acksPending, grab some state and unlock.\n\tsortedPendingMsgs := sub.makeSortedPendingMsgs()\n\tif len(sortedPendingMsgs) == 0 {\n\t\tsub.clearAckTimer()\n\t\tsub.Unlock()\n\t\treturn\n\t}\n\texpTime := int64(sub.ackWait)\n\tsubject := sub.subject\n\tqs := sub.qstate\n\tclientID := sub.ClientID\n\tsubID := sub.ID\n\tif qs == nil {\n\t\t// If the client has some failed heartbeats, ignore this request.\n\t\tif sub.hasFailedHB {\n\t\t\t// Reset the timer\n\t\t\tif s.isStandaloneOrLeader() {\n\t\t\t\tsub.ackTimer.Reset(sub.ackWait)\n\t\t\t}\n\t\t\tsub.Unlock()\n\t\t\tif s.debug {\n\t\t\t\ts.log.Debugf(\"[Client:%s] Skipping redelivery to subid=%d due to missed client heartbeat\", clientID, subID)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tsub.Unlock()\n\n\tc := s.channels.get(subject)\n\tif c == nil {\n\t\ts.log.Errorf(\"[Client:%s] Aborting redelivery to subid=%d for non existing channel %s\", clientID, subID, subject)\n\t\tsub.Lock()\n\t\tsub.clearAckTimer()\n\t\tsub.Unlock()\n\t\treturn\n\t}\n\n\tnow := time.Now().UnixNano()\n\t// limit is now plus a buffer of 15ms to avoid repeated timer callbacks.\n\tlimit := now + int64(15*time.Millisecond)\n\n\tvar (\n\t\tpick *subState\n\t\tsent bool\n\t\tfoundWithZero bool\n\t\tnextExpirationTime int64\n\t)\n\n\t// We will move through acksPending(sorted) and see what needs redelivery.\n\tfor _, pm := range sortedPendingMsgs {\n\t\tm := s.getMsgForRedelivery(c, sub, pm.seq)\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// If we found any pm.expire with 0 in the array (due to a server restart),\n\t\t// ensure that all have now an expiration set, then reschedule right away.\n\t\tif foundWithZero || pm.expire == 0 {\n\t\t\tfoundWithZero = true\n\t\t\tif pm.expire == 0 {\n\t\t\t\tsub.Lock()\n\t\t\t\t// Is message still pending?\n\t\t\t\tif _, present := sub.acksPending[pm.seq]; present {\n\t\t\t\t\tsub.acksPending[pm.seq] = m.Timestamp + expTime\n\t\t\t\t}\n\t\t\t\tsub.Unlock()\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// If this message has not yet expired, reset timer for next callback\n\t\tif pm.expire > limit {\n\t\t\tnextExpirationTime = pm.expire\n\t\t\tif s.trace {\n\t\t\t\ts.log.Tracef(\"[Client:%s] Redelivery for subid=%d, skipping seq=%d\", clientID, subID, m.Sequence)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Flag as redelivered.\n\t\tm.Redelivered = true\n\n\t\t// Handle QueueSubscribers differently, since we will choose best subscriber\n\t\t// to redeliver to, not necessarily the same one.\n\t\t// However, on startup, resends only to member that had previously this message\n\t\t// otherwise this could cause a message to be redelivered to multiple members.\n\t\tif qs != nil && !isStartup {\n\t\t\tqs.Lock()\n\t\t\tsub.Lock()\n\t\t\tmsgPending := sub.isMsgStillPending(m)\n\t\t\tsub.Unlock()\n\t\t\tif msgPending {\n\t\t\t\tpick, sent = s.sendMsgToQueueGroup(qs, m, forceDelivery)\n\t\t\t}\n\t\t\tqs.Unlock()\n\t\t\tif msgPending && pick == nil {\n\t\t\t\ts.log.Errorf(\"[Client:%s] Unable to find queue subscriber for subid=%d\", clientID, subID)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If the message is redelivered to a different queue subscriber,\n\t\t\t// we need to process an implicit ack for the original subscriber.\n\t\t\t// We do this only after confirmation that it was successfully added\n\t\t\t// as pending on the other queue subscriber.\n\t\t\tif msgPending && pick != sub && sent {\n\t\t\t\ts.processAck(c, sub, m.Sequence, false)\n\t\t\t}\n\t\t} else {\n\t\t\tqsLock(qs)\n\t\t\tsub.Lock()\n\t\t\tif sub.isMsgStillPending(m) {\n\t\t\t\ts.sendMsgToSub(sub, m, forceDelivery)\n\t\t\t}\n\t\t\tsub.Unlock()\n\t\t\tqsUnlock(qs)\n\t\t}\n\t}\n\tif foundWithZero {\n\t\t// Restart expiration now that ackPending map's expire values are properly\n\t\t// set. Note that messages may have been added/removed in the meantime.\n\t\ts.performAckExpirationRedelivery(sub, isStartup)\n\t\treturn\n\t}\n\n\t// Adjust the timer\n\tsub.adjustAckTimer(nextExpirationTime)\n}", "func Tick(d Duration) <-chan Time {}", "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 goroutine1() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(time.Second):\n\t\t\tlog.Println(\"heartbeat\")\n\t\tcase <-shutdown.InProgress():\n\t\t\tlog.Println(\"shutdown (1)\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (collector *Collector) resetTimeout() {\n\t// We only need to do something if there actually is a ticker (ie: if an interval was specified)\n\tif collector.ticker != nil {\n\t\t// Stop the ticker so it can be garbage collected\n\t\tcollector.ticker.Stop()\n\n\t\t// From everything I've read the only real way to reset a ticker is to recreate it\n\t\tcollector.ticker = time.NewTicker(collector.config.Timeout.Interval)\n\t\tcollector.timeoutChannel = collector.ticker.C\n\t}\n}", "func (c *Cond) Signal() {\n\tc.Do(func() {})\n}", "func (node *Node) startElectionTimer() {\n\telectionTimeout := node.randElectionTimeout()\n\n\tnode.mu.Lock()\n\ttimerStartTerm := node.currentTerm\n\tnode.mu.Unlock()\n\n\tticker := time.NewTicker(10 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\t// This loops wakes every 10ms and checks if the conditions are conducive\n\t// for starting an election. This is not the most efficient and\n\t// theoretically we could just wake up every electionTimeout, but this\n\t// reduces testability/log readability.\n\tfor {\n\t\t<-ticker.C\n\n\t\tnode.mu.Lock()\n\t\tif node.state != candidate && node.state != follower {\n\t\t\tlog.Printf(\"The node is in the %s state, no need to run election\", node.state)\n\t\t\tnode.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\t// If the timer was started in a previous term then we can back off\n\t\t// because a newer go routine would have been spawned cooresponding to\n\t\t// the new term.\n\t\tif node.currentTerm != timerStartTerm {\n\t\t\tlog.Printf(\"Election timer started in term %d but now node has latest term %d, so we can back off\", timerStartTerm, node.currentTerm)\n\t\t\treturn\n\t\t}\n\n\t\t// Run an election if we have reached the election timeout.\n\t\tif timePassed := time.Since(node.timeSinceTillLastReset); timePassed > electionTimeout {\n\t\t\tnode.runElection()\n\t\t\tnode.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tnode.mu.Unlock()\n\t}\n}", "func ticker(s string) func() error {\n\n\treturn func() error {\n\n\t\tTIME += 1\n\n\t\treturn nil\n\t}\n}", "func startReissRunner() {\n\tif !cfg.CS.DisableCorePush {\n\t\tcorePusher = periodic.StartPeriodicTask(\n\t\t\t&reiss.CorePusher{\n\t\t\t\tLocalIA: itopo.Get().ISD_AS,\n\t\t\t\tTrustDB: state.TrustDB,\n\t\t\t\tMsger: msgr,\n\t\t\t},\n\t\t\tperiodic.NewTicker(time.Hour),\n\t\t\ttime.Minute,\n\t\t)\n\t\tcorePusher.TriggerRun()\n\t}\n\tif !cfg.CS.AutomaticRenewal {\n\t\tlog.Info(\"Reissue disabled, not starting reiss task.\")\n\t\treturn\n\t}\n\tif itopo.Get().Core {\n\t\tlog.Info(\"Starting periodic reiss.Self task\")\n\t\treissRunner = periodic.StartPeriodicTask(\n\t\t\t&reiss.Self{\n\t\t\t\tMsgr: msgr,\n\t\t\t\tState: state,\n\t\t\t\tIA: itopo.Get().ISD_AS,\n\t\t\t\tIssTime: cfg.CS.IssuerReissueLeadTime.Duration,\n\t\t\t\tLeafTime: cfg.CS.LeafReissueLeadTime.Duration,\n\t\t\t\tCorePusher: corePusher,\n\t\t\t},\n\t\t\tperiodic.NewTicker(cfg.CS.ReissueRate.Duration),\n\t\t\tcfg.CS.ReissueTimeout.Duration,\n\t\t)\n\t\treturn\n\t}\n\tlog.Info(\"Starting periodic reiss.Requester task\")\n\treissRunner = periodic.StartPeriodicTask(\n\t\t&reiss.Requester{\n\t\t\tMsgr: msgr,\n\t\t\tState: state,\n\t\t\tIA: itopo.Get().ISD_AS,\n\t\t\tLeafTime: cfg.CS.LeafReissueLeadTime.Duration,\n\t\t\tCorePusher: corePusher,\n\t\t},\n\t\tperiodic.NewTicker(cfg.CS.ReissueRate.Duration),\n\t\tcfg.CS.ReissueTimeout.Duration,\n\t)\n}", "func After(d Duration) <-chan Time {}", "func (s *SlaveHealthChecker) Start() <-chan time.Time {\n\tgo func() {\n\t\tt := time.NewTicker(s.checkDuration)\n\t\tdefer t.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-t.C:\n\t\t\t\tselect {\n\t\t\t\tcase <-s.stop:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\t// continue\n\t\t\t\t}\n\t\t\t\tif paused, slavepid := func() (x bool, y upid.UPID) {\n\t\t\t\t\ts.RLock()\n\t\t\t\t\tdefer s.RUnlock()\n\t\t\t\t\tx = s.paused\n\t\t\t\t\tif s.slaveUPID != nil {\n\t\t\t\t\t\ty = *s.slaveUPID\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}(); !paused {\n\t\t\t\t\ts.doCheck(slavepid)\n\t\t\t\t}\n\t\t\tcase <-s.stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn s.ch\n}", "func keepSendingSubscriptionForced(shutdownSignal <-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-shutdownSignal:\n\t\t\treturn\n\t\tcase <-time.After(1 * time.Minute):\n\t\t\tsendSubscriptions(true)\n\t\t}\n\t}\n}", "func (f *FakeWorkQueue) ShutDown() {}", "func keepSendingSubscriptionIfNeeded(shutdownSignal <-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-shutdownSignal:\n\t\t\treturn\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tsendSubscriptions(false)\n\t\t}\n\t}\n}", "func setupWaitingChannel() (ch chan os.Signal) {\n\tch = make(chan os.Signal)\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)\n\treturn\n}", "func (c *CumulativeClock) Reset() {\n\tc.Set(c.start)\n}", "func (lp *LimitedCounter) Await() {\n\tlp.wg.Wait()\n}", "func (t *SimpleContentionTracker) Run(stopCh <-chan struct{}) {\n\tticker := time.NewTicker(t.expires * 2)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tt.flush()\n\t\t}\n\t}\n}", "func (vm *vm) cassetteRiseInterrupt() {\n\tvm.cassetteRiseInterruptCount++\n\tvm.irqLatch = (vm.irqLatch &^ cassetteRiseIrqMask) |\n\t\t(vm.irqMask & cassetteRiseIrqMask)\n}", "func (k *k8sService) runUntilCancel() {\n\twatcher, err := k.strClient.CoreV1().Pods(defaultNS).Watch(metav1.ListOptions{})\n\tii := 0\n\tfor err != nil {\n\t\tselect {\n\t\tcase <-k.ctx.Done():\n\t\t\tk.Done()\n\t\t\tlog.Infof(\"k8sService main loop runUntilCancel canceled\")\n\t\t\treturn\n\t\tcase <-time.After(time.Second):\n\t\t\twatcher, err = k.strClient.CoreV1().Pods(defaultNS).Watch(metav1.ListOptions{})\n\t\t\tii++\n\t\t\tif ii%10 == 0 {\n\t\t\t\tlog.Errorf(\"Waiting for pod watch to succeed for %v seconds, last err: %v\", ii, err)\n\t\t\t}\n\t\t}\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-k.ctx.Done():\n\t\t\tlog.Infof(\"k8sService main loop runUntilCancel canceled\")\n\t\t\twatcher.Stop()\n\t\t\tk.Done()\n\t\t\treturn\n\t\tcase mod := <-k.modCh:\n\t\t\tlog.Infof(\"Deploying mod %v\", mod)\n\t\t\tk.deployModule(&mod)\n\t\tcase event, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\t// restart this routine.\n\t\t\t\tlog.Infof(\"k8sService error receiving on K8s Apiserver watch channel, restarting main loop\")\n\t\t\t\tgo k.runUntilCancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t\te := types.K8sPodEvent{\n\t\t\t\tPod: event.Object.(*v1.Pod),\n\t\t\t}\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added:\n\t\t\t\te.Type = types.K8sPodAdded\n\t\t\tcase watch.Deleted:\n\t\t\t\te.Type = types.K8sPodDeleted\n\t\t\tcase watch.Modified:\n\t\t\t\te.Type = types.K8sPodModified\n\t\t\t}\n\n\t\t\tif err := k.notify(e); err != nil {\n\t\t\t\tlog.Errorf(\"Failed to notify %+v with error: %v\", e, err)\n\t\t\t}\n\t\tcase <-time.After(interval):\n\t\t\tif k.isLeader {\n\t\t\t\tfoundModules, err := getModules(k.client)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"k8sService error getting modules from K8s ApiServer: %v\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmodulesToDeploy := make(map[string]protos.Module)\n\t\t\t\tfor name, module := range k8sModules {\n\t\t\t\t\tif module.Spec.Disabled {\n\t\t\t\t\t\t/*upon CMD restart disabled flag is set to true and pegasus deployment is deleted, allowing it to be redeployed */\n\t\t\t\t\t\tif _, found := foundModules[name]; found {\n\t\t\t\t\t\t\tdelete(foundModules, name)\n\t\t\t\t\t\t\tmodule.Spec.Disabled = false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := foundModules[name]; !ok {\n\t\t\t\t\t\tmodulesToDeploy[name] = module\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete(foundModules, name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk.deployModules(modulesToDeploy)\n\t\t\t\tk.deleteModules(foundModules)\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *replicationState) tick(n int) {\n\tp.heartbeat -= n\n}", "func startRoutine(channel chan CommandInfo, stopChannel chan string, address string, readWelcome bool) {\n\tconn, err := getConnection(address, readWelcome)\n\tif err != nil {\n\t\tlogError(fmt.Sprintf(\"failed to open connection with %v: %v\", address, err.Error()))\n\t\tstopChannel <- address\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\ttimer := time.NewTimer(20 * time.Second)\n\tdelayTimer := time.NewTimer(0 * time.Second)\n\n\tfor {\n\t\t<-delayTimer.C\n\t\tselect {\n\t\tcase command, ok := <-channel:\n\t\t\tif !ok {\n\t\t\t\tcolor.Set(color.FgHiCyan)\n\t\t\t\tlog.L.Infof(\"Closing connection with %v\", address)\n\t\t\t\tconn.Close()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresp, err := SendCommand(conn, command.Address, command.Command)\n\t\t\tcommand.ResponseChannel <- Response{Response: resp, Err: err}\n\n\t\t\ttimer.Reset(20 * time.Second)\n\t\t\tdelayTimer.Reset(150 * time.Millisecond)\n\t\tcase <-timer.C:\n\t\t\tcolor.Set(color.FgHiCyan)\n\t\t\tlog.L.Infof(\"Connection with %v expired, sending close message\", address)\n\t\t\tcolor.Unset()\n\n\t\t\t//explicitly close it\n\t\t\tconn.Close()\n\t\t\tstopChannel <- address\n\t\t}\n\t}\n}", "func (ts *TimeService) Run() {\n\tfor {\n\t\tselect {\n\t\tcase <-ts.Dead:\n\t\t\t// let's close this channel to make sure we can no longer attempt to write to it\n\t\t\tclose(ts.ReqChan)\n\t\t\treturn\n\t\tcase req := <-ts.ReqChan:\n\t\t\tprocessingTime := time.Duration(ts.AvgResponseTime+1.0-rand.Float64()) * time.Second\n\t\t\ttime.Sleep(processingTime)\n\t\t\treq.RspChan <- time.Now()\n\t\t}\n\t}\n}", "func main() {\n testService := NewService(\"test\", methods)\n\n start := time.Now()\n sigint := make(chan os.Signal, 1)\n signal.Notify(sigint, os.Interrupt)\n\n for {\n select {\n\n case <-testService.Quit:\n fmt.Println(\"Quit\")\n return\n\n case <-sigint:\n fmt.Println(\"Quit\")\n since := time.Since(start)\n fmt.Println(since)\n fmt.Println(testService.NResponses)\n fmt.Println(float64(testService.NResponses) / since.Seconds())\n return\n\n }\n }\n}", "func (r *realTimer) C() <-chan time.Time {\n\treturn r.timer.C\n}", "func (b *B) ResetTimer()", "func (p *promise) Signal(waitChan chan Controller) Promise {\n\tp.Always(func(p2 Controller) {\n\t\twaitChan <- p2\n\t})\n\n\treturn p\n}", "func After(d time.Duration) <-chan time.Time {\n\tif d <= 0 {\n\t\treturn nil\n\t}\n\n\treturn defaultTimerWheel.After(d)\n}", "func (j *DSRocketchat) CalculateTimeToReset(ctx *Ctx, rateLimit, rateLimitReset int) (seconds int) {\n\tseconds = (int(int64(rateLimitReset)-(time.Now().UnixNano()/int64(1000000))) / 1000) + 1\n\tif seconds < 0 {\n\t\tseconds = 0\n\t}\n\tif ctx.Debug > 1 {\n\t\tPrintf(\"CalculateTimeToReset(%d,%d) -> %d\\n\", rateLimit, rateLimitReset, seconds)\n\t}\n\treturn\n}", "func (j *DSGitHub) CalculateTimeToReset(ctx *Ctx, rateLimit, rateLimitReset int) (seconds int) {\n\tseconds = rateLimitReset\n\treturn\n}", "func (p *Pool) masterRoutine() {\n\tidleQueue := make(chan chan Runnable)\n\ttryFork := make(chan bool, 1)\n\tdefer close(idleQueue)\n\tdefer close(tryFork)\n\n\tfor {\n\t\tselect {\n\t\t// Firstly, master routine try to pop a task from taskQueue.\n\t\tcase task, ok := <-p.taskQueue:\n\t\t\tif !ok {\n\t\t\t\t// If taskQueue was closed, master routine will shutdown all the routines gracefully.\n\t\t\t\t// In the for loop, we remove all the down routines until the routine pool is empty.\n\t\t\t\t// first, define a wait time duration for the long running task\n\t\t\t\tvar wait time.Duration\n\t\t\t\tfor 0 < p.removeDownRoutine() {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase taskCh := <-idleQueue:\n\t\t\t\t\t\t// close the taskCh, let the routine return\n\t\t\t\t\t\t// the routine status will be set to down\n\t\t\t\t\t\tclose(taskCh)\n\t\t\t\t\t\twait = 0\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// if working routine exists,\n\t\t\t\t\t\t// we just sleep for a while to wait for it finishing.\n\t\t\t\t\t\t// the wait duration increase if no idleTaskQueue popped out.\n\t\t\t\t\t\ttime.Sleep(wait * time.Millisecond)\n\t\t\t\t\t\tif wait < 1000 {\n\t\t\t\t\t\t\twait++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// if all the routines shuteddown successfully, send the finish signal.\n\t\t\t\tp.termSignal <- true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Secondly, master routine will try to pop a taskCh,\n\t\t\t// then push the task into the taskCh, let the routine handle it.\n\t\t\ttryFork <- true\n\t\tpopRoutineLoop:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase taskCh := <-idleQueue:\n\t\t\t\t\ttaskCh <- task // If taskCh select successful, just push task into the routine.\n\t\t\t\t\t<-tryFork // clear the tryFork for the next newly task\n\t\t\t\t\tbreak popRoutineLoop\n\n\t\t\t\tdefault:\n\t\t\t\t\t// If no standby taskCh, we try to fork a new one.\n\t\t\t\t\t// but fork should do only onetime\n\t\t\t\t\tfor {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\t// Fork for first time, the second time will block\n\t\t\t\t\t\tcase <-tryFork:\n\t\t\t\t\t\t\tp.fork(idleQueue)\n\n\t\t\t\t\t\t\t// If new routine truly forked, just push the task into it\n\t\t\t\t\t\t\t// But if the pool is full of working routine,\n\t\t\t\t\t\t\t//there is nothing to do but wait.\n\t\t\t\t\t\tcase taskCh := <-idleQueue:\n\t\t\t\t\t\t\ttaskCh <- task\n\n\t\t\t\t\t\t\tif 0 < len(tryFork) {\n\t\t\t\t\t\t\t\t<-tryFork\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak popRoutineLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (srv *IOServerInstance) dPrepShutdown(ctx context.Context) *system.MemberResult {\n\trank, err := srv.GetRank()\n\tif err != nil {\n\t\treturn nil // no rank to return result for\n\t}\n\n\tif !srv.isReady() {\n\t\treturn system.NewMemberResult(rank, \"prep shutdown\", nil, system.MemberStateStopped)\n\t}\n\n\tresChan := make(chan *system.MemberResult)\n\tgo func() {\n\t\tdresp, err := srv.CallDrpc(drpc.ModuleMgmt, drpc.MethodPrepShutdown, nil)\n\t\tresChan <- drespToMemberResult(rank, \"prep shutdown\", dresp, err,\n\t\t\tsystem.MemberStateStopping)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tif ctx.Err() == context.DeadlineExceeded {\n\t\t\treturn system.NewMemberResult(rank, \"prep shutdown\", ctx.Err(),\n\t\t\t\tsystem.MemberStateUnresponsive)\n\t\t}\n\t\treturn nil // shutdown\n\tcase result := <-resChan:\n\t\treturn result\n\t}\n}", "func cancelCheck(ctx context.Context, pipelineId uuid.UUID, cancelChannel chan bool, cacheService cache.Cache) {\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\tcase _ = <-ticker.C:\n\t\t\tcancel, err := cacheService.GetValue(ctx, pipelineId, cache.Canceled)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif cancel.(bool) {\n\t\t\t\tcancelChannel <- true\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (cs *cpuState) runTimerCycle() {\n\n\tcs.TimerDivCycles++\n\n\tif !cs.TimerOn {\n\t\treturn\n\t}\n\n\tcycleCount := [...]uint{\n\t\t1024, 16, 64, 256,\n\t}[cs.TimerFreqSelector]\n\tif cs.Cycles&(cycleCount-1) == 0 {\n\t\tcs.TimerCounterReg++\n\t\tif cs.TimerCounterReg == 0 {\n\t\t\tcs.TimerCounterReg = cs.TimerModuloReg\n\t\t\tcs.TimerIRQ = true\n\t\t}\n\t}\n}", "func (n *Sub) asyncRtyproc() {\n\tvar err error\n\tfor {\n\t\tif n.Closed() {\n\t\t\treturn\n\t\t}\n\t\trty, ok := <-n.asyncRty\n\t\tcountProm.Decr(_opConsumerFail, n.w.Group, n.w.Topic)\n\t\tif !ok {\n\t\t\tlog.Error(\"async chan close \")\n\t\t\treturn\n\t\t}\n\t\tfor i := rty.index; i < len(n.w.Callbacks); i++ {\n\t\t\terr = n.retry(n.w.Callbacks[i].URL, rty.msg, _asyncCall)\n\t\t\tif err != nil {\n\t\t\t\tn.addAsyncRty(rty.id, rty.msg, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\t// if ok,restart consumer.\n\t\t\tn.stop = false\n\t\t\tn.delBackup(rty.id)\n\t\t}\n\t}\n}", "func timer(testT int, consumerChan chan bool) {\n\ttime.Sleep(time.Second * time.Duration(testT))\n\tconsumerChan <- true\n}", "func main() {\n\tquit := make(chan bool)\n\n\tgo func() {\n\t\ti := 1\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-quit:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"Running routine - iter %d\\n\", i)\n\t\t\t\ti = i + 1\n\t\t\t\ttime.Sleep(3 * time.Second)\n\t\t\t}\n\t\t}\n\t}()\n\t// something happens ...\n\ttime.Sleep(9 * time.Second)\n\tfmt.Println(\"Ticker Stop - quit <- true\")\n\tquit <- true\n}", "func gracefulShutdown(exitSig <-chan os.Signal, done chan error, timeout time.Duration) {\n\t// start_shutdown1 OMIT\n\tsig := <-exitSig // same as before // HL\n\tfmt.Printf(\"received signal: %q, starting graceful shutdown...\\n\",\n\t\tsig.String())\n\n\t// start timeout countdown // HL\n\tctx, cancel := context.WithTimeout(context.Background(), timeout) // HL\n\tdefer cancel()\n\t// end_shutdown1 OMIT\n\n\t// start_shutdown_timeout OMIT\n\tgo func() {\n\t\t<-ctx.Done() // wait until context timeout or it's cancelled // HL\n\t\tif err := ctx.Err(); err != nil {\n\t\t\tdone <- fmt.Errorf(\"graceful shutdown failed: %w\", err) // HL\n\t\t}\n\t}()\n\t// end_shutdown_timeout OMIT\n\n\t// start_shutdown_wg OMIT\n\t// tl;dr: a WaitGroup is a counter which can increase and decrease. // HL\n\t// Calling WaitGroup.Wait() will block until the counter is ZERO // HL\n\twg := &sync.WaitGroup{}\n\n\twg.Add(4) // adds 4 to the counter // HL\n\tgo closeDependency(ctx, 0, wg)\n\tgo closeDependency(ctx, 1, wg)\n\tgo closeDependency(ctx, 2, wg)\n\tgo closeDependency(ctx, 3, wg)\n\n\twg.Wait() // Wait() will return when WaitGroup counter == 0 // HL\n\t// end_shutdown_wg OMIT\n\tfmt.Println(\"shutdown complete\")\n\tdone <- nil\n}", "func (u NoopUpdater) ResetRemaining() {}", "func Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n}", "func (pomo *Pomo) Start() {\n\n\t// Start the goroutine if not already running.\n\tif pomo.Status == OFF {\n\n\t\tpomo.Status = ON\n\t\tpomo.Notified = false\n\n\t\t// goroutine cancelation channel\n\t\tcancel := make(chan bool)\n\n\t\tgo func() {\n\n\t\t\tfor {\n\n\t\t\t\tselect {\n\n\t\t\t\tcase <-cancel:\n\t\t\t\t\tpomo.Status = OFF\n\t\t\t\t\treturn\n\n\t\t\t\tdefault:\n\t\t\t\t\tpomo.Time -= time.Second\n\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}()\n\n\t\tpomo.Cancel = cancel\n\t}\n}", "func (m *etcdMinion) periodicRunner() {\n\tschedule := time.Minute * 5\n\tticker := time.NewTicker(schedule)\n\tlog.Printf(\"Periodic scheduler set to run every %s\\n\", schedule)\n\n\tfor {\n\t\tselect {\n\t\tcase <-m.done:\n\t\t\tbreak\n\t\tcase now := <-ticker.C:\n\t\t\t// Run periodic jobs\n\t\t\tm.classify()\n\t\t\tm.checkQueue()\n\t\t\tm.SetLastseen(now.Unix())\n\t\t}\n\t}\n}", "func (s *Stopper) ShouldQuiesce() <-chan struct{} {\n\tif s == nil {\n\t\t// A nil stopper will never signal ShouldQuiesce, but will also never panic.\n\t\treturn nil\n\t}\n\treturn s.quiescer\n}", "func (s *Stopper) ShouldQuiesce() <-chan struct{} {\n\tif s == nil {\n\t\t// A nil stopper will never signal ShouldQuiesce, but will also never panic.\n\t\treturn nil\n\t}\n\treturn s.quiescer\n}", "func setupSignalHandler() <-chan struct{} {\n\tstopCh := make(chan struct{})\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\t<-ch\n\t\tclose(stopCh)\n\t\t<-ch\n\t\tos.Exit(1)\n\t}()\n\treturn stopCh\n}", "func (c *Clock) AfterReconnectTimeout() <-chan chan struct{} { return newClockChan(c.ReconnectTimeout) }", "func someHandler() {\n\t// Create the ctx\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// Do some stuff\n\tgo doStuff(ctx)\n\n\t// Cancel after 10 seconds\n\ttime.Sleep(10 * time.Second)\n\tcancel()\n\n\t// Waiting for doStuff to finish\n\t<-ch\n}", "func initGracefulStop() context.Context {\n\tgracefulStop := make(chan os.Signal, 1)\n\tsignal.Notify(gracefulStop, syscall.SIGINT, syscall.SIGTERM)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tsig := <-gracefulStop\n\t\tlog.Warnf(\"Received signal %q. Exiting as soon as possible!\", sig)\n\t\tcancel()\n\t}()\n\n\treturn ctx\n}", "func (hb *heartbeat) Beat() error {\n\tctx, err := func() (ctx context.Context, err error) {\n\t\thb.lock.Lock()\n\t\tdefer hb.lock.Unlock()\n\t\tif hb.cancel != nil {\n\t\t\terr = ErrRunning\n\t\t} else {\n\t\t\tctx, hb.cancel = context.WithCancel(context.Background())\n\t\t}\n\t\treturn\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\thb.lock.Lock()\n\t\tdefer hb.lock.Unlock()\n\t\thb.cancel()\n\t\thb.cancel = nil\n\t}()\n\n\t// get the value if we don't have it\n\tdeadline, _ := context.WithTimeout(ctx, hb.frequency)\n\thb.value, err = hb.get(deadline)\n\tif isEtcdErrorCode(err, etcd.ErrorCodeKeyNotFound) {\n\t\treturn ErrNotFound\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// set the ttl since the first tick is not immediate\n\terr = hb.set(deadline)\n\tif isEtcdErrorCode(err, etcd.ErrorCodeKeyNotFound) {\n\t\treturn ErrDeleted\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// set ttl on every timer tick\n\tticker := time.NewTicker(hb.frequency)\n\tfor {\n\t\tselect {\n\t\tcase tick := <-ticker.C:\n\t\t\tdeadline, _ := context.WithDeadline(ctx, tick.Add(hb.frequency))\n\t\t\terr := hb.set(deadline)\n\t\t\tif inClusterError(err, context.Canceled) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif 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 Trap() chan os.Signal {\r\n\t// signal channel\r\n\tsigs := make(chan os.Signal, 1)\r\n\t// listen channel\r\n\tdone := make(chan os.Signal)\r\n\r\n\t// trap signals\r\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\r\n\r\n\t// signal handler\r\n\tgo func() {\r\n\t\t// allow signals to be continually trapped\r\n\t\tfor {\r\n\t\t\tdone <- <-sigs\r\n\t\t}\r\n\t}()\r\n\r\n\t// return channel to listen on\r\n\treturn done\r\n}", "func signal_disable(uint32) {}", "func (this *RedisSequencer) reset() error {\n\tlockKey := this.getLockName()\n\tres := this.client.SetNX(lockKey, \"\", 10*time.Second)\n\tif res.Err() != nil {\n\t\treturn res.Err()\n\t}\n\tif !res.Val() {\n\t\treturn ErrLockNotGranted\n\t}\n\tthis.client.Watch(func(tx *redis.Tx) error {\n\t\tn64, err := tx.Get(this.getName()).Int64()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn := int(n64)\n\t\ttx.Pipelined(func(pipe redis.Pipeliner) error {\n\t\t\tif (!this.isReverse && n > this.limit) || (this.isReverse && n < this.limit) {\n\t\t\t\t_ = pipe.Set(this.getName(), this.getStart(), 0)\n\t\t\t}\n\t\t\tpipe.Del(lockKey)\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t}, lockKey)\n\n\treturn nil\n}", "func (k *KubernetesExecutor) doShutdown(driver bindings.ExecutorDriver) {\n\tdefer func() {\n\t\tlog.Errorf(\"exiting with unclean shutdown: %v\", recover())\n\t\tif k.exitFunc != nil {\n\t\t\tk.exitFunc(1)\n\t\t}\n\t}()\n\n\t(&k.state).transitionTo(terminalState)\n\n\t// signal to all listeners that this KubeletExecutor is done!\n\tclose(k.done)\n\n\tif k.shutdownAlert != nil {\n\t\tfunc() {\n\t\t\tutil.HandleCrash()\n\t\t\tk.shutdownAlert()\n\t\t}()\n\t}\n\n\tlog.Infoln(\"Stopping executor driver\")\n\t_, err := driver.Stop()\n\tif err != nil {\n\t\tlog.Warningf(\"failed to stop executor driver: %v\", err)\n\t}\n\n\tlog.Infoln(\"Shutdown the executor\")\n\n\t// according to docs, mesos will generate TASK_LOST updates for us\n\t// if needed, so don't take extra time to do that here.\n\tk.tasks = map[string]*kuberTask{}\n\n\tselect {\n\t// the main Run() func may still be running... wait for it to finish: it will\n\t// clear the pod configuration cleanly, telling k8s \"there are no pods\" and\n\t// clean up resources (pods, volumes, etc).\n\tcase <-k.kubeletFinished:\n\n\t//TODO(jdef) attempt to wait for events to propagate to API server?\n\n\t// TODO(jdef) extract constant, should be smaller than whatever the\n\t// slave graceful shutdown timeout period is.\n\tcase <-time.After(15 * time.Second):\n\t\tlog.Errorf(\"timed out waiting for kubelet Run() to die\")\n\t}\n\tlog.Infoln(\"exiting\")\n\tif k.exitFunc != nil {\n\t\tk.exitFunc(0)\n\t}\n}", "func (s *scheduler) Tick() <-chan struct{} {\n\treturn s.notifyCh\n}", "func ShortRateTime() {\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\ttime.Sleep(2050 * time.Millisecond)\n\t\t\tCSRs = 0\n\t\tcase <-StopRateLimit:\n\t\t\tCSRs = 0\n\t\t\tRateLimitingActive = false\n\t\t\treturn\n\t\t}\n\t}\n}" ]
[ "0.48804328", "0.48184106", "0.46771833", "0.463024", "0.45945308", "0.45879915", "0.4565603", "0.45534387", "0.45432544", "0.45378762", "0.45378506", "0.45321634", "0.44820613", "0.4481226", "0.44739786", "0.44665173", "0.4464409", "0.44545475", "0.44348782", "0.4426257", "0.44251016", "0.44101864", "0.44082478", "0.43840227", "0.43802485", "0.43793303", "0.43660083", "0.4360845", "0.43496746", "0.4349374", "0.43466824", "0.43433845", "0.43384025", "0.43141255", "0.43106", "0.42951524", "0.42945117", "0.42896622", "0.42714322", "0.42670515", "0.4255739", "0.42490196", "0.42456073", "0.4241462", "0.4240576", "0.42300814", "0.42284936", "0.42199516", "0.42096254", "0.41940555", "0.41932747", "0.41866317", "0.417482", "0.41701362", "0.41649708", "0.4156818", "0.41547394", "0.4145463", "0.41447785", "0.41442254", "0.41431826", "0.41393894", "0.41366798", "0.4135918", "0.41333327", "0.41250443", "0.41173756", "0.41166568", "0.41104853", "0.4106563", "0.41039547", "0.4088328", "0.4083262", "0.40831724", "0.40811864", "0.40802407", "0.4078351", "0.40782306", "0.407764", "0.40750417", "0.4073881", "0.40716547", "0.40690023", "0.4054292", "0.404678", "0.4045669", "0.40442944", "0.40421286", "0.40421286", "0.40400755", "0.40388677", "0.4032715", "0.40268984", "0.40264758", "0.4024547", "0.40238228", "0.4022224", "0.40194562", "0.40173414", "0.40167695" ]
0.6303878
0
async continuation of LaunchTask
func (k *KubernetesExecutor) launchTask(driver bindings.ExecutorDriver, taskId string, pod *api.Pod) { deleteTask := func() { k.lock.Lock() defer k.lock.Unlock() delete(k.tasks, taskId) k.resetSuicideWatch(driver) } // TODO(k8s): use Pods interface for binding once clusters are upgraded // return b.Pods(binding.Namespace).Bind(binding) if pod.Spec.NodeName == "" { //HACK(jdef): cloned binding construction from k8s plugin/pkg/scheduler/scheduler.go binding := &api.Binding{ ObjectMeta: api.ObjectMeta{ Namespace: pod.Namespace, Name: pod.Name, Annotations: make(map[string]string), }, Target: api.ObjectReference{ Kind: "Node", Name: pod.Annotations[meta.BindingHostKey], }, } // forward the annotations that the scheduler wants to apply for k, v := range pod.Annotations { binding.Annotations[k] = v } // create binding on apiserver log.Infof("Binding '%v/%v' to '%v' with annotations %+v...", pod.Namespace, pod.Name, binding.Target.Name, binding.Annotations) ctx := api.WithNamespace(api.NewContext(), binding.Namespace) err := k.client.Post().Namespace(api.NamespaceValue(ctx)).Resource("bindings").Body(binding).Do().Error() if err != nil { deleteTask() k.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED, messages.CreateBindingFailure)) return } } else { // post annotations update to apiserver patch := struct { Metadata struct { Annotations map[string]string `json:"annotations"` } `json:"metadata"` }{} patch.Metadata.Annotations = pod.Annotations patchJson, _ := json.Marshal(patch) log.V(4).Infof("Patching annotations %v of pod %v/%v: %v", pod.Annotations, pod.Namespace, pod.Name, string(patchJson)) err := k.client.Patch(api.MergePatchType).RequestURI(pod.SelfLink).Body(patchJson).Do().Error() if err != nil { log.Errorf("Error updating annotations of ready-to-launch pod %v/%v: %v", pod.Namespace, pod.Name, err) deleteTask() k.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED, messages.AnnotationUpdateFailure)) return } } podFullName := container.GetPodFullName(pod) // allow a recently failed-over scheduler the chance to recover the task/pod binding: // it may have failed and recovered before the apiserver is able to report the updated // binding information. replays of this status event will signal to the scheduler that // the apiserver should be up-to-date. data, err := json.Marshal(api.PodStatusResult{ ObjectMeta: api.ObjectMeta{ Name: podFullName, SelfLink: "/podstatusresult", }, }) if err != nil { deleteTask() log.Errorf("failed to marshal pod status result: %v", err) k.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED, err.Error())) return } k.lock.Lock() defer k.lock.Unlock() // Add the task. task, found := k.tasks[taskId] if !found { log.V(1).Infof("task %v not found, probably killed: aborting launch, reporting lost", taskId) k.reportLostTask(driver, taskId, messages.LaunchTaskFailed) return } //TODO(jdef) check for duplicate pod name, if found send TASK_ERROR // from here on, we need to delete containers associated with the task // upon it going into a terminal state task.podName = podFullName k.pods[podFullName] = pod // send the new pod to the kubelet which will spin it up update := kubelet.PodUpdate{ Op: kubelet.ADD, Pods: []*api.Pod{pod}, } k.updateChan <- update statusUpdate := &mesos.TaskStatus{ TaskId: mutil.NewTaskID(taskId), State: mesos.TaskState_TASK_STARTING.Enum(), Message: proto.String(messages.CreateBindingSuccess), Data: data, } k.sendStatus(driver, statusUpdate) // Delay reporting 'task running' until container is up. psf := podStatusFunc(func() (*api.PodStatus, error) { status, err := k.podStatusFunc(k.kl, pod) if err != nil { return nil, err } status.Phase = kubelet.GetPhase(&pod.Spec, status.ContainerStatuses) hostIP, err := k.kl.GetHostIP() if err != nil { log.Errorf("Cannot get host IP: %v", err) } else { status.HostIP = hostIP.String() } return status, nil }) go k._launchTask(driver, taskId, podFullName, psf) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (item *CatalogItem) LaunchSync() (*Task, error) {\n\tutil.Logger.Printf(\"[TRACE] LaunchSync '%s' \\n\", item.CatalogItem.Name)\n\terr := WaitResource(func() (*types.TasksInProgress, error) {\n\t\tif item.CatalogItem.Tasks == nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr := item.Refresh()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn item.CatalogItem.Tasks, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn elementLaunchSync(item.client, item.CatalogItem.HREF, \"catalog item\")\n}", "func influunt_ExecutorRunAsync(self, args *pyObject) *C.PyObject {\n\teCapsule, inputs, outputs, callback := parse4ObjectFromArgs(args)\n\te := capsuleToPointer(eCapsule)\n\texec := pointer.Restore(e).(*executor.Executor)\n\n\tinputMap, err := convertPyDictNodeMap(inputs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\toutputArr, err := convertPyListToNodeArr(outputs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\tresponses, err := exec.Run(inputMap, outputArr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tgstate := C.PyGILState_Ensure()\n\t\tdefer C.PyGILState_Release(gstate)\n\n\t\targs := C.PyTuple_New(C.long(len(responses)))\n\t\tfor i, val := range responses {\n\t\t\tpyVal, err := convertGoTypeToPyObject(val)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tC.PyTuple_SetItem(args, C.long(i), pyVal)\n\t\t}\n\n\t\tres := C.PyObject_CallObject(callback, args)\n\t\tif res == nil {\n\t\t\t// TODO handle error\n\t\t\tC.PyErr_Print()\n\t\t}\n\t\tpyRelease(args)\n\t}()\n\n\tpyRetain(C.Py_None)\n\treturn C.Py_None\n}", "func (this *TestEnvironment) Launch() {\n\twg := sync.WaitGroup{}\n\twg.Add(len(this.funcList))\n\n\tif this.maxTimeout == 0 {\n\t\tthis.maxTimeout = 25 * time.Second\n\t}\n\tthis.urls = make(map[string]string)\n\n\tthis.doneChan = make(chan bool)\n\tthis.idChan = make(chan string)\n\tthis.urlChan = make(chan urlTuple)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase id := <-this.idChan:\n\t\t\t\tif len(id) > 0 {\n\t\t\t\t\tthis.ids = append(this.ids, id)\n\t\t\t\t}\n\t\t\tcase <-this.doneChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase tuple := <-this.urlChan:\n\t\t\t\tthis.urls[tuple.name] = tuple.url\n\t\t\tcase <-this.doneChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\n\tfor _, group := range this.funcList {\n\t\tgo func(grpCpy startAndWaitFuncs){\n\t\t\tid, url := grpCpy.startFunc()\n\t\t\tthis.idChan <- id\n\t\t\tgrpCpy.waitFunc(url, this.maxTimeout)\n\t\t\tthis.urlChan <- urlTuple{grpCpy.name, url}\n\t\t\twg.Done()\n\t\t}(group)\n\t}\n\n\twg.Wait()\n\tthis.doneChan <- true\n\tthis.doneChan <- true\n\tclose(this.idChan)\n\tclose(this.urlChan)\n\treturn\n}", "func Run(task Task, waiter *Waiter) { global.Run(task, waiter) }", "func (fl *FlowLauncher) Exec(p Props) {\n\n\tendParams := MakeParams()\n\tendParams.Props = p\n\n\t// make fresh chanels on each exec as they were probably closed\n\tfl.CStat = make(chan *Params)\n\tfl.iEnd = make(chan *Params)\n\n\tif fl.LastRunResult == nil {\n\t\tfl.LastRunResult = &FlowLaunchResult{}\n\t}\n\tfl.Error = \"\"\n\n\tif fl.TidyDeskPolicy(p) == false {\n\t\tendParams.Status = FAIL\n\t\tfl.iEnd <- endParams\n\t\treturn\n\t}\n\n\tglog.Info(\"workflow launcher \", fl.Name, \" with \", fl.Threads, \" threads\")\n\tvar waitGroup sync.WaitGroup\n\n\tfl.Flows = make([]*Workflow, fl.Threads, fl.Threads)\n\n\t// fire off some threads\n\tfor i := 0; i < fl.Threads; i++ {\n\n\t\t// create a new workflow\n\t\tflow := fl.FlowFunc(i)\n\n\t\t// save it for later\n\t\tfl.Flows[i] = flow\n\n\t\t// only realy need to do this once - but hey\n\t\tendParams.FlowName = flow.Name\n\n\t\tglog.Info(\"workflow launch \", flow.Name, \" with threadid \", i)\n\n\t\t// check some conditions...\n\t\tif flow == nil {\n\t\t\tglog.Error(flow.Name, \" has no flow\")\n\t\t\treturn\n\t\t}\n\n\t\tif flow.Start == nil {\n\t\t\tglog.Error(flow.Name, \" has no flow start\")\n\t\t\treturn\n\t\t}\n\n\t\tif flow.End == nil {\n\t\t\tglog.Error(flow.Name, \" has no flow end\")\n\t\t\treturn\n\t\t}\n\n\t\t// for the first thread make the results including capturing any streamed io from the tasks\n\t\tif i == 0 {\n\t\t\tfl.MakeLaunchResults(flow)\n\t\t}\n\n\t\t// TOOD - here you would inject any function to vary the params per thread\n\t\tparams := MakeParams()\n\t\tparams.Props = p\n\t\tparams.FlowName = flow.Name\n\t\tparams.ThreadId = i\n\n\t\tglog.Info(\"firing task with params \", params)\n\n\t\t// build up the thread wait group\n\t\twaitGroup.Add(1)\n\n\t\t// and fire of the workflow\n\t\tgo flow.Exec(params)\n\n\t\t// loop round forwarding status updates\n\t\tgo func() {\n\t\t\tglog.Info(\"waiting on chanel flow.C \")\n\t\t\tfor stat := range flow.C {\n\t\t\t\tglog.Info(\"got status \", stat)\n\t\t\t\tfl.LastRunResult.AddStatusOrResult(stat.TaskId, stat.Complete, stat.Status)\n\t\t\t\tfl.CStat <- stat // tiger any stats change chanel (e.g. for push messages like websockets)\n\t\t\t}\n\t\t\tglog.Info(\"launcher status loop stoppped\")\n\t\t}()\n\n\t\t// set up the flow end trigger - the end registered node will fire this\n\t\tgo func() {\n\t\t\tpar := <-flow.End.Trigger()\n\t\t\tglog.Info(\"got flow end \", par.ThreadId, \" \", flow.End.GetName())\n\t\t\t// collect all end event triggers - last par wins\n\t\t\tendParams.Status = endParams.Status + par.Status\n\n\t\t\t// update metrics\n\t\t\tnow := time.Now()\n\t\t\tfl.LastRunResult.Duration = now.Sub(fl.LastRunResult.Start)\n\n\t\t\t// close the flow status chanel\n\t\t\tclose(flow.C)\n\n\t\t\t// count down the waitgroup\n\t\t\twaitGroup.Done()\n\t\t}()\n\t}\n\n\t// now lets wait for all the threads to finish - probably TODO a timeout as well in case of bad flows...\n\tgo func() {\n\t\twaitGroup.Wait()\n\t\tglog.Info(\"completed launcher \", fl.Name, \" with \", fl.Threads, \" threads\")\n\t\t// mark status\n\t\tfl.LastRunResult.Completed = true\n\n\t\t// close the status channel\n\t\tclose(fl.CStat)\n\n\t\t// and trigger the end event\n\t\tfl.iEnd <- endParams\n\t}()\n}", "func (s stressng) Launch() (executor.TaskHandle, error) {\n\treturn s.executor.Execute(fmt.Sprintf(\"stress-ng %s\", s.arguments))\n}", "func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Launch task %v\\n\", taskInfo)\n\n\tif !k.isConnected() {\n\t\tlog.Errorf(\"Ignore launch task because the executor is disconnected\\n\")\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.ExecutorUnregistered))\n\t\treturn\n\t}\n\n\tobj, err := api.Codec.Decode(taskInfo.GetData())\n\tif err != nil {\n\t\tlog.Errorf(\"failed to extract yaml data from the taskInfo.data %v\", err)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\tpod, ok := obj.(*api.Pod)\n\tif !ok {\n\t\tlog.Errorf(\"expected *api.Pod instead of %T: %+v\", pod, pod)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\ttaskId := taskInfo.GetTaskId().GetValue()\n\tif _, found := k.tasks[taskId]; found {\n\t\tlog.Errorf(\"task already launched\\n\")\n\t\t// Not to send back TASK_RUNNING here, because\n\t\t// may be duplicated messages or duplicated task id.\n\t\treturn\n\t}\n\t// remember this task so that:\n\t// (a) we ignore future launches for it\n\t// (b) we have a record of it so that we can kill it if needed\n\t// (c) we're leaving podName == \"\" for now, indicates we don't need to delete containers\n\tk.tasks[taskId] = &kuberTask{\n\t\tmesosTaskInfo: taskInfo,\n\t}\n\tk.resetSuicideWatch(driver)\n\n\tgo k.launchTask(driver, taskId, pod)\n}", "func InvokeUITask(task func()) {\n\tcef.TaskRunnerGetForThread(cef.TIDUI).PostTask(cef.NewTask(&taskFunc{task: task}))\n}", "func (t TaskFunc) Run() { t() }", "func (t TaskFunc) Execute() { t() }", "func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Launch task %v\\n\", taskInfo)\n\n\tif !k.isConnected() {\n\t\tlog.Warningf(\"Ignore launch task because the executor is disconnected\\n\")\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.ExecutorUnregistered))\n\t\treturn\n\t}\n\n\tvar pod api.BoundPod\n\tif err := yaml.Unmarshal(taskInfo.GetData(), &pod); err != nil {\n\t\tlog.Warningf(\"Failed to extract yaml data from the taskInfo.data %v\\n\", err)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\ttaskId := taskInfo.GetTaskId().GetValue()\n\tif _, found := k.tasks[taskId]; found {\n\t\tlog.Warningf(\"task already launched\\n\")\n\t\t// Not to send back TASK_RUNNING here, because\n\t\t// may be duplicated messages or duplicated task id.\n\t\treturn\n\t}\n\t// remember this task so that:\n\t// (a) we ignore future launches for it\n\t// (b) we have a record of it so that we can kill it if needed\n\t// (c) we're leaving podName == \"\" for now, indicates we don't need to delete containers\n\tk.tasks[taskId] = &kuberTask{\n\t\tmesosTaskInfo: taskInfo,\n\t}\n\tgo k.launchTask(driver, taskId, &pod)\n}", "func (w *worker) taskLaunchStep(task concurrency.Task, params concurrency.TaskParameters) (_ concurrency.TaskResult, xerr fail.Error) {\n\tdefer fail.OnPanic(&xerr)\n\n\tif w == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif w.feature == nil {\n\t\treturn nil, fail.InvalidInstanceContentError(\"w.Feature\", \"cannot be nil\")\n\t}\n\tif task == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"task\")\n\t}\n\tif params == nil {\n\t\treturn nil, fail.InvalidParameterError(\"params\", \"can't be nil\")\n\t}\n\n\tvar (\n\t\tanon interface{}\n\t\tok bool\n\t)\n\tp := params.(taskLaunchStepParameters)\n\n\tif p.stepName == \"\" {\n\t\treturn nil, fail.InvalidParameterError(\"param.stepName\", \"cannot be empty string\")\n\t}\n\tif p.stepKey == \"\" {\n\t\treturn nil, fail.InvalidParameterError(\"param.stepKey\", \"cannot be empty string\")\n\t}\n\tif p.stepMap == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"params.stepMap\")\n\t}\n\tif p.variables == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"params[variables]\")\n\t}\n\n\tif task.Aborted() {\n\t\tif lerr, err := task.LastError(); err == nil {\n\t\t\treturn nil, fail.AbortedError(lerr, \"aborted\")\n\t\t}\n\t\treturn nil, fail.AbortedError(nil, \"aborted\")\n\t}\n\n\tdefer fail.OnExitLogError(&xerr, fmt.Sprintf(\"executed step '%s::%s'\", w.action.String(), p.stepName))\n\tdefer temporal.NewStopwatch().OnExitLogWithLevel(\n\t\tfmt.Sprintf(\"Starting execution of step '%s::%s'...\", w.action.String(), p.stepName),\n\t\tfmt.Sprintf(\"Ending execution of step '%s::%s' with error '%s'\", w.action.String(), p.stepName, xerr),\n\t\tlogrus.DebugLevel,\n\t)\n\n\tvar (\n\t\trunContent string\n\t\tstepT = stepTargets{}\n\t\t// options = map[string]string{}\n\t)\n\n\t// Determine list of hosts concerned by the step\n\tvar hostsList []resources.Host\n\tif w.target.TargetType() == featuretargettype.Host {\n\t\thostsList, xerr = w.identifyHosts(task.Context(), map[string]string{\"hosts\": \"1\"})\n\t} else {\n\t\tanon, ok = p.stepMap[yamlTargetsKeyword]\n\t\tif ok {\n\t\t\tfor i, j := range anon.(map[string]interface{}) {\n\t\t\t\tswitch j := j.(type) {\n\t\t\t\tcase bool:\n\t\t\t\t\tif j {\n\t\t\t\t\t\tstepT[i] = \"true\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstepT[i] = \"false\"\n\t\t\t\t\t}\n\t\t\t\tcase string:\n\t\t\t\t\tstepT[i] = j\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tmsg := `syntax error in Feature '%s' specification file (%s): no key '%s.%s' found`\n\t\t\treturn nil, fail.SyntaxError(msg, w.feature.GetName(), w.feature.GetDisplayFilename(), p.stepKey, yamlTargetsKeyword)\n\t\t}\n\n\t\thostsList, xerr = w.identifyHosts(task.Context(), stepT)\n\t}\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tif len(hostsList) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Marks hosts instances as released after use\n\tdefer func() {\n\t\tfor _, v := range hostsList {\n\t\t\tv.Released()\n\t\t}\n\t}()\n\n\t// Get the content of the action based on method\n\tvar keyword string\n\tswitch w.method {\n\tcase installmethod.Apt, installmethod.Yum, installmethod.Dnf:\n\t\tkeyword = yamlPackageKeyword\n\tdefault:\n\t\tkeyword = yamlRunKeyword\n\t}\n\trunContent, ok = p.stepMap[keyword].(string)\n\tif ok {\n\t\t// If 'run' content has to be altered, do it\n\t\tif w.commandCB != nil {\n\t\t\trunContent = w.commandCB(runContent)\n\t\t}\n\t} else {\n\t\tmsg := `syntax error in Feature '%s' specification file (%s): no key '%s.%s' found`\n\t\treturn nil, fail.SyntaxError(msg, w.feature.GetName(), w.feature.GetDisplayFilename(), p.stepKey, yamlRunKeyword)\n\t}\n\n\twallTime := temporal.GetLongOperationTimeout()\n\tif anon, ok = p.stepMap[yamlTimeoutKeyword]; ok {\n\t\tif _, ok := anon.(int); ok {\n\t\t\twallTime = time.Duration(anon.(int)) * time.Minute\n\t\t} else {\n\t\t\twallTimeConv, inner := strconv.Atoi(anon.(string))\n\t\t\tif inner != nil {\n\t\t\t\tlogrus.Warningf(\"Invalid value '%s' for '%s.%s', ignored.\", anon.(string), w.rootKey, yamlTimeoutKeyword)\n\t\t\t} else {\n\t\t\t\twallTime = time.Duration(wallTimeConv) * time.Minute\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplateCommand, xerr := normalizeScript(&p.variables, data.Map{\n\t\t\"reserved_Name\": w.feature.GetName(),\n\t\t\"reserved_Content\": runContent,\n\t\t\"reserved_Action\": strings.ToLower(w.action.String()),\n\t\t\"reserved_Step\": p.stepName,\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\t// Checks if step can be performed in parallel on selected hosts\n\tserial := false\n\tanon, ok = p.stepMap[yamlSerialKeyword]\n\tif ok {\n\t\tvalue, ok := anon.(string)\n\t\tif ok {\n\t\t\tif strings.ToLower(value) == \"yes\" || strings.ToLower(value) != \"true\" {\n\t\t\t\tserial = true\n\t\t\t}\n\t\t}\n\t}\n\n\tstepInstance := step{\n\t\tWorker: w,\n\t\tName: p.stepName,\n\t\tAction: w.action,\n\t\tScript: templateCommand,\n\t\tWallTime: wallTime,\n\t\t// OptionsFileContent: optionsFileContent,\n\t\tYamlKey: p.stepKey,\n\t\tSerial: serial,\n\t}\n\tr, xerr := stepInstance.Run(task, hostsList, p.variables, w.settings)\n\t// If an error occurred, do not execute the remaining steps, fail immediately\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tif !r.Successful() {\n\t\t// If there are some not completed steps, reports them and break\n\t\tif !r.Completed() {\n\t\t\tvar errpack []error\n\t\t\tfor _, key := range r.Keys() {\n\t\t\t\tcuk := r.ResultOfKey(key)\n\t\t\t\tif cuk != nil {\n\t\t\t\t\tif !cuk.Successful() && !cuk.Completed() {\n\t\t\t\t\t\t// TBR: It's one of those\n\t\t\t\t\t\tmsg := fmt.Errorf(\"execution unsuccessful and incomplete of step '%s::%s' failed on: %v with [%s]\", w.action.String(), p.stepName, cuk.Error(), spew.Sdump(cuk))\n\t\t\t\t\t\tlogrus.Warnf(msg.Error())\n\t\t\t\t\t\terrpack = append(errpack, msg)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(errpack) > 0 {\n\t\t\t\treturn &r, fail.NewErrorList(errpack)\n\t\t\t}\n\t\t}\n\n\t\t// not successful but completed, if action is check means the Feature is not installed, it's an information not a failure\n\t\tif w.action == installaction.Check {\n\t\t\treturn &r, nil\n\t\t}\n\n\t\tvar newerrpack []error\n\t\tfor _, key := range r.Keys() {\n\t\t\tcuk := r.ResultOfKey(key)\n\t\t\tif cuk != nil {\n\t\t\t\tif !cuk.Successful() && cuk.Completed() {\n\t\t\t\t\t// TBR: It's one of those\n\t\t\t\t\tmsg := fmt.Errorf(\"execution unsuccessful of step '%s::%s' failed on: %s with [%v]\", w.action.String(), p.stepName, key /*cuk.Error()*/, spew.Sdump(cuk))\n\t\t\t\t\tlogrus.Warnf(msg.Error())\n\t\t\t\t\tnewerrpack = append(newerrpack, msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(newerrpack) > 0 {\n\t\t\treturn &r, fail.NewErrorList(newerrpack)\n\t\t}\n\t}\n\n\treturn &r, nil\n}", "func (atr *ActiveTaskRun) Start() (int, time.Duration, error) {\n var env []string\n var err error\n\n for _, param := range atr.Task.Params {\n env = append(env, fmt.Sprintf(\"%s=%s\", param.Name, param.Value))\n }\n\n env = append(env, fmt.Sprintf(\"WAYFINDER_TOTAL_CORES=%d\", len(atr.CoreIds)))\n env = append(env, fmt.Sprintf(\"WAYFINDER_CORES=%s\", strings.Trim(\n strings.Join(strings.Fields(fmt.Sprint(atr.CoreIds)), \" \"), \"[]\",\n )))\n for i, coreId := range atr.CoreIds {\n env = append(env, fmt.Sprintf(\"WAYFINDER_CORE_ID%d=%d\", i, coreId))\n }\n\n config := &run.RunnerConfig{\n Log: atr.log,\n CacheDir: atr.Task.cacheDir,\n ResultsDir: atr.Task.resultsDir,\n AllowOverride: atr.Task.AllowOverride,\n Name: atr.run.Name,\n Image: atr.run.Image,\n CoreIds: atr.CoreIds,\n Devices: atr.run.Devices,\n Inputs: atr.Task.Inputs,\n Outputs: atr.Task.Outputs,\n Env: env,\n Capabilities: atr.run.Capabilities,\n }\n if atr.run.Path != \"\" {\n config.Path = atr.run.Path\n } else if atr.run.Cmd != \"\" {\n config.Cmd = atr.run.Cmd\n } else {\n return 1, -1, fmt.Errorf(\"Run did not specify path or cmd: %s\", atr.run.Name)\n }\n\n atr.Runner, err = run.NewRunner(config, atr.bridge, atr.dryRun)\n if err != nil {\n return 1, -1, err\n }\n\n atr.log.Infof(\"Starting run...\")\n exitCode, timeElapsed, err := atr.Runner.Run()\n atr.Runner.Destroy()\n if err != nil {\n return 1, -1, fmt.Errorf(\"Could not start runner: %s\", err)\n }\n\n return exitCode, timeElapsed, nil\n}", "func task() {\n\tfmt.Println(\"task one is called\")\n}", "func executeLaunch() {\n\tfmt.Println(\"Launching ...\")\n}", "func (g *Gulf) Task(name string, fn func() error, deps ...string) {}", "func (rm *ResponseManager) StartTask(task *peertask.Task, responseTaskDataChan chan<- ResponseTaskData) {\n\trm.send(&startTaskRequest{task, responseTaskDataChan}, nil)\n}", "func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) {\n\tif _, ok := d.tasks.Get(cfg.ID); ok {\n\t\treturn nil, nil, fmt.Errorf(\"task with ID %q already started\", cfg.ID)\n\t}\n\n\tvar driverConfig TaskConfig\n\tif err := cfg.DecodeDriverConfig(&driverConfig); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode driver config: %v\", err)\n\t}\n\n\thandle := drivers.NewTaskHandle(taskHandleVersion)\n\thandle.Config = cfg\n\n\tif driverConfig.Image == \"\" {\n\t\treturn nil, nil, fmt.Errorf(\"image name required\")\n\t}\n\n\tcreateOpts := api.SpecGenerator{}\n\tcreateOpts.ContainerBasicConfig.LogConfiguration = &api.LogConfig{}\n\tallArgs := []string{}\n\tif driverConfig.Command != \"\" {\n\t\tallArgs = append(allArgs, driverConfig.Command)\n\t}\n\tallArgs = append(allArgs, driverConfig.Args...)\n\n\tif driverConfig.Entrypoint != \"\" {\n\t\tcreateOpts.ContainerBasicConfig.Entrypoint = append(createOpts.ContainerBasicConfig.Entrypoint, driverConfig.Entrypoint)\n\t}\n\n\tcontainerName := BuildContainerName(cfg)\n\n\t// ensure to include port_map into tasks environment map\n\tcfg.Env = taskenv.SetPortMapEnvs(cfg.Env, driverConfig.PortMap)\n\n\t// Basic config options\n\tcreateOpts.ContainerBasicConfig.Name = containerName\n\tcreateOpts.ContainerBasicConfig.Command = allArgs\n\tcreateOpts.ContainerBasicConfig.Env = cfg.Env\n\tcreateOpts.ContainerBasicConfig.Hostname = driverConfig.Hostname\n\tcreateOpts.ContainerBasicConfig.Sysctl = driverConfig.Sysctl\n\n\tcreateOpts.ContainerBasicConfig.LogConfiguration.Path = cfg.StdoutPath\n\n\t// Storage config options\n\tcreateOpts.ContainerStorageConfig.Init = driverConfig.Init\n\tcreateOpts.ContainerStorageConfig.Image = driverConfig.Image\n\tcreateOpts.ContainerStorageConfig.InitPath = driverConfig.InitPath\n\tcreateOpts.ContainerStorageConfig.WorkDir = driverConfig.WorkingDir\n\tallMounts, err := d.containerMounts(cfg, &driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerStorageConfig.Mounts = allMounts\n\n\t// Resources config options\n\tcreateOpts.ContainerResourceConfig.ResourceLimits = &spec.LinuxResources{\n\t\tMemory: &spec.LinuxMemory{},\n\t\tCPU: &spec.LinuxCPU{},\n\t}\n\tif driverConfig.MemoryReservation != \"\" {\n\t\treservation, err := memoryInBytes(driverConfig.MemoryReservation)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Reservation = &reservation\n\t}\n\n\tif cfg.Resources.NomadResources.Memory.MemoryMB > 0 {\n\t\tlimit := cfg.Resources.NomadResources.Memory.MemoryMB * 1024 * 1024\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Limit = &limit\n\t}\n\tif driverConfig.MemorySwap != \"\" {\n\t\tswap, err := memoryInBytes(driverConfig.MemorySwap)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swap = &swap\n\t}\n\tif !d.cgroupV2 {\n\t\tswappiness := uint64(driverConfig.MemorySwappiness)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swappiness = &swappiness\n\t}\n\t// FIXME: can fail for nonRoot due to missing cpu limit delegation permissions,\n\t// see https://github.com/containers/podman/blob/master/troubleshooting.md\n\tif !d.systemInfo.Host.Rootless {\n\t\tcpuShares := uint64(cfg.Resources.LinuxResources.CPUShares)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.CPU.Shares = &cpuShares\n\t}\n\n\t// Security config options\n\tcreateOpts.ContainerSecurityConfig.CapAdd = driverConfig.CapAdd\n\tcreateOpts.ContainerSecurityConfig.CapDrop = driverConfig.CapDrop\n\tcreateOpts.ContainerSecurityConfig.User = cfg.User\n\n\t// Network config options\n\tfor _, strdns := range driverConfig.Dns {\n\t\tipdns := net.ParseIP(strdns)\n\t\tif ipdns == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"Invald dns server address\")\n\t\t}\n\t\tcreateOpts.ContainerNetworkConfig.DNSServers = append(createOpts.ContainerNetworkConfig.DNSServers, ipdns)\n\t}\n\t// Configure network\n\tif cfg.NetworkIsolation != nil && cfg.NetworkIsolation.Path != \"\" {\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.Value = cfg.NetworkIsolation.Path\n\t} else {\n\t\tif driverConfig.NetworkMode == \"\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"bridge\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"host\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Host\n\t\t} else if driverConfig.NetworkMode == \"none\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.NoNetwork\n\t\t} else if driverConfig.NetworkMode == \"slirp4netns\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp\n\t\t} else {\n\t\t\treturn nil, nil, fmt.Errorf(\"Unknown/Unsupported network mode: %s\", driverConfig.NetworkMode)\n\t\t}\n\t}\n\n\tportMappings, err := d.portMappings(cfg, driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerNetworkConfig.PortMappings = portMappings\n\n\tcontainerID := \"\"\n\trecoverRunningContainer := false\n\t// check if there is a container with same name\n\totherContainerInspect, err := d.podman.ContainerInspect(d.ctx, containerName)\n\tif err == nil {\n\t\t// ok, seems we found a container with similar name\n\t\tif otherContainerInspect.State.Running {\n\t\t\t// it's still running. So let's use it instead of creating a new one\n\t\t\td.logger.Info(\"Detect running container with same name, we reuse it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tcontainerID = otherContainerInspect.ID\n\t\t\trecoverRunningContainer = true\n\t\t} else {\n\t\t\t// let's remove the old, dead container\n\t\t\td.logger.Info(\"Detect stopped container with same name, removing it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tif err = d.podman.ContainerDelete(d.ctx, otherContainerInspect.ID, true, true); err != nil {\n\t\t\t\treturn nil, nil, nstructs.WrapRecoverable(fmt.Sprintf(\"failed to remove dead container: %v\", err), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\t// FIXME: there are more variations of image sources, we should handle it\n\t\t// e.g. oci-archive:/... etc\n\t\t// see also https://github.com/hashicorp/nomad-driver-podman/issues/69\n\t\t// do we already have this image in local storage?\n\t\thaveImage, err := d.podman.ImageExists(d.ctx, createOpts.Image)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to check for local image: %v\", err)\n\t\t}\n\t\tif !haveImage {\n\t\t\t// image is not in local storage, so we need to pull it\n\t\t\tif err = d.podman.ImagePull(d.ctx, createOpts.Image); err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to pull image %s: %v\", createOpts.Image, err)\n\t\t\t}\n\t\t}\n\n\t\tcreateResponse, err := d.podman.ContainerCreate(d.ctx, createOpts)\n\t\tfor _, w := range createResponse.Warnings {\n\t\t\td.logger.Warn(\"Create Warning\", \"warning\", w)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not create container: %v\", err)\n\t\t}\n\t\tcontainerID = createResponse.Id\n\t}\n\n\tcleanup := func() {\n\t\td.logger.Debug(\"Cleaning up\", \"container\", containerID)\n\t\tif err := d.podman.ContainerDelete(d.ctx, containerID, true, true); err != nil {\n\t\t\td.logger.Error(\"failed to clean up from an error in Start\", \"error\", err)\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\tif err = d.podman.ContainerStart(d.ctx, containerID); err != nil {\n\t\t\tcleanup()\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not start container: %v\", err)\n\t\t}\n\t}\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, containerID)\n\tif err != nil {\n\t\td.logger.Error(\"failed to inspect container\", \"err\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not inspect container : %v\", err)\n\t}\n\n\tnet := &drivers.DriverNetwork{\n\t\tPortMap: driverConfig.PortMap,\n\t\tIP: inspectData.NetworkSettings.IPAddress,\n\t\tAutoAdvertise: true,\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: containerID,\n\t\tdriver: d,\n\t\ttaskConfig: cfg,\n\t\tprocState: drivers.TaskStateRunning,\n\t\texitResult: &drivers.ExitResult{},\n\t\tstartedAt: time.Now().Round(time.Millisecond),\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tdriverState := TaskState{\n\t\tContainerID: containerID,\n\t\tTaskConfig: cfg,\n\t\tStartedAt: h.startedAt,\n\t\tNet: net,\n\t}\n\n\tif err := handle.SetDriverState(&driverState); err != nil {\n\t\td.logger.Error(\"failed to start task, error setting driver state\", \"error\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to set driver state: %v\", err)\n\t}\n\n\td.tasks.Set(cfg.ID, h)\n\n\tgo h.runContainerMonitor()\n\n\td.logger.Info(\"Completely started container\", \"taskID\", cfg.ID, \"container\", containerID, \"ip\", inspectData.NetworkSettings.IPAddress)\n\n\treturn handle, net, nil\n}", "func MainProcess() {\n\tfor _, t := range GetAllPendingTasks() {\n\t\tProcessTaskAsync(t)\n\t}\n\ttime.Sleep(2 * time.Second)\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func callMeOnStart(routine int, task *pooler.Task) {\n\t// Get pointer to custom data, then change some value in it\n\tcd := task.CustomData().(*myCustomData)\n\tfmt.Printf(\">> Goroutine %d is starting task %s with CustomData %d\\n\", routine, task.ID(), cd.Amount)\n\t// After displaying amount, change it!\n\tcd.Amount = 128\n}", "func (conf *Confirmer) StartConfirmerTask(bundleTrytes []Trytes) (chan *ConfirmerUpdate, func(), error) {\n\tconf.runningMutex.Lock()\n\tdefer conf.runningMutex.Unlock()\n\n\tif conf.running {\n\t\treturn nil, nil, fmt.Errorf(\"Confirmer task is already running\")\n\t}\n\n\ttail, err := utils.TailFromBundleTrytes(bundleTrytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tbundleHash := tail.Bundle\n\tnowis := time.Now()\n\n\t// no need to lock state because no routine is running\n\tconf.lastBundleTrytes = bundleTrytes\n\tconf.bundleHash = bundleHash\n\tconf.nextForceReattachTime = nowis.Add(time.Duration(conf.ForceReattachAfterMin) * time.Minute)\n\tconf.nextPromoTime = nowis\n\tconf.nextTailHashToPromote = tail.Hash\n\tconf.isNotPromotable = false\n\tconf.chanUpdate = make(chan *ConfirmerUpdate, 1) // not to block each time\n\tconf.numAttach = 0\n\tconf.numPromote = 0\n\tconf.totalDurationGTTAMsec = 0\n\tconf.totalDurationATTMsec = 0\n\tif conf.AEC == nil {\n\t\tconf.AEC = &utils.DummyAEC{}\n\t}\n\tif conf.SlowDownThreshold == 0 {\n\t\tconf.SlowDownThreshold = defaultSlowDownThresholdNumGoroutine\n\t}\n\n\t// starting 3 routines\n\tcancelPromoCheck := conf.goPromotabilityCheck()\n\tcancelPromo := conf.goPromote()\n\tcancelReattach := conf.goReattach()\n\n\t// confirmation monitor starts yet another routine\n\tconf.confMon.OnConfirmation(bundleHash, func(nowis time.Time) {\n\t\tconf.postConfirmerUpdate(UPD_CONFIRM, \"\", nil)\n\t})\n\n\tconf.running = true\n\n\treturn conf.chanUpdate, func() {\n\t\tconf.stopConfirmerTask(cancelPromoCheck, cancelPromo, cancelReattach)\n\t\tconf.confMon.CancelConfirmationPolling(bundleHash)\n\t}, nil\n}", "func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {\n\tcfg := ctl.Task().(*messages.GitilesTask)\n\n\tu, err := url.Parse(cfg.Repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg := gerrit.NewGerrit(u)\n\n\tvar wg sync.WaitGroup\n\n\tvar heads map[string]string\n\tvar headsErr error\n\twg.Add(1)\n\tgo func() {\n\t\theads, headsErr = m.load(c, ctl.JobID(), u)\n\t\twg.Done()\n\t}()\n\n\tvar refs map[string]string\n\tvar refsErr error\n\twg.Add(1)\n\tgo func() {\n\t\trefs, refsErr = g.GetRefs(c, cfg.Refs)\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n\n\tif headsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch heads - %s\", headsErr)\n\t\treturn fmt.Errorf(\"failed to fetch heads: %v\", headsErr)\n\t}\n\tif refsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch refs - %s\", refsErr)\n\t\treturn fmt.Errorf(\"failed to fetch refs: %v\", refsErr)\n\t}\n\n\ttype result struct {\n\t\tref string\n\t\tlog gerrit.Log\n\t\terr error\n\t}\n\tch := make(chan result)\n\n\tfor ref, head := range refs {\n\t\tif val, ok := heads[ref]; !ok {\n\t\t\twg.Add(1)\n\t\t\tgo func(ref string) {\n\t\t\t\tl, err := g.GetLog(c, ref, fmt.Sprintf(\"%s~\", ref))\n\t\t\t\tch <- result{ref, l, err}\n\t\t\t\twg.Done()\n\t\t\t}(ref)\n\t\t} else if val != head {\n\t\t\twg.Add(1)\n\t\t\tgo func(ref, since string) {\n\t\t\t\tl, err := g.GetLog(c, ref, since)\n\t\t\t\tch <- result{ref, l, err}\n\t\t\t\twg.Done()\n\t\t\t}(ref, val)\n\t\t}\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\n\tvar log gerrit.Log\n\tfor r := range ch {\n\t\tif r.err != nil {\n\t\t\tctl.DebugLog(\"Failed to fetch log - %s\", r.err)\n\t\t\tif gerrit.IsNotFound(r.err) {\n\t\t\t\tdelete(heads, r.ref)\n\t\t\t} else {\n\t\t\t\treturn r.err\n\t\t\t}\n\t\t}\n\t\tif len(r.log) > 0 {\n\t\t\theads[r.ref] = r.log[len(r.log)-1].Commit\n\t\t}\n\t\tlog = append(log, r.log...)\n\t}\n\n\tsort.Sort(log)\n\tfor _, commit := range log {\n\t\t// TODO(phosek): Trigger buildbucket job here.\n\t\tctl.DebugLog(\"Trigger build for commit %s\", commit.Commit)\n\t}\n\tif err := m.save(c, ctl.JobID(), u, heads); err != nil {\n\t\treturn err\n\t}\n\n\tctl.State().Status = task.StatusSucceeded\n\treturn nil\n}", "func (h *Hub) StartTask(ctx context.Context, request *pb.HubStartTaskRequest) (*pb.HubStartTaskReply, error) {\n\tlog.G(h.ctx).Info(\"handling StartTask request\", zap.Any(\"req\", request))\n\n\ttaskID := uuid.New()\n\tminer, err := h.selectMiner(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar startRequest = &pb.MinerStartRequest{\n\t\tId: taskID,\n\t\tRegistry: request.Registry,\n\t\tImage: request.Image,\n\t\tAuth: request.Auth,\n\t\tPublicKeyData: request.PublicKeyData,\n\t\tCommitOnStop: request.CommitOnStop,\n\t\tEnv: request.Env,\n\t\tUsage: request.Requirements.GetResources(),\n\t\tRestartPolicy: &pb.ContainerRestartPolicy{\n\t\t\tName: \"\",\n\t\t\tMaximumRetryCount: 0,\n\t\t},\n\t}\n\n\tresp, err := miner.Client.Start(ctx, startRequest)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to start %v\", err)\n\t}\n\n\troutes := []extRoute{}\n\tfor k, v := range resp.Ports {\n\t\t_, protocol, err := decodePortBinding(k)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to decode miner's port mapping\",\n\t\t\t\tzap.String(\"mapping\", k),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\trealPort, err := strconv.ParseUint(v.Port, 10, 16)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to convert real port to uint16\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"port\", v.Port),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\troute, err := miner.router.RegisterRoute(taskID, protocol, v.IP, uint16(realPort))\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to register route\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\troutes = append(routes, extRoute{\n\t\t\tcontainerPort: k,\n\t\t\troute: route,\n\t\t})\n\t}\n\n\th.setMinerTaskID(miner.ID(), taskID)\n\n\tresources := request.GetRequirements().GetResources()\n\tcpuCount := resources.GetCPUCores()\n\tmemoryCount := resources.GetMaxMemory()\n\n\tvar usage = resource.NewResources(int(cpuCount), int64(memoryCount))\n\tif err := miner.Consume(taskID, &usage); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar reply = pb.HubStartTaskReply{\n\t\tId: taskID,\n\t}\n\n\tfor _, route := range routes {\n\t\treply.Endpoint = append(\n\t\t\treply.Endpoint,\n\t\t\tfmt.Sprintf(\"%s->%s:%d\", route.containerPort, route.route.Host, route.route.Port),\n\t\t)\n\t}\n\n\treturn &reply, nil\n}", "func Launch(actions []actloop.Action, logger *log.Logger) (stop func()) {\n\tloop := actloop.NewActLoop(actions, logger)\n\tgo loop.Run(time.Second*2, time.Minute*5, notifyReady)\n\treturn loop.Cancel\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 StartAsync(ctx context.Context) {\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\terr := manager().processOnce()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (client *Client) ExecuteImportTaskWithCallback(request *ExecuteImportTaskRequest, callback func(response *ExecuteImportTaskResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ExecuteImportTaskResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ExecuteImportTask(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 (mgr *ClientMgr) runTask(ctx context.Context, client *Client, task *Task, endChan chan int) error {\n\tif task.Logger != nil {\n\t\ttask.Logger.Debug(\"runTask\", zap.String(\"servaddr\", client.servAddr), JSON(\"task\", task))\n\t}\n\n\ttask.ServAddr = client.servAddr\n\n\tif task.AnalyzePage != nil {\n\t\tversion, reply, err := client.analyzePage(ctx, task.Hostname, task.AnalyzePage.URL,\n\t\t\t&task.AnalyzePage.Viewport, &task.AnalyzePage.Options)\n\n\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\treturn err\n\n\t} else if task.GeoIP != nil {\n\t\tversion, reply, err := client.getGeoIP(ctx, task.Hostname, task.GeoIP.IP, task.GeoIP.Platform)\n\n\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\treturn err\n\t} else if task.TechInAsia != nil {\n\t\tif task.TechInAsia.Mode == jarviscrawlercore.TechInAsiaMode_TIAM_JOBLIST {\n\t\t\tversion, reply, err := client.getTechInAsiaJobList(ctx, task.Hostname, task.TechInAsia.JobTag,\n\t\t\t\ttask.TechInAsia.JobSubTag, task.TechInAsia.JobNums, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.TechInAsia.Mode == jarviscrawlercore.TechInAsiaMode_TIAM_JOB {\n\t\t\tversion, reply, err := client.getTechInAsiaJob(ctx, task.Hostname, task.TechInAsia.JobCode,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.TechInAsia.Mode == jarviscrawlercore.TechInAsiaMode_TIAM_COMPANY {\n\t\t\tversion, reply, err := client.getTechInAsiaCompany(ctx, task.Hostname, task.TechInAsia.CompanyCode,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.TechInAsia.Mode == jarviscrawlercore.TechInAsiaMode_TIAM_JOBTAG {\n\t\t\tversion, reply, err := client.getTechInAsiaJobTagList(ctx, task.Hostname, task.TechInAsia.JobTag,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTechInAsiaMode\n\t} else if task.SteepAndCheap != nil {\n\t\tif task.SteepAndCheap.Mode == jarviscrawlercore.SteepAndCheapMode_SACM_PRODUCTS {\n\t\t\tversion, reply, err := client.getSteepAndCheapProducts(ctx, task.Hostname, task.SteepAndCheap.URL,\n\t\t\t\ttask.SteepAndCheap.Page, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.SteepAndCheap.Mode == jarviscrawlercore.SteepAndCheapMode_SACM_PRODUCT {\n\t\t\tversion, reply, err := client.getSteepAndCheapProduct(ctx, task.Hostname, task.SteepAndCheap.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidSteepAndCheapMode\n\t} else if task.JRJ != nil {\n\t\tif task.JRJ.Mode == jarviscrawlercore.JRJMode_JRJM_FUND {\n\t\t\tversion, reply, err := client.getJRJFund(ctx, task.Hostname, task.JRJ.Code, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.JRJ.Mode == jarviscrawlercore.JRJMode_JRJM_FUNDS {\n\t\t\tversion, reply, err := client.getJRJFunds(ctx, task.Hostname,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.JRJ.Mode == jarviscrawlercore.JRJMode_JRJM_FUNDMANAGER {\n\t\t\tversion, reply, err := client.getJRJFundManager(ctx, task.Hostname, task.JRJ.Code,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.JRJ.Mode == jarviscrawlercore.JRJMode_JRJM_FUNDVALUE {\n\t\t\tversion, reply, err := client.getJRJFundValue(ctx, task.Hostname, task.JRJ.Code, task.JRJ.Year,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidJRJMode\n\t} else if task.JD != nil {\n\t\tif task.JD.Mode == jarviscrawlercore.JDMode_JDM_ACTIVE {\n\t\t\tversion, reply, err := client.getJDActive(ctx, task.Hostname, task.JD.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.JD.Mode == jarviscrawlercore.JDMode_JDM_PRODUCT {\n\t\t\tversion, reply, err := client.getJDProduct(ctx, task.Hostname, task.JD.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.JD.Mode == jarviscrawlercore.JDMode_JDM_ACTIVEPAGE {\n\t\t\tversion, reply, err := client.getJDActivePage(ctx, task.Hostname, task.JD.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidJDMode\n\t} else if task.Alimama != nil {\n\t\tif task.Alimama.Mode == jarviscrawlercore.AlimamaMode_ALIMMM_KEEPALIVE {\n\t\t\tversion, reply, err := client.alimamaKeepalive(ctx, task.Hostname,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Alimama.Mode == jarviscrawlercore.AlimamaMode_ALIMMM_GETTOP {\n\t\t\tversion, reply, err := client.alimamaGetTop(ctx, task.Hostname,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Alimama.Mode == jarviscrawlercore.AlimamaMode_ALIMMM_SEARCH {\n\t\t\tversion, reply, err := client.alimamaSearch(ctx, task.Hostname, task.Alimama.Text,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Alimama.Mode == jarviscrawlercore.AlimamaMode_ALIMMM_GETSHOP {\n\t\t\tversion, reply, err := client.alimamaShop(ctx, task.Hostname, task.Alimama.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidAlimamaMode\n\t} else if task.Tmall != nil {\n\t\tif task.Tmall.Mode == jarviscrawlercore.TmallMode_TMM_PRODUCT {\n\t\t\tversion, reply, err := client.tmallProduct(ctx, task.Hostname, task.Tmall.ItemID,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Tmall.Mode == jarviscrawlercore.TmallMode_TMM_MOBILEPRODUCT {\n\t\t\tversion, reply, err := client.tmallMobileProduct(ctx, task.Hostname, task.Tmall.ItemID,\n\t\t\t\ttask.Tmall.Device, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTmallMode\n\t} else if task.Taobao != nil {\n\t\tif task.Taobao.Mode == jarviscrawlercore.TaobaoMode_TBM_PRODUCT {\n\t\t\tversion, reply, err := client.taobaoProduct(ctx, task.Hostname, task.Taobao.ItemID,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Taobao.Mode == jarviscrawlercore.TaobaoMode_TBM_MOBILEPRODUCT {\n\t\t\tversion, reply, err := client.taobaoMobileProduct(ctx, task.Hostname, task.Taobao.ItemID,\n\t\t\t\ttask.Taobao.Device, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Taobao.Mode == jarviscrawlercore.TaobaoMode_TBM_SEARCH {\n\t\t\tversion, reply, err := client.taobaoSearch(ctx, task.Hostname,\n\t\t\t\ttask.Taobao.Text, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTmallMode\n\t} else if task.MountainSteals != nil {\n\t\tif task.MountainSteals.Mode == jarviscrawlercore.MountainStealsMode_MSM_SALE {\n\t\t\tversion, reply, err := client.mountainstealsSale(ctx, task.Hostname, task.MountainSteals.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.MountainSteals.Mode == jarviscrawlercore.MountainStealsMode_MSM_PRODUCT {\n\t\t\tversion, reply, err := client.mountainstealsProduct(ctx, task.Hostname, task.MountainSteals.URL,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidMountainstealsMode\n\t} else if task.Douban != nil {\n\t\tif task.Douban.Mode == jarviscrawlercore.DoubanMode_DBM_SEARCH {\n\t\t\tversion, reply, err := client.doubanSearch(ctx, task.Hostname, task.Douban.DoubanType,\n\t\t\t\ttask.Douban.Text, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Douban.Mode == jarviscrawlercore.DoubanMode_DBM_BOOK {\n\t\t\tversion, reply, err := client.doubanBook(ctx, task.Hostname, task.Douban.ID,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTmallMode\n\t} else if task.ManhuaDB != nil {\n\t\tif task.ManhuaDB.Mode == jarviscrawlercore.ManhuaDBMode_MHDB_AUTHOR {\n\t\t\tversion, reply, err := client.manhuadbAuthor(ctx, task.Hostname, task.ManhuaDB.AuthorID,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTmallMode\n\t} else if task.OABT != nil {\n\t\tif task.OABT.Mode == jarviscrawlercore.OABTMode_OABTM_PAGE {\n\t\t\tversion, reply, err := client.oabtPage(ctx, task.Hostname, task.OABT.PageIndex,\n\t\t\t\ttask.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidTmallMode\n\t} else if task.Hao6v != nil {\n\t\tif task.Hao6v.Mode == jarviscrawlercore.Hao6VMode_H6VM_NEWPAGE {\n\t\t\tversion, reply, err := client.hao6vNewest(ctx, task.Hostname, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Hao6v.Mode == jarviscrawlercore.Hao6VMode_H6VM_RESPAGE {\n\t\t\tversion, reply, err := client.hao6vRes(ctx, task.Hostname, task.Hao6v.URL, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidHao6vMode\n\t} else if task.P6vdy != nil {\n\t\tif task.P6vdy.Mode == jarviscrawlercore.P6VdyMode_P6VDY_MOVIES {\n\t\t\tversion, reply, err := client.p6vdyMovies(ctx, task.Hostname, task.P6vdy.URL, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.P6vdy.Mode == jarviscrawlercore.P6VdyMode_P6VDY_MOVIE {\n\t\t\tversion, reply, err := client.p6vdyMovie(ctx, task.Hostname, task.P6vdy.URL, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidP6vdyMode\n\t} else if task.Investing != nil {\n\t\tif task.Investing.Mode == jarviscrawlercore.InvestingMode_INVESTINGMODE_ASSETS {\n\t\t\tversion, reply, err := client.investingAssets(ctx, task.Hostname, task.Investing.URL, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t} else if task.Investing.Mode == jarviscrawlercore.InvestingMode_INVESTINGMODE_HD {\n\t\t\tversion, reply, err := client.investingHD(ctx, task.Hostname, task.Investing.URL, task.Investing.StartData, task.Investing.EndData, task.Timeout)\n\n\t\t\ttask.JCCInfo.Nodes = append(task.JCCInfo.Nodes, JCCNode{Addr: client.servAddr, Version: version})\n\n\t\t\tmgr.onTaskEnd(ctx, client, task, err, reply, endChan)\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn ErrInvalidInvestingMode\n\t}\n\n\tif task.Logger != nil {\n\t\ttask.Logger.Error(\"runTask: ErrInvalidTask\", zap.String(\"servaddr\", client.servAddr), JSON(\"task\", task))\n\t}\n\n\tclient.Running = false\n\n\treturn ErrInvalidTask\n}", "func (t *Task) Exec(agent *Agent) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\n\t\t\t//todo send task status to DCMS-agent\n\t\t\t// log.Warningf(\"run task: %s jobname: failed : %s\", t.TaskId, t.Job.Name, e)\n\t\t\tts := &TaskStatus{\n\t\t\t\tTaskPtr: t,\n\t\t\t\tCommand: nil,\n\t\t\t\tStatus: StatusFailed,\n\t\t\t\tCreateAt: time.Now().Unix(),\n\t\t\t\tErr: fmt.Errorf(\"run task: %s jobname: failed : %s\", t.TaskId, t.Job.Name, e),\n\t\t\t}\n\n\t\t\terrstr := fmt.Sprintf(\"%s\", e)\n\t\t\tif errstr == \"signal: killed\" {\n\t\t\t\tts.Status = StatusKilled\n\t\t\t}\n\t\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\t}\n\t}()\n\n\tvar ts *TaskStatus\n\tvar err error\n\t// log.Info(\"task run Exec function in goroutine\")\n\n\tt.genLogFile()\n\t// check file signature\n\ttmp_md5 := util.Md5File(t.Job.Executor)\n\tif t.Job.Signature != tmp_md5 {\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: nil,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"cronjob: %s executor: %s signature:%s does't match db's sig:%s\", t.Job.Name, t.Job.Executor, tmp_md5, t.Job.Signature),\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t} else {\n\t\tlog.Info(\"cronjob signature match for \", t.Job.Name, t.Job.ExecutorFlags)\n\t}\n\n\tvar u *user.User\n\tu, err = user.Lookup(t.Job.Runner)\n\tif err != nil {\n\t\t// log.Warningf(\"user %s not exists, task %s quit \", err, t.TaskId)\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: nil,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"user %s not exists, task %s quit \", err, t.TaskId),\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t}\n\n\tvar uid int\n\tuid, err = strconv.Atoi(u.Uid)\n\tif err != nil {\n\t\t// log.Warningf(\"uid %s conver to int failed \", uid)\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: nil,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"uid %s conver to int failed \", uid),\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t}\n\n\t// chown log file to specific t.Job.Runner user\n\tif err = t.logfile.Chown(uid, uid); err != nil {\n\t\t// log.Warningf(\"chown logfile: %s to uid: %s failed, %s\", t.logfile.Name(), u.Uid, err)\n\t\tt.logfile = nil\n\t}\n\tvar cmd *exec.Cmd\n\tif t.Job.Executor != \"\" && t.Job.ExecutorFlags != \"\" {\n\t\tcmd = exec.Command(t.Job.Executor, t.Job.ExecutorFlags)\n\t} else if t.Job.Executor != \"\" && t.Job.ExecutorFlags == \"\" {\n\t\tcmd = exec.Command(t.Job.Executor)\n\t} else {\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: cmd,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"job %s must have Executor \", t.Job.Name),\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t}\n\n\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\tcmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid)}\n\tcmd.SysProcAttr.Setsid = true\n\t// Pdeathsig only valid on linux system\n\t//\n\tcmd.SysProcAttr.Pdeathsig = syscall.SIGUSR1\n\n\tcmd.Stderr = t.logfile\n\tcmd.Stdout = t.logfile\n\n\tif err = cmd.Start(); err != nil {\n\t\t// log.Warningf(\"taskid:%s cmd Start failed: %s\", t.TaskId, err)\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: cmd,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"taskid:%s cmd Start failed: %s\", t.TaskId, err),\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t}\n\n\tts = &TaskStatus{\n\t\tTaskPtr: t,\n\t\tCommand: cmd,\n\t\tStatus: StatusRunning,\n\t\tCreateAt: time.Now().Unix(),\n\t\tErr: nil,\n\t}\n\tt.Job.Dcms.JobStatusChan <- ts\n\t// send cmd.process to dcms-agent\n\n\tif err = cmd.Wait(); err != nil {\n\t\t// log.Warningf(\"taskid:%s cmd Wait failed: %s\", t.TaskId, err)\n\t\tts = &TaskStatus{\n\t\t\tTaskPtr: t,\n\t\t\tCommand: cmd,\n\t\t\tStatus: StatusFailed,\n\t\t\tCreateAt: time.Now().Unix(),\n\t\t\tErr: fmt.Errorf(\"taskid:%s cmd Wait failed: %s\", t.TaskId, err),\n\t\t}\n\t\terrstr := fmt.Sprintf(\"%s\", err.Error())\n\t\tif errstr == \"signal: killed\" {\n\t\t\tts.Status = StatusKilled\n\t\t}\n\t\tt.Job.Dcms.JobStatusChan <- ts\n\t\treturn\n\t}\n\t// log.Warning(\"task run DONE\")\n\tts = &TaskStatus{\n\t\tTaskPtr: t,\n\t\tCommand: cmd,\n\t\tStatus: StatusSuccess,\n\t\tCreateAt: time.Now().Unix(),\n\t\tErr: nil,\n\t}\n\tt.Job.Dcms.JobStatusChan <- ts\n\treturn\n}", "func (i *TaskRegisterUpdater) StartTask(ctx context.Context, action string, age time.Duration) (models.Task, error) {\n\n\treturn i.repository.GetTask(ctx, action, age)\n}", "func AsyncBg(parent context.Context) context.Context", "func (i *DeleteOrUpdateInvTask) Start(taskContext *taskrunner.TaskContext) {\n\tgo func() {\n\t\tvar err error\n\t\tif i.Destroy && i.destroySuccessful(taskContext) {\n\t\t\terr = i.deleteInventory()\n\t\t} else {\n\t\t\terr = i.updateInventory(taskContext)\n\t\t}\n\t\ttaskContext.TaskChannel() <- taskrunner.TaskResult{Err: err}\n\t}()\n}", "func Run(task structs.Task) {\n\tmsg := structs.Response{}\n\tmsg.TaskID = task.TaskID\n\n\tcurUser, err := user.Current()\n\n\tif err != nil {\n\t\tmsg.UserOutput = err.Error()\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\n\tserUser := SerializableUser{\n\t\tUid: curUser.Uid,\n\t\tGid: curUser.Gid,\n\t\tUsername: curUser.Username,\n\t\tName: curUser.Name,\n\t\tHomeDir: curUser.HomeDir,\n\t}\n\n\tif err != nil {\n\t\tmsg.UserOutput = err.Error()\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\n\tres, err := json.MarshalIndent(serUser, \"\", \" \")\n\n\tif err != nil {\n\t\tmsg.UserOutput = err.Error()\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\tmsg.UserOutput = string(res)\n\tmsg.Completed = true\n\n\tresp, _ := json.Marshal(msg)\n\tmu.Lock()\n\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\tmu.Unlock()\n\treturn\n}", "func taskHandlerAnts(task interface{}) {\n\tworkLoadHandler()\n\twg.Done()\n}", "func (w *Worker) handleTask() {\n\tvar handleTaskInterval = time.Second\n\tfailpoint.Inject(\"handleTaskInterval\", func(val failpoint.Value) {\n\t\tif milliseconds, ok := val.(int); ok {\n\t\t\thandleTaskInterval = time.Duration(milliseconds) * time.Millisecond\n\t\t\tw.l.Info(\"set handleTaskInterval\", zap.String(\"failpoint\", \"handleTaskInterval\"), zap.Int(\"value\", milliseconds))\n\t\t}\n\t})\n\tticker := time.NewTicker(handleTaskInterval)\n\tdefer ticker.Stop()\n\n\tretryCnt := 0\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.l.Info(\"handle task process exits!\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tif w.closed.Get() == closedTrue {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\topLog := w.meta.PeekLog()\n\t\t\tif opLog == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.l.Info(\"start to execute operation\", zap.Reflect(\"oplog\", opLog))\n\n\t\t\tst := w.subTaskHolder.findSubTask(opLog.Task.Name)\n\t\t\tvar err error\n\t\t\tswitch opLog.Task.Op {\n\t\t\tcase pb.TaskOp_Start:\n\t\t\t\tif st != nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskExists.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif w.relayPurger.Purging() {\n\t\t\t\t\tif retryCnt < maxRetryCount {\n\t\t\t\t\t\tretryCnt++\n\t\t\t\t\t\tw.l.Warn(\"relay log purger is purging, cannot start subtask, would try again later\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t\t\tcontinue Loop\n\t\t\t\t\t}\n\n\t\t\t\t\tretryCnt = 0\n\t\t\t\t\terr = terror.ErrWorkerRelayIsPurging.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tretryCnt = 0\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar cfgDecrypted *config.SubTaskConfig\n\t\t\t\tcfgDecrypted, err = taskCfg.DecryptPassword()\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = terror.WithClass(err, terror.ClassDMWorker)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"started sub task\", zap.Stringer(\"config\", cfgDecrypted))\n\t\t\t\tst = NewSubTask(cfgDecrypted)\n\t\t\t\tw.subTaskHolder.recordSubTask(st)\n\t\t\t\tst.Run()\n\n\t\t\tcase pb.TaskOp_Update:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"updated sub task\", zap.String(\"task\", opLog.Task.Name), zap.Stringer(\"new config\", taskCfg))\n\t\t\t\terr = st.Update(taskCfg)\n\t\t\tcase pb.TaskOp_Stop:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"stop sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\tst.Close()\n\t\t\t\tw.subTaskHolder.removeSubTask(opLog.Task.Name)\n\t\t\tcase pb.TaskOp_Pause:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"pause sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Pause()\n\t\t\tcase pb.TaskOp_Resume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\tcase pb.TaskOp_AutoResume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"auto_resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\t}\n\n\t\t\tw.l.Info(\"end to execute operation\", zap.Int64(\"oplog ID\", opLog.Id), log.ShortError(err))\n\n\t\t\tif err != nil {\n\t\t\t\topLog.Message = err.Error()\n\t\t\t} else {\n\t\t\t\topLog.Task.Stage = st.Stage()\n\t\t\t\topLog.Success = true\n\t\t\t}\n\n\t\t\t// fill current task config\n\t\t\tif len(opLog.Task.Task) == 0 {\n\t\t\t\ttm := w.meta.GetTask(opLog.Task.Name)\n\t\t\t\tif tm == nil {\n\t\t\t\t\tw.l.Warn(\"task meta not found\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t} else {\n\t\t\t\t\topLog.Task.Task = append([]byte{}, tm.Task...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr = w.meta.MarkOperation(opLog)\n\t\t\tif err != nil {\n\t\t\t\tw.l.Error(\"fail to mark subtask operation\", zap.Reflect(\"oplog\", opLog))\n\t\t\t}\n\t\t}\n\t}\n}", "func TaskCreate(runner *gsmake.Runner, args ...string) error {\n\n\tif runner.Name() != gsmake.PacakgeAnonymous {\n\t\treturn gserrors.Newf(nil, \"you are already in a package dir.\")\n\t}\n\n\tvar flagset flag.FlagSet\n\n\toutput := flagset.String(\"o\", \"\", \"the package version\")\n\n\tversion := flagset.String(\"v\", \"current\", \"the package version\")\n\n\tprotocol := flagset.String(\"p\", \"\", \"the pacakge's scm protocol\")\n\n\tif err := flagset.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\tif flagset.NArg() != 1 {\n\t\trunner.I(\"usage : gsmake create [-v version] [-p protocol] package:archtype\")\n\t\treturn gserrors.Newf(nil, \"expect package:archtype arg\")\n\t}\n\n\ttoken := strings.SplitN(flagset.Arg(0), \":\", 2)\n\n\tif len(token) != 2 {\n\t\trunner.I(\"usage : gsmake create [-v version] [-p protocol] package:archtype\")\n\t\treturn gserrors.Newf(nil, \"invalid arg :%s\", flagset.Arg(0))\n\t}\n\n\thost := token[0]\n\n\tname := token[1]\n\n\tif *output == \"\" {\n\t\t*output = filepath.Join(runner.StartDir(), filepath.Base(name))\n\t} else {\n\t\t*output, _ = filepath.Abs(*output)\n\t}\n\n\tif *protocol == \"\" {\n\t\t*protocol = runner.RootFS().Protocol(host)\n\t}\n\n\trunner.I(\"package :%s\", host)\n\trunner.I(\"archtype :%s\", name)\n\trunner.I(\"protocol :%s\", *protocol)\n\trunner.I(\"target :%s\", *output)\n\n\tsrc := fmt.Sprintf(\"%s://%s?version=%s\", *protocol, host, *version)\n\n\ttarget := fmt.Sprintf(\"gsmake://%s?domain=archtype\", host)\n\n\terr := runner.RootFS().Mount(src, target)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath, err := runner.Path(\"archtype\", host)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tarchtype := filepath.Join(path, \".archtype\", name)\n\n\tif !fs.Exists(archtype) {\n\t\treturn gserrors.Newf(nil, \"archtype not exists :\", flagset.Arg(0))\n\t}\n\n\tif fs.Exists(*output) {\n\t\treturn gserrors.Newf(nil, \"target dir already exists\")\n\t}\n\n\tif err := fs.CopyDir(archtype, *output); err != nil {\n\t\treturn gserrors.Newf(err, \"copy archtype to target dir error\")\n\t}\n\n\treturn nil\n\n}", "func Run(task structs.Task) {\n\tmsg := structs.Response{}\n\tmsg.TaskID = task.TaskID\n\tparts := strings.SplitAfterN(task.Params, \" \", 2)\n\tparts[0] = strings.TrimSpace(parts[0])\n\tparts[1] = strings.TrimSpace(parts[1])\n\tif len(parts) != 2 {\n\t\tmsg.UserOutput = \"Not enough parameters\"\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\terr := os.Setenv(parts[0], parts[1])\n\tif err != nil {\n\t\tmsg.UserOutput = err.Error()\n\t\tmsg.Completed = true\n\t\tmsg.Status = \"error\"\n\n\t\tresp, _ := json.Marshal(msg)\n\t\tmu.Lock()\n\t\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\t\tmu.Unlock()\n\t\treturn\n\t}\n\tmsg.Completed = true\n\tmsg.UserOutput = fmt.Sprintf(\"Set %s=%s\", parts[0], parts[1])\n\tresp, _ := json.Marshal(msg)\n\tmu.Lock()\n\tprofiles.TaskResponses = append(profiles.TaskResponses, resp)\n\tmu.Unlock()\n\treturn\n}", "func (c Control) ServeStartTask(w http.ResponseWriter, r *http.Request) {\n\tc.ServeTaskAction(w, r, true)\n}", "func newTask(opts taskOptions) *task {\n\tctx, cancel := context.WithCancel(opts.Context)\n\n\tt := &task{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\texited: make(chan struct{}),\n\t}\n\n\tgo func() {\n\t\tdefer opts.OnDone()\n\t\tdefer close(t.exited)\n\t\t_ = opts.Runnable.Run(t.ctx)\n\t}()\n\treturn t\n}", "func (env *Env) Run(task Task) {\n env.session.SetIsPingTask(true)\n switch t := task.(type) {\n case *PingMessageTask:\n env.pingMessageTask = t\n }\n go task.run(env.channel)\n}", "func runTask(ctx context.Context, c autotest.Config, a *autotest.AutoservArgs, w io.Writer) (*Result, error) {\n\tr := &Result{}\n\tcmd := autotest.AutoservCommand(c, a)\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\n\tvar err error\n\tr.RunResult, err = osutil.RunWithAbort(ctx, cmd)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\tif es, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {\n\t\tr.Exit = es.ExitStatus()\n\t} else {\n\t\treturn r, errors.New(\"RunAutoserv: failed to get exit status: unknown process state\")\n\t}\n\tif r.Exit != 0 {\n\t\treturn r, errors.Errorf(\"RunAutoserv: exited %d\", r.Exit)\n\t}\n\treturn r, nil\n}", "func forwardAsync(fhandler *flowHandler, currentNodeId string, result []byte) ([]byte, error) {\n\tvar hash []byte\n\tstore := make(map[string]string)\n\n\t// get pipeline\n\tpipeline := fhandler.getPipeline()\n\n\t// Get pipeline state\n\tpipelineState := pipeline.GetState()\n\n\tdefaultStore, ok := fhandler.dataStore.(*requestEmbedDataStore)\n\tif ok {\n\t\tstore = defaultStore.store\n\t}\n\n\t// Build request\n\tuprequest := buildRequest(fhandler.id, string(pipelineState), fhandler.query, result, store)\n\n\t// Make request data\n\tdata, _ := uprequest.encode()\n\n\t// Check if HMAC used\n\tif hmacEnabled() {\n\t\tkey := getHmacKey()\n\t\thash = hmac.Sign(data, []byte(key))\n\t}\n\n\t// build url for calling the flow in async\n\thttpreq, _ := http.NewRequest(http.MethodPost, fhandler.asyncUrl, bytes.NewReader(data))\n\thttpreq.Header.Add(\"Accept\", \"application/json\")\n\thttpreq.Header.Add(\"Content-Type\", \"application/json\")\n\n\t// If hmac is enabled set digest\n\tif hmacEnabled() {\n\t\thttpreq.Header.Add(\"X-Hub-Signature\", \"sha1=\"+hex.EncodeToString(hash))\n\t}\n\n\t// extend req span for async call (TODO : Get the value)\n\tfhandler.tracer.extendReqSpan(fhandler.id, currentNodeId,\n\t\tfhandler.asyncUrl, httpreq)\n\n\tclient := &http.Client{}\n\tres, resErr := client.Do(httpreq)\n\tif resErr != nil {\n\t\treturn nil, resErr\n\t}\n\n\tdefer res.Body.Close()\n\tresdata, _ := ioutil.ReadAll(res.Body)\n\n\tif res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {\n\t\treturn resdata, fmt.Errorf(res.Status)\n\t}\n\treturn resdata, nil\n}", "func Launch(config *Config, tasks *map[string]interface{}) error {\n\tgores := NewGores(config)\n\tif gores == nil {\n\t\treturn errors.New(\"Gores launch failed: Gores is nil\")\n\t}\n\n\tinSlice := make([]interface{}, len(config.Queues))\n\tfor i, q := range config.Queues {\n\t\tinSlice[i] = q\n\t}\n\tqueuesSet := mapset.NewSetFromSlice(inSlice)\n\n\tdispatcher := NewDispatcher(gores, config, queuesSet)\n\tif dispatcher == nil {\n\t\treturn errors.New(\"Gores launch failed: Dispatcher is nil\")\n\t}\n\n\terr := dispatcher.Start(tasks)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Gores launch failed: %s\", err)\n\t}\n\n\treturn nil\n}", "func (l localOptimizer) initialLocation(operation chan<- Task, result <-chan Task, task Task, needs needser) Task {\n\ttask.Op = l.initialOperation(task, needs)\n\toperation <- task\n\treturn <-result\n}", "func (ow *outerWorker) buildTask(ctx context.Context) (*lookUpJoinTask, error) {\n\ttask := &lookUpJoinTask{\n\t\tdoneCh: make(chan error, 1),\n\t\touterResult: newList(ow.executor),\n\t\tlookupMap: mvmap.NewMVMap(),\n\t}\n\ttask.memTracker = memory.NewTracker(-1, -1)\n\ttask.outerResult.GetMemTracker().AttachTo(task.memTracker)\n\ttask.memTracker.AttachTo(ow.parentMemTracker)\n\tfailpoint.Inject(\"ConsumeRandomPanic\", nil)\n\n\tow.increaseBatchSize()\n\trequiredRows := ow.batchSize\n\tif ow.lookup.isOuterJoin {\n\t\t// If it is outerJoin, push the requiredRows down.\n\t\t// Note: buildTask is triggered when `Open` is called, but\n\t\t// ow.lookup.requiredRows is set when `Next` is called. Thus we check\n\t\t// whether it's 0 here.\n\t\tif parentRequired := int(atomic.LoadInt64(&ow.lookup.requiredRows)); parentRequired != 0 {\n\t\t\trequiredRows = parentRequired\n\t\t}\n\t}\n\tmaxChunkSize := ow.ctx.GetSessionVars().MaxChunkSize\n\tfor requiredRows > task.outerResult.Len() {\n\t\tchk := ow.ctx.GetSessionVars().GetNewChunkWithCapacity(ow.outerCtx.rowTypes, maxChunkSize, maxChunkSize, ow.executor.Base().AllocPool)\n\t\tchk = chk.SetRequiredRows(requiredRows, maxChunkSize)\n\t\terr := Next(ctx, ow.executor, chk)\n\t\tif err != nil {\n\t\t\treturn task, err\n\t\t}\n\t\tif chk.NumRows() == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\ttask.outerResult.Add(chk)\n\t}\n\tif task.outerResult.Len() == 0 {\n\t\treturn nil, nil\n\t}\n\tnumChks := task.outerResult.NumChunks()\n\tif ow.filter != nil {\n\t\ttask.outerMatch = make([][]bool, task.outerResult.NumChunks())\n\t\tvar err error\n\t\tfor i := 0; i < numChks; i++ {\n\t\t\tchk := task.outerResult.GetChunk(i)\n\t\t\touterMatch := make([]bool, 0, chk.NumRows())\n\t\t\ttask.memTracker.Consume(int64(cap(outerMatch)))\n\t\t\ttask.outerMatch[i], err = expression.VectorizedFilter(ow.ctx, ow.filter, chunk.NewIterator4Chunk(chk), outerMatch)\n\t\t\tif err != nil {\n\t\t\t\treturn task, err\n\t\t\t}\n\t\t}\n\t}\n\ttask.encodedLookUpKeys = make([]*chunk.Chunk, task.outerResult.NumChunks())\n\tfor i := range task.encodedLookUpKeys {\n\t\ttask.encodedLookUpKeys[i] = ow.ctx.GetSessionVars().GetNewChunkWithCapacity([]*types.FieldType{types.NewFieldType(mysql.TypeBlob)}, task.outerResult.GetChunk(i).NumRows(), task.outerResult.GetChunk(i).NumRows(), ow.executor.Base().AllocPool)\n\t}\n\treturn task, nil\n}", "func await(fn func()) {\n\tmu.Lock()\n\tif !paused {\n\t\tmu.Unlock()\n\t\tfn()\n\t\treturn\n\t}\n\tch := make(chan struct{})\n\twaiters = append(waiters, ch)\n\tmu.Unlock()\n\tgo func() {\n\t\t<-ch\n\t\tfn()\n\t}()\n}", "func (task *Task) inflate(displayIdx int, replicaValue string) {\n\n\tif task.Config.CmdString != \"\" || task.Config.URL != \"\" {\n\t\tTaskStats.totalTasks++\n\t}\n\n\ttask.inflateCmd()\n\n\ttask.Display.Template = lineDefaultTemplate\n\ttask.Display.Index = displayIdx\n\ttask.ErrorBuffer = bytes.NewBufferString(\"\")\n\n\ttask.resultChan = make(chan CmdEvent)\n\ttask.status = statusPending\n}", "func (o *localRunOpts) Execute() error {\n\tif err := o.configureClients(o); err != nil {\n\t\treturn err\n\t}\n\n\ttaskDef, err := o.ecsLocalClient.TaskDefinition(o.appName, o.envName, o.wkldName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get task definition: %w\", err)\n\t}\n\n\tsecrets := taskDef.Secrets()\n\tdecryptedSecrets, err := o.ecsLocalClient.DecryptedSecrets(secrets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get secret values: %w\", err)\n\t}\n\n\tsecretsList := make(map[string]string, len(decryptedSecrets))\n\tfor _, s := range decryptedSecrets {\n\t\tsecretsList[s.Name] = s.Value\n\t}\n\n\tenvVars := make(map[string]string, len(taskDef.EnvironmentVariables()))\n\tfor _, e := range taskDef.EnvironmentVariables() {\n\t\tenvVars[e.Name] = e.Value\n\t}\n\n\tcontainerPorts := make(map[string]string, len(taskDef.ContainerDefinitions))\n\tfor _, container := range taskDef.ContainerDefinitions {\n\t\tfor _, portMapping := range container.PortMappings {\n\t\t\thostPort := strconv.FormatInt(aws.Int64Value(portMapping.HostPort), 10)\n\n\t\t\tcontainerPort := hostPort\n\t\t\tif portMapping.ContainerPort == nil {\n\t\t\t\tcontainerPort = strconv.FormatInt(aws.Int64Value(portMapping.ContainerPort), 10)\n\t\t\t}\n\t\t\tcontainerPorts[hostPort] = containerPort\n\t\t}\n\t}\n\n\tenvSess, err := o.sessProvider.FromRole(o.targetEnv.ManagerRoleARN, o.targetEnv.Region)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get env session: %w\", err)\n\t}\n\tmft, err := workloadManifest(&workloadManifestInput{\n\t\tname: o.wkldName,\n\t\tappName: o.appName,\n\t\tenvName: o.envName,\n\t\tinterpolator: o.newInterpolator(o.appName, o.envName),\n\t\tws: o.ws,\n\t\tunmarshal: o.unmarshal,\n\t\tsess: envSess,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\to.appliedDynamicMft = mft\n\n\tif err := o.buildContainerImages(o); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, imageInfo := range o.out.ImageDigests {\n\t\tif len(imageInfo.RepoTags) == 0 {\n\t\t\treturn fmt.Errorf(\"no repo tags for image %q\", name)\n\t\t}\n\t\to.imageInfoList = append(o.imageInfoList, clideploy.ImagePerContainer{\n\t\t\tContainerName: name,\n\t\t\tImageURI: imageInfo.RepoTags[0],\n\t\t})\n\t}\n\n\tvar sidecarImageLocations []clideploy.ImagePerContainer //sidecarImageLocations has the image locations which are already built\n\tmanifestContent := o.appliedDynamicMft.Manifest()\n\tswitch t := manifestContent.(type) {\n\tcase *manifest.ScheduledJob:\n\t\tsidecarImageLocations = getBuiltSidecarImageLocations(t.Sidecars)\n\tcase *manifest.LoadBalancedWebService:\n\t\tsidecarImageLocations = getBuiltSidecarImageLocations(t.Sidecars)\n\tcase *manifest.WorkerService:\n\t\tsidecarImageLocations = getBuiltSidecarImageLocations(t.Sidecars)\n\tcase *manifest.BackendService:\n\t\tsidecarImageLocations = getBuiltSidecarImageLocations(t.Sidecars)\n\t}\n\to.imageInfoList = append(o.imageInfoList, sidecarImageLocations...)\n\n\terr = o.runPauseContainer(context.Background(), containerPorts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = o.runContainers(context.Background(), o.imageInfoList, secretsList, envVars)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InitiateRakeTask(taskName string, settings *models.Settings) {\n\trakeTask := map[string]string{}\n\tb, err := json.Marshal(rakeTask)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\tencodedTaskName, err := url.Parse(taskName)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\thttpclient.Post(b, fmt.Sprintf(\"%s/v1/environments/%s/services/%s/rake/%s\", settings.PaasHost, settings.EnvironmentID, settings.ServiceID, encodedTaskName), true, settings)\n}", "func (inst *IndependentInstance) execTask(behavior model.TaskBehavior, taskInst *TaskInst) {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\n\t\t\terr := fmt.Errorf(\"Unhandled Error executing task '%s' : %v\", taskInst.task.Name(), r)\n\t\t\tlogger.Error(err)\n\n\t\t\t// todo: useful for debugging\n\t\t\tlogger.Errorf(\"StackTrace: %s\", debug.Stack())\n\n\t\t\tif !taskInst.flowInst.isHandlingError {\n\n\t\t\t\ttaskInst.appendErrorData(NewActivityEvalError(taskInst.task.Name(), \"unhandled\", err.Error()))\n\t\t\t\tinst.HandleGlobalError(taskInst.flowInst, err)\n\t\t\t}\n\t\t\t// else what should we do?\n\t\t}\n\t}()\n\n\tvar err error\n\n\tvar evalResult model.EvalResult\n\n\tif taskInst.status == model.TaskStatusWaiting {\n\n\t\tevalResult, err = behavior.PostEval(taskInst)\n\n\t} else {\n\t\tevalResult, err = behavior.Eval(taskInst)\n\t}\n\n\tif err != nil {\n\t\ttaskInst.returnError = err\n\t\tinst.handleTaskError(behavior, taskInst, err)\n\t\treturn\n\t}\n\n\tswitch evalResult {\n\tcase model.EVAL_DONE:\n\t\ttaskInst.SetStatus(model.TaskStatusDone)\n\t\tinst.handleTaskDone(behavior, taskInst)\n\tcase model.EVAL_SKIP:\n\t\ttaskInst.SetStatus(model.TaskStatusSkipped)\n\t\tinst.handleTaskDone(behavior, taskInst)\n\tcase model.EVAL_WAIT:\n\t\ttaskInst.SetStatus(model.TaskStatusWaiting)\n\tcase model.EVAL_FAIL:\n\t\ttaskInst.SetStatus(model.TaskStatusFailed)\n\tcase model.EVAL_REPEAT:\n\t\ttaskInst.SetStatus(model.TaskStatusReady)\n\t\t//task needs to iterate or retry\n\t\tinst.scheduleEval(taskInst)\n\t}\n}", "func (krct *keyRegistrationConfirmationTask) RunTask() (interface{}, error) {\n\tlog.Infof(\"Waiting for confirmation for the Key [%x]\", krct.key)\n\tif krct.ctx == nil {\n\t\tkrct.ctx, _ = krct.contextInitializer(krct.timeout)\n\t}\n\n\tid := newEthereumIdentity(krct.centID, krct.contract, krct.config, krct.queue, krct.gethClientFinder, krct.contractProvider)\n\tcontract, err := id.getContract()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkrct.filterer = contract\n\tfOpts := &bind.FilterOpts{\n\t\tContext: krct.ctx,\n\t\tStart: krct.blockHeight,\n\t}\n\n\tfor {\n\t\titer, err := krct.filterer.FilterKeyAdded(fOpts, [][32]byte{krct.key}, []*big.Int{big.NewInt(int64(krct.keyPurpose))})\n\t\tif err != nil {\n\t\t\treturn nil, centerrors.Wrap(err, \"failed to start filtering key event logs\")\n\t\t}\n\n\t\terr = utils.LookForEvent(iter)\n\t\tif err == nil {\n\t\t\tlog.Infof(\"Received filtered event Key Registration Confirmation for CentrifugeID [%s] and key [%x] with purpose [%d]\\n\", krct.centID.String(), krct.key, krct.keyPurpose)\n\t\t\treturn iter.Event, nil\n\t\t}\n\n\t\tif err != utils.ErrEventNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func (a *ApplyTask) Start(taskChannel chan taskrunner.TaskResult) {\n\tgo func() {\n\t\ta.ApplyOptions.SetObjects(a.Objects)\n\t\terr := a.ApplyOptions.Run()\n\t\ttaskChannel <- taskrunner.TaskResult{\n\t\t\tErr: err,\n\t\t}\n\t}()\n}", "func (consumer *Consumer) Launch() {\n\tconsumer.rxC.runNum++\n\tconsumer.txC.runNum = consumer.rxC.runNum\n\tconsumer.Rx.Launch()\n\tconsumer.Tx.Launch()\n}", "func (s *Sun) StartAsync() {\n\ts.start(true)\n}", "func (s *Worker) Start() error {\n\tclient, err := worker.InitRPCChannel(*s.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.rc = client\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif client != nil {\n\t\t\t\t// we dont really care about the error here...\n\t\t\t\thostname, _ := os.Hostname()\n\t\t\t\terrStr := fmt.Sprintf(\"A panic occurred. Check logs on %s for more details\", hostname)\n\t\t\t\tclient.ChangeTaskStatus(rpc.ChangeTaskStatusRequest{\n\t\t\t\t\tTaskID: s.taskid,\n\t\t\t\t\tNewStatus: storage.TaskStatusError,\n\t\t\t\t\tError: &errStr,\n\t\t\t\t})\n\t\t\t}\n\t\t\tlog.Error().Str(\"task_id\", s.taskid).Msg(\"A critical error occurred while running task (panic)\")\n\t\t}\n\t}()\n\n\ts.t = NewTask(s.taskid, s.devices, s.cfg, s.rc) //Get the task in order to collect the task duration\n\tresp, err := s.t.c.GetTask(rpc.RequestTaskPayload{\n\t\tTaskID: s.t.taskid,\n\t})\n\n\tif resp.TaskDuration != 0 { //If the task duration is 0 (not set), we don't run the timer\n\t\ttimer := time.NewTimer(time.Second * time.Duration(resp.TaskDuration))\n\t\tgo func() {\n\t\t\t<-timer.C\n\t\t\tlog.Warn().Msg(\"Timer expired, stopping task\")\n\t\t\ts.t.Stop()\n\t\t\ttimer.Stop()\n\t\t}()\n\t}\n\n\tif err := s.t.Start(); err != nil {\n\t\tlog.Error().Err(err).Str(\"task_id\", s.taskid).Msg(\"An error occurred while processing a task\")\n\t\terrptr := err.Error()\n\t\tif rpcerr := client.ChangeTaskStatus(rpc.ChangeTaskStatusRequest{\n\t\t\tTaskID: s.taskid,\n\t\t\tNewStatus: storage.TaskStatusError,\n\t\t\tError: &errptr,\n\t\t}); rpcerr != nil {\n\t\t\tlog.Error().Err(rpcerr).Msg(\"Failed to change tasks status to error\")\n\t\t}\n\t}\n\treturn nil\n}", "func asyncRestart(ctx context.Context, logger hclog.Logger, task WorkloadRestarter, event *structs.TaskEvent) {\n\t// Check watcher restarts are always failures\n\tconst failure = true\n\n\t// Restarting is asynchronous so there's no reason to allow this\n\t// goroutine to block indefinitely.\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tif err := task.Restart(ctx, event, failure); err != nil {\n\t\t// Restart errors are not actionable and only relevant when\n\t\t// debugging allocation lifecycle management.\n\t\tlogger.Debug(\"failed to restart task\", \"error\", err, \"event_time\", event.Time, \"event_type\", event.Type)\n\t}\n}", "func (runner *AsyncRunner) Start(runnable Runnable) {\n\tgo func() {\n\t\terr := runnable.Run()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n}", "func Launch(addr, localDir, filename string,\n\targs []string, logDir string, retry int) error {\n\n\tfields := strings.Split(addr, \":\")\n\tif len(fields) != 2 || len(fields[0]) <= 0 || len(fields[1]) <= 0 {\n\t\treturn fmt.Errorf(\"Launch addr %s not in form of host:port\")\n\t}\n\n\tc, e := connect(fields[0])\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer c.Close()\n\n\te = c.Call(\"Prism.Launch\",\n\t\t&Cmd{addr, localDir, filename, args, logDir, retry}, nil)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Prism.Launch failed: %v\", e)\n\t}\n\treturn nil\n}", "func newSshNativeTask(host string, cmd string, opt Options) func() (interface{}, error) {\n\tstate := &sshNativeTask{\n\t\tHost: host,\n\t\tCmd: cmd,\n\t\tOpts: opt,\n\t}\n\treturn state.run\n}", "func main() {\n\tctx := context.Background()\n\n\tflag.Parse()\n\targs := flag.Args()\n\tif len(args) < 1 {\n\t\tusage()\n\t}\n\tswitch args[0] {\n\tcase \"start\":\n\t\tif len(args) != 2 {\n\t\t\tusage()\n\t\t}\n\t\tcfgFile := args[1]\n\t\tcfg, err := config.Load(cfgFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not parse %q: %v\", cfgFile, err)\n\t\t}\n\t\tif err := start(ctx, cfg); err != nil {\n\t\t\tlog.Fatalf(\"Could not start workflow: %v\", err)\n\t\t}\n\t}\n\n\t// WAIT PROCESS\n\t// Create subscription to watch for completions\n\t// Inspect coord logs for completions\n\t// Wait for remaining completions on pubsub\n\n\t// DESCRIBE PROCESS\n\t// ?\n\n\t// RETRY PROCESS\n\t// Cancel existing execution\n\t// Begin execution\n\n\t// SKIP PROCESS\n\t// Cancel existing execution\n\t// Publish completion\n}", "func (m *Master) RequestTask(args *RequestTaskArgs, reply *RequestTaskReply) error {\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tswitch m.state {\n\tcase Initializing:\n\t\treply.WorkerNextState = Idle\n\tcase MapPhase:\n\t\tfor i, task := range m.mapTasks {\n\t\t\tif task.State == UnScheduled {\n\t\t\t\t//schedule unassigned task\n\t\t\t\ttask.State = InProgress\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\n\t\t\t\tm.mapTasks[i].State = InProgress\n\t\t\t\tm.mapTasks[i].TimeStamp = time.Now()\n\t\t\t\treturn nil\n\t\t\t} else if task.State == InProgress && time.Now().Sub(task.TimeStamp) > 10*time.Second {\n\t\t\t\t//reassign tasks due to timeout\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\t\t\t\t//update TimeStamp\n\t\t\t\tm.mapTasks[i].TimeStamp = time.Now()\n\n\t\t\t\treturn nil\n\t\t\t} else if task.State == Done {\n\t\t\t\t//ignore the task\n\t\t\t\t//TODO: array for task is not efficient, maybe change to map?\n\t\t\t}\n\t\t}\n\t\t//no more mapWork, wait for other tasks\n\t\treply.WorkerNextState = Idle\n\n\tcase ReducePhase:\n\t\tfor i, task := range m.reduceTasks {\n\t\t\tif task.State == UnScheduled {\n\t\t\t\t//schedule unassigned task\n\t\t\t\ttask.State = InProgress\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\n\t\t\t\tm.reduceTasks[i].State = InProgress\n\t\t\t\tm.reduceTasks[i].TimeStamp = time.Now()\n\n\t\t\t\treturn nil\n\t\t\t} else if task.State == InProgress && time.Now().Sub(task.TimeStamp) > 10*time.Second {\n\t\t\t\t//reassign tasks due to timeout\n\t\t\t\treply.Task = task\n\t\t\t\treply.WorkerNextState = WorkAssigned\n\t\t\t\t//update TimeStamp\n\t\t\t\tm.reduceTasks[i].TimeStamp = time.Now()\n\t\t\t\treturn nil\n\t\t\t} else if task.State == Done {\n\t\t\t\t//ignore the task\n\t\t\t\t//TODO: array for task is not efficient, maybe change to map?\n\t\t\t}\n\t\t}\n\t\t//no more reduceWork, wait for other tasks\n\t\treply.WorkerNextState = Idle\n\tdefault:\n\t\t//master gonna be teared down, shut down worker\n\t\t//or something weng wrong\n\t\treply.WorkerNextState = NoMoreWork\n\t}\n\n\treturn nil\n}", "func (la Launch) execute(l *Lobby) {\n\tl.started = true\n\tla.Event = \"launch\"\n\tl.send <- la\n}", "func (protocol *DebuggerProtocol) ScheduleStepIntoAsync() <-chan *debugger.ScheduleStepIntoAsyncResult {\n\tresultChan := make(chan *debugger.ScheduleStepIntoAsyncResult)\n\tcommand := NewCommand(protocol.Socket, \"Debugger.scheduleStepIntoAsync\", nil)\n\tresult := &debugger.ScheduleStepIntoAsyncResult{}\n\n\tgo func() {\n\t\tresponse := <-protocol.Socket.SendCommand(command)\n\t\tif nil != response.Error && 0 != response.Error.Code {\n\t\t\tresult.Err = response.Error\n\t\t}\n\t\tresultChan <- result\n\t\tclose(resultChan)\n\t}()\n\n\treturn resultChan\n}", "func (p *PromoteVolumeTask) Run() error {\n\t// perform sub-tasks\n\treturn nil\n}", "func (t *task) complete(bq *InMemoryBuildQueue, executeResponse *remoteexecution.ExecuteResponse, completedByWorker bool) {\n\tswitch t.getStage() {\n\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t// The task isn't executing. Create a temporary worker\n\t\t// on which we start the task, so that we can go through\n\t\t// the regular completion code below.\n\t\tvar w worker\n\t\tw.assignQueuedTask(bq, t)\n\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t// Task is executing on a worker. Make sure to preserve\n\t\t// worker.lastInvocations.\n\t\tif completedByWorker {\n\t\t\tw := t.currentWorker\n\t\t\tif len(w.lastInvocations) != 0 {\n\t\t\t\tpanic(\"Executing worker cannot have invocations associated with it\")\n\t\t\t}\n\t\t\tif len(t.operations) == 0 {\n\t\t\t\tpanic(\"Task no longer has an invocation associated with it\")\n\t\t\t}\n\t\t\tfor i := range t.operations {\n\t\t\t\tw.lastInvocations = append(w.lastInvocations, i)\n\t\t\t\ti.idleWorkersCount++\n\t\t\t}\n\t\t}\n\tcase remoteexecution.ExecutionStage_COMPLETED:\n\t\t// Task is already completed. Nothing to do.\n\t\treturn\n\t}\n\n\tcurrentSCQ := t.getSizeClassQueue()\n\tfor i := range t.operations {\n\t\ti.decrementExecutingWorkersCount(bq)\n\t}\n\tt.currentWorker.currentTask = nil\n\tt.currentWorker = nil\n\tresult, grpcCode := getResultAndGRPCCodeFromExecuteResponse(executeResponse)\n\tt.registerExecutingStageFinished(bq, result, grpcCode)\n\n\t// Communicate the results to the initial size class learner,\n\t// which may request that the task is re-executed.\n\tpq := currentSCQ.platformQueue\n\tvar timeout time.Duration\n\tif code, actionResult := status.FromProto(executeResponse.Status).Code(), executeResponse.Result; code == codes.OK && actionResult.GetExitCode() == 0 {\n\t\t// The task succeeded, but we're still getting\n\t\t// instructed to run the task again for training\n\t\t// purposes. If that happens, create a new task that\n\t\t// runs in the background. The user does not need to be\n\t\t// blocked on this.\n\t\texecutionMetadata := actionResult.GetExecutionMetadata()\n\t\tbackgroundSizeClassIndex, backgroundTimeout, backgroundInitialSizeClassLearner := t.initialSizeClassLearner.Succeeded(\n\t\t\texecutionMetadata.GetExecutionCompletedTimestamp().AsTime().Sub(\n\t\t\t\texecutionMetadata.GetExecutionStartTimestamp().AsTime()),\n\t\t\tpq.sizeClasses)\n\t\tt.initialSizeClassLearner = nil\n\t\tif backgroundInitialSizeClassLearner != nil {\n\t\t\tif pq.maximumQueuedBackgroundLearningOperations == 0 {\n\t\t\t\t// No background learning permitted.\n\t\t\t\tbackgroundInitialSizeClassLearner.Abandoned()\n\t\t\t} else {\n\t\t\t\tbackgroundSCQ := pq.sizeClassQueues[backgroundSizeClassIndex]\n\t\t\t\tbackgroundInvocation := backgroundSCQ.getOrCreateInvocation(backgroundLearningInvocationKey)\n\t\t\t\tif backgroundInvocation.queuedOperations.Len() >= pq.maximumQueuedBackgroundLearningOperations {\n\t\t\t\t\t// Already running too many background tasks.\n\t\t\t\t\tbackgroundInitialSizeClassLearner.Abandoned()\n\t\t\t\t} else {\n\t\t\t\t\tbackgroundAction := *t.desiredState.Action\n\t\t\t\t\tbackgroundAction.DoNotCache = true\n\t\t\t\t\tbackgroundAction.Timeout = durationpb.New(backgroundTimeout)\n\t\t\t\t\tbackgroundTask := &task{\n\t\t\t\t\t\toperations: map[*invocation]*operation{},\n\t\t\t\t\t\tactionDigest: t.actionDigest,\n\t\t\t\t\t\tdesiredState: t.desiredState,\n\t\t\t\t\t\ttargetID: t.targetID,\n\t\t\t\t\t\tinitialSizeClassLearner: backgroundInitialSizeClassLearner,\n\t\t\t\t\t\tstageChangeWakeup: make(chan struct{}),\n\t\t\t\t\t}\n\t\t\t\t\tbackgroundTask.desiredState.Action = &backgroundAction\n\t\t\t\t\tbackgroundTask.newOperation(bq, pq.backgroundLearningOperationPriority, backgroundInvocation, true)\n\t\t\t\t\tbackgroundTask.schedule(bq)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if completedByWorker {\n\t\t// The worker communicated that the task failed. Attempt\n\t\t// to run it on another size class.\n\t\ttimeout, t.initialSizeClassLearner = t.initialSizeClassLearner.Failed(code == codes.DeadlineExceeded)\n\t} else {\n\t\t// The task was completed, but this was not done by the\n\t\t// worker. Treat is as a regular failure.\n\t\tt.initialSizeClassLearner.Abandoned()\n\t\tt.initialSizeClassLearner = nil\n\t}\n\n\tif t.initialSizeClassLearner != nil {\n\t\t// Re-execution against the largest size class is\n\t\t// requested, using the original timeout value.\n\t\t// Transplant all operations to the other size class\n\t\t// queue and reschedule.\n\t\tt.desiredState.Action.Timeout = durationpb.New(timeout)\n\t\tt.registerCompletedStageFinished(bq)\n\t\tlargestSCQ := pq.sizeClassQueues[len(pq.sizeClassQueues)-1]\n\t\toperations := t.operations\n\t\tt.operations = make(map[*invocation]*operation, len(operations))\n\t\tfor oldI, o := range operations {\n\t\t\ti := largestSCQ.getOrCreateInvocation(oldI.invocationKey)\n\t\t\tt.operations[i] = o\n\t\t\to.invocation = i\n\t\t}\n\t\tt.schedule(bq)\n\t\tt.reportNonFinalStageChange()\n\t} else {\n\t\t// The task succeeded or it failed on the largest size\n\t\t// class. Let's just complete it.\n\t\t//\n\t\t// Scrub data from the task that are no longer needed\n\t\t// after completion. This reduces memory usage\n\t\t// significantly. Keep the Action digest, so that\n\t\t// there's still a way to figure out what the task was.\n\t\tdelete(bq.inFlightDeduplicationMap, t.actionDigest)\n\t\tt.executeResponse = executeResponse\n\t\tt.desiredState.Action = nil\n\t\tclose(t.stageChangeWakeup)\n\t\tt.stageChangeWakeup = nil\n\n\t\t// Background learning tasks may continue to exist, even\n\t\t// if no clients wait for the results. Now that this\n\t\t// task is completed, it must go through the regular\n\t\t// cleanup process.\n\t\tfor _, o := range t.operations {\n\t\t\tif o.mayExistWithoutWaiters {\n\t\t\t\to.mayExistWithoutWaiters = false\n\t\t\t\to.maybeStartCleanup(bq)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Session) Start(tags map[string]interface{}) error {\n\tif s.task != nil {\n\t\treturn errors.New(\"task already running\")\n\t}\n\n\tt := &task{\n\t\tName: s.TaskName,\n\t\tVersion: 1,\n\t\tSchedule: s.Schedule,\n\t}\n\n\twf := wmap.NewWorkflowMap()\n\n\tsnapTags := make(map[string]string)\n\tfor key, value := range tags {\n\t\tsnapTags[key] = fmt.Sprintf(\"%v\", value)\n\t}\n\twf.CollectNode.Tags = map[string]map[string]string{\"\": snapTags}\n\n\tfor _, metric := range s.Metrics {\n\t\twf.CollectNode.AddMetric(metric, -1)\n\t}\n\n\tfor _, configItem := range s.CollectNodeConfigItems {\n\t\twf.CollectNode.AddConfigItem(configItem.Ns, configItem.Key, configItem.Value)\n\t}\n\n\tloaderConfig := DefaultPluginLoaderConfig()\n\tloaderConfig.SnapteldAddress = s.pClient.URL\n\n\t// Add specified publisher to workflow as well.\n\twf.CollectNode.Add(s.Publisher)\n\n\tt.Workflow = wf\n\n\tr := s.pClient.CreateTask(t.Schedule, t.Workflow, t.Name, t.Deadline, true, 10)\n\tif r.Err != nil {\n\t\treturn errors.Wrapf(r.Err, \"could not create task %q\", t.Name)\n\t}\n\n\t// Save a copy of the task so we can stop it again.\n\tt.ID = r.ID\n\tt.State = r.State\n\ts.task = t\n\n\treturn nil\n}", "func createOneTask(id string, buildVarTask BuildVariantTaskUnit, project *Project, buildVariant *BuildVariant,\n\tb *build.Build, v *Version, dat distro.AliasLookupTable, createTime time.Time, activationInfo specificActivationInfo,\n\tgithubChecksAliases ProjectAliases) (*task.Task, error) {\n\n\tactivateTask := b.Activated && !activationInfo.taskHasSpecificActivation(b.BuildVariant, buildVarTask.Name)\n\tisStepback := activationInfo.isStepbackTask(b.BuildVariant, buildVarTask.Name)\n\n\tbuildVarTask.RunOn = dat.Expand(buildVarTask.RunOn)\n\tbuildVariant.RunOn = dat.Expand(buildVariant.RunOn)\n\n\tvar (\n\t\tdistroID string\n\t\tdistroAliases []string\n\t)\n\n\tif len(buildVarTask.RunOn) > 0 {\n\t\tdistroID = buildVarTask.RunOn[0]\n\n\t\tif len(buildVarTask.RunOn) > 1 {\n\t\t\tdistroAliases = append(distroAliases, buildVarTask.RunOn[1:]...)\n\t\t}\n\n\t} else if len(buildVariant.RunOn) > 0 {\n\t\tdistroID = buildVariant.RunOn[0]\n\n\t\tif len(buildVariant.RunOn) > 1 {\n\t\t\tdistroAliases = append(distroAliases, buildVariant.RunOn[1:]...)\n\t\t}\n\t} else {\n\t\tgrip.Warning(message.Fields{\n\t\t\t\"task_id\": id,\n\t\t\t\"message\": \"task is not runnable as there is no distro specified\",\n\t\t\t\"variant\": buildVariant.Name,\n\t\t\t\"project\": project.Identifier,\n\t\t\t\"version\": v.Revision,\n\t\t\t\"requester\": v.Requester,\n\t\t})\n\t}\n\n\tactivatedTime := utility.ZeroTime\n\tif activateTask {\n\t\tactivatedTime = time.Now()\n\t}\n\n\tisGithubCheck := false\n\tif len(githubChecksAliases) > 0 {\n\t\tvar err error\n\t\tname, tags, ok := project.GetTaskNameAndTags(buildVarTask)\n\t\tif ok {\n\t\t\tisGithubCheck, err = githubChecksAliases.HasMatchingTask(name, tags)\n\t\t\tgrip.Error(message.WrapError(err, message.Fields{\n\t\t\t\t\"message\": \"error checking if task matches aliases\",\n\t\t\t\t\"version\": v.Id,\n\t\t\t\t\"task\": buildVarTask.Name,\n\t\t\t\t\"variant\": buildVarTask.Variant,\n\t\t\t}))\n\t\t}\n\t}\n\n\tt := &task.Task{\n\t\tId: id,\n\t\tSecret: utility.RandomString(),\n\t\tDisplayName: buildVarTask.Name,\n\t\tBuildId: b.Id,\n\t\tBuildVariant: buildVariant.Name,\n\t\tDistroId: distroID,\n\t\tDistroAliases: distroAliases,\n\t\tCreateTime: createTime,\n\t\tIngestTime: time.Now(),\n\t\tScheduledTime: utility.ZeroTime,\n\t\tStartTime: utility.ZeroTime, // Certain time fields must be initialized\n\t\tFinishTime: utility.ZeroTime, // to our own utility.ZeroTime value (which is\n\t\tDispatchTime: utility.ZeroTime, // Unix epoch 0, not Go's time.Time{})\n\t\tLastHeartbeat: utility.ZeroTime,\n\t\tStatus: evergreen.TaskUndispatched,\n\t\tActivated: activateTask,\n\t\tActivatedTime: activatedTime,\n\t\tRevisionOrderNumber: v.RevisionOrderNumber,\n\t\tRequester: v.Requester,\n\t\tParentPatchID: b.ParentPatchID,\n\t\tParentPatchNumber: b.ParentPatchNumber,\n\t\tVersion: v.Id,\n\t\tRevision: v.Revision,\n\t\tMustHaveResults: utility.FromBoolPtr(project.GetSpecForTask(buildVarTask.Name).MustHaveResults),\n\t\tProject: project.Identifier,\n\t\tPriority: buildVarTask.Priority,\n\t\tGenerateTask: project.IsGenerateTask(buildVarTask.Name),\n\t\tTriggerID: v.TriggerID,\n\t\tTriggerType: v.TriggerType,\n\t\tTriggerEvent: v.TriggerEvent,\n\t\tCommitQueueMerge: buildVarTask.CommitQueueMerge,\n\t\tIsGithubCheck: isGithubCheck,\n\t\tDisplayTaskId: utility.ToStringPtr(\"\"), // this will be overridden if the task is an execution task\n\t}\n\tif isStepback {\n\t\tt.ActivatedBy = evergreen.StepbackTaskActivator\n\t}\n\tif buildVarTask.IsGroup {\n\t\ttg := project.FindTaskGroup(buildVarTask.GroupName)\n\t\tif tg == nil {\n\t\t\treturn nil, errors.Errorf(\"unable to find task group %s in project %s\", buildVarTask.GroupName, project.Identifier)\n\t\t}\n\n\t\ttg.InjectInfo(t)\n\t}\n\treturn t, nil\n}", "func runTask(ctx context.Context, cfg *taskConfig, f TaskFunc, args ...interface{}) *Task {\n\ttask := newTask(ctx, cfg, f, args...)\n\ttask.Start()\n\treturn task\n}", "func Launch(th ThreadWithRole) error {\n\tif e := AllocThread(th); e != nil {\n\t\treturn e\n\t}\n\tth.Launch()\n\treturn nil\n}", "func (*container) AttachTask(context.Context, libcontainerdtypes.StdioCallback) (libcontainerdtypes.Task, error) {\n\treturn nil, errdefs.NotFound(cerrdefs.ErrNotImplemented)\n}", "func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {\n\tcfg := ctl.Task().(*messages.GitilesTask)\n\n\tctl.DebugLog(\"Repo: %s, Refs: %s\", cfg.Repo, cfg.Refs)\n\tu, err := url.Parse(cfg.Repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twatchedRefs := watchedRefs{}\n\twatchedRefs.init(cfg.GetRefs())\n\n\tvar wg sync.WaitGroup\n\n\tvar heads map[string]string\n\tvar headsErr error\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\theads, headsErr = loadState(c, ctl.JobID(), u)\n\t}()\n\n\tvar refs map[string]string\n\tvar refsErr error\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\trefs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs)\n\t}()\n\n\twg.Wait()\n\n\tif headsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch heads - %s\", headsErr)\n\t\treturn fmt.Errorf(\"failed to fetch heads: %v\", headsErr)\n\t}\n\tif refsErr != nil {\n\t\tctl.DebugLog(\"Failed to fetch refs - %s\", refsErr)\n\t\treturn fmt.Errorf(\"failed to fetch refs: %v\", refsErr)\n\t}\n\n\trefsChanged := 0\n\n\t// Delete all previously known refs which are either no longer watched or no\n\t// longer exist in repo.\n\tfor ref := range heads {\n\t\tswitch {\n\t\tcase !watchedRefs.hasRef(ref):\n\t\t\tctl.DebugLog(\"Ref %s is no longer watched\", ref)\n\t\t\tdelete(heads, ref)\n\t\t\trefsChanged++\n\t\tcase refs[ref] == \"\":\n\t\t\tctl.DebugLog(\"Ref %s deleted\", ref)\n\t\t\tdelete(heads, ref)\n\t\t\trefsChanged++\n\t\t}\n\t}\n\t// For determinism, sort keys of current refs.\n\tsortedRefs := make([]string, 0, len(refs))\n\tfor ref := range refs {\n\t\tsortedRefs = append(sortedRefs, ref)\n\t}\n\tsort.Strings(sortedRefs)\n\n\temittedTriggers := 0\n\tmaxTriggersPerInvocation := m.maxTriggersPerInvocation\n\tif maxTriggersPerInvocation == 0 {\n\t\tmaxTriggersPerInvocation = defaultMaxTriggersPerInvocation\n\t}\n\t// Note, that current `refs` contain only watched refs (see getRefsTips).\n\tfor _, ref := range sortedRefs {\n\t\tnewHead := refs[ref]\n\t\toldHead, existed := heads[ref]\n\t\tswitch {\n\t\tcase !existed:\n\t\t\tctl.DebugLog(\"Ref %s is new: %s\", ref, newHead)\n\t\tcase oldHead != newHead:\n\t\t\tctl.DebugLog(\"Ref %s updated: %s => %s\", ref, oldHead, newHead)\n\t\tdefault:\n\t\t\t// No change.\n\t\t\tcontinue\n\t\t}\n\t\theads[ref] = newHead\n\t\trefsChanged++\n\t\temittedTriggers++\n\t\t// TODO(tandrii): actually look at commits between current and previously\n\t\t// known tips of each ref.\n\t\t// In current (v1) engine, all triggers emitted around the same time will\n\t\t// result in just 1 invocation of each triggered job. Therefore,\n\t\t// passing just HEAD's revision is good enough.\n\t\t// For the same reason, only 1 of the refs will actually be processed if\n\t\t// several refs changed at the same time.\n\t\tctl.EmitTrigger(c, &internal.Trigger{\n\t\t\tId: fmt.Sprintf(\"%s/+/%s@%s\", cfg.Repo, ref, newHead),\n\t\t\tTitle: newHead,\n\t\t\tUrl: fmt.Sprintf(\"%s/+/%s\", cfg.Repo, newHead),\n\t\t\tPayload: &internal.Trigger_Gitiles{\n\t\t\t\tGitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead},\n\t\t\t},\n\t\t})\n\n\t\t// Safeguard against too many changes such as the first run after\n\t\t// config change to watch many more refs than before.\n\t\tif emittedTriggers >= maxTriggersPerInvocation {\n\t\t\tctl.DebugLog(\"Emitted %d triggers, postponing the rest\", emittedTriggers)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif refsChanged == 0 {\n\t\tctl.DebugLog(\"No changes detected\")\n\t} else {\n\t\tctl.DebugLog(\"%d refs changed\", refsChanged)\n\t\t// Force save to ensure triggers are actually emitted.\n\t\tif err := ctl.Save(c); err != nil {\n\t\t\t// At this point, triggers have not been sent, so bail now and don't save\n\t\t\t// the refs' heads newest values.\n\t\t\treturn err\n\t\t}\n\t\tif err := saveState(c, ctl.JobID(), u, heads); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctl.DebugLog(\"Saved %d known refs\", len(heads))\n\t}\n\n\tctl.State().Status = task.StatusSucceeded\n\treturn nil\n}", "func (s *sshNativeTask) run() (interface{}, error) {\n\tclient, err := s.newClient()\n\t// create session\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\t// run cmd\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\tctx := createContext(s.Host)\n\tif err := session.Run(s.Cmd); err != nil {\n\t\t// if of type ExitError, then its a remote issue, add to code\n\t\twaitmsg, ok := err.(*ssh.ExitError)\n\t\tif ok {\n\t\t\tctx.Response.Code = waitmsg.ExitStatus()\n\t\t} else {\n\t\t\t// else return err\n\t\t\treturn ctx, err\n\t\t}\n\t}\n\n\tctx.Response.Stdout = stdout.String()\n\tctx.Response.Stderr = stderr.String()\n\n\treturn ctx, nil\n}", "func workerTask() {\n\tworker, err := zmq4.NewSocket(zmq4.REQ)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"ipc://backend.ipc\")\n\tworker.SendMessage(WorkerReady)\n\n\tfor {\n\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tmsg[len(msg)-1] = \"OK\"\n\t\tworker.SendMessage(msg)\n\t}\n\n}", "func (m *Master) Task(args *TaskArgs, reply *TaskReply) error {\r\n\t// log.Printf(\"Receiving Task Requesting: worker=%s\\n\", args.WorkerID)\r\n\t// assign task base on phase\r\n\t// 0-Map Phase\r\n\t// 1-Reduce Phase\r\n\t// -1 exit\r\n\tm.mux.Lock()\r\n\ttaskType := m.taskPhase\r\n\tm.mux.Unlock()\r\n\tswitch taskType {\r\n\tcase 0:\r\n\t\t// wg.Add(1)\r\n\t\treply.TaskType = taskType\r\n\r\n\t\tm.mux.Lock()\r\n\t\ttaskNo := m.nextMapTaskNo\r\n\t\treply.TaskNo = taskNo\r\n\t\tm.nextMapTaskNo++\r\n\t\tm.mux.Unlock()\r\n\r\n\t\tif len(m.inputFiles) == 0 {\r\n\t\t\treply.TaskType = 2\r\n\t\t\treply.Files = []string{}\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\tfilename := <-m.inputFiles\r\n\t\treply.Files = []string{filename}\r\n\r\n\t\treply.NReduce = m.nReduce\r\n\r\n\t\t// log.Printf(\"assigned MapTask: File=%s, MapTaskNo=%d\\n\", filename, taskNo)\r\n\r\n\t\t// wg.Add(1)\r\n\t\tgo checkMapTask(m, taskNo, filename)\r\n\r\n\t\t// log.Printf(\"assigned MapTask: worker=%s\\n\", args.WorkerID)\r\n\r\n\t\treturn nil\r\n\tcase 1:\r\n\t\t// wg.Add(1)\r\n\t\treply.TaskType = taskType\r\n\t\tm.mux.Lock()\r\n\t\ttaskNo := m.nextReduceTaskNo\r\n\t\tm.mux.Unlock()\r\n\t\treply.TaskNo = taskNo\r\n\t\tif len(m.inputIntermediateFiles) == 0 {\r\n\t\t\treply.TaskType = 2\r\n\t\t\treply.Files = []string{}\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\t// log.Printf(\"Channel[inputIntermediateFiles] Size: %d\\n\", len(m.inputIntermediateFiles))\r\n\t\tfilenames := <-m.inputIntermediateFiles\r\n\r\n\t\treply.Files = filenames\r\n\r\n\t\tm.mux.Lock()\r\n\t\t// m.nReduce--\r\n\t\tm.nextReduceTaskNo++\r\n\t\tm.mux.Unlock()\r\n\r\n\t\t// wg.Add(1)\r\n\t\tgo checkReduceTask(m, taskNo, filenames)\r\n\t\t// log.Printf(\"assigned ReduceTask: worker=%s\\n\", args.WorkerID)\r\n\r\n\t\treturn nil\r\n\r\n\tdefault:\r\n\t\treply.TaskType = -1 //notice worker to exit\r\n\t\treturn nil\r\n\r\n\t}\r\n\r\n}", "func (t *Task) StartSync() (TaskResult, error) {\n\tt.Start()\n\tres, err := t.Wait(0)\n\treturn res, err\n}", "func (s *BaseAspidaListener) EnterTasks(ctx *TasksContext) {}", "func (a *API) finishImportImageTask(importImageResponse *ecs.ImportImageResponse) (string, error) {\n\timportDone := func(taskId string) (bool, error) {\n\t\trequest := ecs.CreateDescribeTasksRequest()\n\t\trequest.TaskIds = taskId\n\t\tres, err := a.ecs.DescribeTasks(request)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif len(res.TaskSet.Task) != 1 {\n\t\t\treturn false, fmt.Errorf(\"expected result about one task, got %v\", res.TaskSet.Task)\n\t\t}\n\n\t\tswitch res.TaskSet.Task[0].TaskStatus {\n\t\tcase \"Finished\":\n\t\t\treturn true, nil\n\t\tcase \"Processing\":\n\t\t\treturn false, nil\n\t\tcase \"Waiting\":\n\t\t\treturn false, nil\n\t\tcase \"Deleted\":\n\t\t\treturn false, fmt.Errorf(\"task %v was deleted\", taskId)\n\t\tcase \"Paused\":\n\t\t\treturn false, fmt.Errorf(\"task %v was paused\", taskId)\n\t\tcase \"Failed\":\n\t\t\treturn false, fmt.Errorf(\"task %v failed\", taskId)\n\t\tdefault:\n\t\t\treturn false, fmt.Errorf(\"unexpected status for task %v: %v\", taskId, res.TaskSet.Task[0].TaskStatus)\n\t\t}\n\t}\n\n\tfor {\n\t\tdone, err := importDone(importImageResponse.TaskId)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn importImageResponse.ImageId, nil\n}", "func (m *Monitor) RunAsync() chan error {\n\tklog.V(5).Info(\"starting leader elect bit\")\n\tgo func() {\n\t\tdefer close(m.c)\n\t\tif err := m.runLeaderElect(); err != nil {\n\t\t\t// Return the error to the calling thread\n\t\t\tm.c <- err\n\t\t}\n\t}()\n\tklog.V(5).Info(\"starting leader elect bit started\")\n\treturn m.c\n}", "func (ts *TaskService) Connect(ctx context.Context, req *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithField(\"id\", req.ID).Debug(\"connect\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.Connect(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"connect failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).WithFields(logrus.Fields{\n\t\t\"shim_pid\": resp.ShimPid,\n\t\t\"task_pid\": resp.TaskPid,\n\t\t\"version\": resp.Version,\n\t}).Error(\"connect succeeded\")\n\treturn resp, nil\n}", "func (q *Queue) run(c *config.Config) error {\n\tfor len(q.tasks) > 0 {\n\t\tvar t string\n\t\tt, q.tasks = q.tasks[0], q.tasks[1:]\n\n\t\tvar task string\n\t\tvar version int\n\t\tif strings.Contains(t, \"@\") {\n\t\t\tparts := strings.Split(t, \"@\")\n\t\t\tif len(parts) != 2 {\n\t\t\t\treturn fmt.Errorf(\"task should have the `name@version` \"+\n\t\t\t\t\t\"format: %+v\", parts)\n\t\t\t}\n\n\t\t\tv, err := strconv.ParseInt(parts[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"parse version failed (%s): %s\", parts[1], err)\n\t\t\t}\n\n\t\t\ttask = parts[0]\n\t\t\tversion = int(v)\n\t\t} else {\n\t\t\ttask = t\n\t\t\tversion = -1\n\t\t}\n\n\t\tf, err := getTask(task, version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif *config.Verbose {\n\t\t\tlog.Printf(\"%s[%2d] Running %s@%d...%s\\n\",\n\t\t\t\tcolors.Cyan, len(q.tasks), task, version, colors.Reset)\n\t\t} else {\n\t\t\tlog.Printf(\"%s[%2d] Running %s%s\\n\",\n\t\t\t\tcolors.Cyan, len(q.tasks), task, colors.Reset)\n\t\t}\n\n\t\tq.CurTask = task\n\t\tif err := f(c, q); err != nil {\n\t\t\treturn fmt.Errorf(\"task failed (%s): %s\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (f *LambdaFunc) Task() {\n\tf.printf(\"debug: LambdaFunc.Task() runs on goroutine %d\", common.GetGoroutineID())\n\n\t// we want to perform various cleanup actions, such as killing\n\t// instances and deleting old code. We want to do these\n\t// asynchronously, but in order. Thus, we use a chan to get\n\t// FIFO behavior and a single cleanup task to get async.\n\t//\n\t// two types can be sent to this chan:\n\t//\n\t// 1. string: this is a path to be deleted\n\t//\n\t// 2. chan: this is a signal chan that corresponds to\n\t// previously initiated cleanup work. We block until we\n\t// receive the complete signal, before proceeding to\n\t// subsequent cleanup tasks in the FIFO.\n\tcleanupChan := make(chan any, 32)\n\tcleanupTaskDone := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tmsg, ok := <-cleanupChan\n\t\t\tif !ok {\n\t\t\t\tcleanupTaskDone <- true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch op := msg.(type) {\n\t\t\tcase string:\n\t\t\t\tif err := os.RemoveAll(op); err != nil {\n\t\t\t\t\tf.printf(\"Async code cleanup could not delete %s, even after all instances using it killed: %v\", op, err)\n\t\t\t\t}\n\t\t\tcase chan bool:\n\t\t\t\t<-op\n\t\t\t}\n\t\t}\n\t}()\n\n\t// stats for autoscaling\n\toutstandingReqs := 0\n\texecMs := common.NewRollingAvg(10)\n\tvar lastScaling *time.Time = nil\n\ttimeout := time.NewTimer(0)\n\n\tfor {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\tif f.codeDir == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase req := <-f.funcChan:\n\t\t\t// msg: client -> function\n\n\t\t\t// check for new code, and cleanup old code\n\t\t\t// (and instances that use it) if necessary\n\t\t\toldCodeDir := f.codeDir\n\t\t\tif err := f.pullHandlerIfStale(); err != nil {\n\t\t\t\tf.printf(\"Error checking for new lambda code at `%s`: %v\", f.codeDir, err)\n\t\t\t\treq.w.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treq.w.Write([]byte(err.Error() + \"\\n\"))\n\t\t\t\treq.done <- true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif oldCodeDir != \"\" && oldCodeDir != f.codeDir {\n\t\t\t\tel := f.instances.Front()\n\t\t\t\tfor el != nil {\n\t\t\t\t\twaitChan := el.Value.(*LambdaInstance).AsyncKill()\n\t\t\t\t\tcleanupChan <- waitChan\n\t\t\t\t\tel = el.Next()\n\t\t\t\t}\n\t\t\t\tf.instances = list.New()\n\n\t\t\t\t// cleanupChan is a FIFO, so this will\n\t\t\t\t// happen after the cleanup task waits\n\t\t\t\t// for all instance kills to finish\n\t\t\t\tcleanupChan <- oldCodeDir\n\t\t\t}\n\n\t\t\tf.lmgr.DepTracer.TraceInvocation(f.codeDir)\n\n\t\t\tselect {\n\t\t\tcase f.instChan <- req:\n\t\t\t\t// msg: function -> instance\n\t\t\t\toutstandingReqs++\n\t\t\tdefault:\n\t\t\t\t// queue cannot accept more, so reply with backoff\n\t\t\t\treq.w.WriteHeader(http.StatusTooManyRequests)\n\t\t\t\treq.w.Write([]byte(\"lambda instance queue is full\\n\"))\n\t\t\t\treq.done <- true\n\t\t\t}\n\t\tcase req := <-f.doneChan:\n\t\t\t// msg: instance -> function\n\n\t\t\texecMs.Add(req.execMs)\n\t\t\toutstandingReqs--\n\n\t\t\t// msg: function -> client\n\t\t\treq.done <- true\n\n\t\tcase done := <-f.killChan:\n\t\t\t// signal all instances to die, then wait for\n\t\t\t// cleanup task to finish and exit\n\t\t\tel := f.instances.Front()\n\t\t\tfor el != nil {\n\t\t\t\twaitChan := el.Value.(*LambdaInstance).AsyncKill()\n\t\t\t\tcleanupChan <- waitChan\n\t\t\t\tel = el.Next()\n\t\t\t}\n\t\t\tif f.codeDir != \"\" {\n\t\t\t\t//cleanupChan <- f.codeDir\n\t\t\t}\n\t\t\tclose(cleanupChan)\n\t\t\t<-cleanupTaskDone\n\t\t\tdone <- true\n\t\t\treturn\n\t\t}\n\n\t\t// POLICY: how many instances (i.e., virtual sandboxes) should we allocate?\n\n\t\t// AUTOSCALING STEP 1: decide how many instances we want\n\n\t\t// let's aim to have 1 sandbox per second of outstanding work\n\t\tinProgressWorkMs := outstandingReqs * execMs.Avg\n\t\tdesiredInstances := inProgressWorkMs / 1000\n\n\t\t// if we have, say, one job that will take 100\n\t\t// seconds, spinning up 100 instances won't do any\n\t\t// good, so cap by number of outstanding reqs\n\t\tif outstandingReqs < desiredInstances {\n\t\t\tdesiredInstances = outstandingReqs\n\t\t}\n\n\t\t// always try to have one instance\n\t\tif desiredInstances < 1 {\n\t\t\tdesiredInstances = 1\n\t\t}\n\n\t\t// AUTOSCALING STEP 2: tweak how many instances we have, to get closer to our goal\n\n\t\t// make at most one scaling adjustment per second\n\t\tadjustFreq := time.Second\n\t\tnow := time.Now()\n\t\tif lastScaling != nil {\n\t\t\telapsed := now.Sub(*lastScaling)\n\t\t\tif elapsed < adjustFreq {\n\t\t\t\tif desiredInstances != f.instances.Len() {\n\t\t\t\t\ttimeout = time.NewTimer(adjustFreq - elapsed)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// kill or start at most one instance to get closer to\n\t\t// desired number\n\t\tif f.instances.Len() < desiredInstances {\n\t\t\tf.printf(\"increase instances to %d\", f.instances.Len()+1)\n\t\t\tf.newInstance()\n\t\t\tlastScaling = &now\n\t\t} else if f.instances.Len() > desiredInstances {\n\t\t\tf.printf(\"reduce instances to %d\", f.instances.Len()-1)\n\t\t\twaitChan := f.instances.Back().Value.(*LambdaInstance).AsyncKill()\n\t\t\tf.instances.Remove(f.instances.Back())\n\t\t\tcleanupChan <- waitChan\n\t\t\tlastScaling = &now\n\t\t}\n\n\t\tif f.instances.Len() != desiredInstances {\n\t\t\t// we can only adjust quickly, so we want to\n\t\t\t// run through this loop again as soon as\n\t\t\t// possible, even if there are no requests to\n\t\t\t// service.\n\t\t\ttimeout = time.NewTimer(adjustFreq)\n\t\t}\n\t}\n}", "func (s *Task) Run(updateHandler func(*Task)) error {\n\tvar wg sync.WaitGroup\n\ts.results.SetStatus(StatusRunning)\n\tupdateHandler(s)\n\tcmd := exec.Command(s.Command, s.Args...)\n\tcmd.Env = s.env()\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(`couldn't open standard out for command %q %v: %w`, s.Command, s.Args, err)\n\t}\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(`couldn't open standard error for command %q %v: %w`, s.Command, s.Args, err)\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(`couldn't start command %q %v: %w`, s.Command, s.Args, err)\n\t}\n\twg.Add(2)\n\tgo func() {\n\t\tdefer stdout.Close()\n\t\tdefer wg.Done()\n\t\tbuff := make([]byte, 1024)\n\t\tfor {\n\t\t\tn, err := stdout.Read(buff)\n\t\t\tif n > 0 {\n\t\t\t\ts.results.AppendStdOut(string(buff))\n\t\t\t\tupdateHandler(s)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tfmt.Println(`Could not read std in from task`, s.Name, `read bytes`, n, err)\n\t\t\t\t\ts.results.SetStatus(StatusFailed)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer stderr.Close()\n\t\tdefer wg.Done()\n\t\tbuff := make([]byte, 1024)\n\t\tfor {\n\t\t\tn, err := stderr.Read(buff)\n\t\t\tif n > 0 {\n\t\t\t\ts.results.AppendStdErr(string(buff))\n\t\t\t\tupdateHandler(s)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\ts.results.SetStatus(StatusFailed)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\twg.Wait()\n\tif err := cmd.Wait(); err != nil {\n\t\ts.results.SetStatus(StatusFailed)\n\t\ts.results.AppendStdErr(fmt.Sprintf(`command failed %q %v: %v`, s.Command, s.Args, err))\n\t}\n\ts.results.SetReturnCode(cmd.ProcessState.ExitCode())\n\ts.evaluateSuccess()\n\tupdateHandler(s)\n\treturn nil\n}", "func sequentialDeployment(action []parlaytypes.Action, hostConfig ssh.HostSSHConfig, logger *plunderlogging.Logger) error {\n\tvar err error\n\n\tfor y := range action {\n\t\tswitch action[y].ActionType {\n\t\tcase \"upload\":\n\t\t\terr = hostConfig.UploadFile(action[y].Source, action[y].Destination)\n\t\t\tif err != nil {\n\t\t\t\t// Set checkpoint\n\t\t\t\trestore.Action = action[y].Name\n\t\t\t\trestore.Host = hostConfig.Host\n\t\t\t\trestore.createCheckpoint()\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, \"\", err.Error())\n\t\t\t\t// Return the error\n\t\t\t\treturn fmt.Errorf(\"Upload task [%s] on host [%s] failed with error [%s]\", action[y].Name, hostConfig.Host, err)\n\t\t\t}\n\t\t\tlog.Infof(\"Upload Task [%s] on node [%s] completed successfully\", action[y].Name, hostConfig.Host)\n\t\tcase \"download\":\n\t\t\terr = hostConfig.DownloadFile(action[y].Source, action[y].Destination)\n\t\t\tif err != nil {\n\t\t\t\t// Set checkpoint\n\t\t\t\trestore.Action = action[y].Name\n\t\t\t\trestore.Host = hostConfig.Host\n\t\t\t\trestore.createCheckpoint()\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, \"\", err.Error())\n\t\t\t\t// Return the error\n\t\t\t\treturn fmt.Errorf(\"Download task [%s] on host [%s] failed with error [%s]\", action[y].Name, hostConfig.Host, err)\n\t\t\t}\n\t\t\tlog.Infof(\"Succesfully Downloaded [%s] to [%s] from [%s]\", action[y].Source, action[y].Destination, hostConfig.Host)\n\t\tcase \"command\":\n\t\t\t// Build out a configuration based upon the action\n\t\t\tcr := parseAndExecute(action[y], &hostConfig)\n\t\t\t// This will end command execution and print the error\n\t\t\tif cr.Error != nil && action[y].IgnoreFailure == false {\n\t\t\t\t// Set checkpoint\n\t\t\t\trestore.Action = action[y].Name\n\t\t\t\trestore.Host = hostConfig.Host\n\t\t\t\trestore.createCheckpoint()\n\n\t\t\t\t// Output error messages\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, cr.Result, cr.Error.Error())\n\t\t\t\t// cr.Result is ommited here TODO\n\t\t\t\treturn fmt.Errorf(\"Command task [%s] on host [%s] failed with error [%s]\", action[y].Name, hostConfig.Host, cr.Error)\n\t\t\t}\n\n\t\t\t// if there is an error and we're set to ignore it then process accordingly\n\t\t\tif cr.Error != nil && action[y].IgnoreFailure == true {\n\t\t\t\tlog.Warnf(\"Command Task [%s] on node [%s] failed (execution will continute)\", action[y].Name, hostConfig.Host)\n\t\t\t\tlog.Debugf(\"Command Results ->\\n%s\", cr.Result)\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, cr.Result, cr.Error.Error())\n\n\t\t\t\t//logger.WriteLogEntry(hostConfig.Host, fmt.Sprintf(\"Command task [%s] on host [%s] has failed (execution will continute)\\n\", action[y].Name, hostConfig.Host))\n\t\t\t}\n\n\t\t\t// No error, task was completed correctly\n\t\t\tif cr.Error == nil {\n\t\t\t\t// Output success Messages\n\t\t\t\tlog.Infof(\"Command Task [%s] on node [%s] completed successfully\", action[y].Name, hostConfig.Host)\n\t\t\t\tlog.Debugf(\"Command Results ->\\n%s\", cr.Result)\n\t\t\t\t//logger.WriteLogEntry(hostConfig.Host, fmt.Sprintf(\"Command task [%s] on host [%s] has completed succesfully\\n\", action[y].Name, hostConfig.Host))\n\t\t\t\t//logger.WriteLogEntry(hostConfig.Host, fmt.Sprintf(\"Command task [%s] Output [%s]\\n\", action[y].Name, cr.Result))\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, cr.Result, \"\")\n\n\t\t\t}\n\t\tcase \"pkg\":\n\n\t\tcase \"key\":\n\n\t\tdefault:\n\t\t\t// Set checkpoint (the actiontype may be modified or spelling issue)\n\t\t\trestore.Action = action[y].Name\n\t\t\trestore.Host = hostConfig.Host\n\t\t\trestore.createCheckpoint()\n\t\t\tpluginActions, err := parlayplugin.ExecuteAction(action[y].ActionType, hostConfig.Host, action[y].Plugin)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WriteLogEntry(hostConfig.Host, action[y].Name, \"\", err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Debugf(\"About to execute [%d] actions\", len(pluginActions))\n\t\t\terr = sequentialDeployment(pluginActions, hostConfig, logger)\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 ProcessTaskAsync(t Task) {\n\tidstr := strconv.Itoa(t.ID)\n\tfmt.Println(\"Running task with id: \" + idstr)\n\tgo ProcessTask(t)\n}", "func (t *Task) start(runnable func() error) {\n\tt.group.mutex.Lock()\n\tt.group.running[t] = true\n\tt.state = stateRunning\n\tt.group.mutex.Unlock()\n\n\tgo t.run(runnable)\n}", "func CreateTask(c *gin.Context) {\n\tsrv := server.GetServer()\n\n\tvar param TaskParams\n\tc.BindJSON(&param)\n\n\targs := make([]tasks.Arg, len(param.Args))\n\tfor idx, arg := range param.Args {\n\t\targs[idx] = tasks.Arg{\n\t\t\tType: \"int64\",\n\t\t\tValue: arg,\n\t\t}\n\t}\n\tsignature := &tasks.Signature{\n\t\tName: param.TaskName,\n\t\tArgs: args,\n\t\tRetryCount: 3,\n\t}\n\n\tasyncResult, err := srv.SendTask(signature)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"asyncResult:\", asyncResult)\n\n\tc.JSON(http.StatusOK, gin.H{\"Status\": \"In progress\", \"Job\": asyncResult})\n}", "func (client *Client) ExecuteImportTaskWithChan(request *ExecuteImportTaskRequest) (<-chan *ExecuteImportTaskResponse, <-chan error) {\n\tresponseChan := make(chan *ExecuteImportTaskResponse, 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.ExecuteImportTask(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 main() {\n\tconnectOpions, err := redis.ParseURL(\"redis://\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tclient := redis.NewClient(connectOpions)\n\n\t// initialize celery client\n\tcli, _ := gocelery.NewCeleryClient(\n\t\tgocelery.NewRedisBroker(client),\n\t\t&gocelery.RedisCeleryBackend{UniversalClient: client},\n\t\t1,\n\t)\n\n\t// prepare arguments\n\ttaskName := \"worker.add\"\n\targA := rand.Intn(10)\n\targB := rand.Intn(10)\n\n\ttask := gocelery.GetTaskMessage(taskName)\n\ttask.Args = append(task.Args, argA, argB)\n\n\t// run task\n\tasyncResult, err := cli.Delay(context.Background(), task)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get results from backend with timeout\n\tres, err := asyncResult.Get(context.Background(), 10*time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlog.Printf(\"result: %+v of type %+v\", res, reflect.TypeOf(res))\n\n}", "func (t *Task) Run() error {\n\tred := color.New(color.FgRed).SprintFunc()\n\turl := fmt.Sprintf(\"%s%s\", t.BaseURL, t.Path)\n\n\treq, e := request.NewRequester(t.Method, t.Config.Insecure, t.Config.Detail)\n\tif e != nil {\n\t\tfmt.Printf(\"%s: %s\\n\", red(\"Error\"), e)\n\t\treturn e\n\t}\n\treq.SetHeaders(t.applyVarsToMap(t.Headers))\n\treq.SetCookies(t.Cookies)\n\n\treqBody := t.applyVars(t.RequestBody)\n\tif len(t.UploadList) > 0 {\n\t\tuploadRequest, e := t.UploadList.ToRequestBody()\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\n\t\treqBody = uploadRequest.RequestBody\n\t\treq.SetHeaders(map[string]string{\n\t\t\t\"Content-Type\": uploadRequest.ContentType,\n\t\t\t\"Content-Length\": fmt.Sprintf(\"%d\", len(reqBody)),\n\t\t})\n\t}\n\n\tresp, e := req.Request(t.applyVars(url), reqBody)\n\tif e != nil {\n\t\tfmt.Printf(\"%s: %s\\n\", red(\"Error\"), e)\n\t\treturn e\n\t}\n\n\tr := response.NewResponse(resp, t.Config.Detail)\n\tif t.Config.Detail {\n\t\tr.LogResponse()\n\t}\n\n\tref := referrable.NewReferrable(r)\n\n\tt.Cookies = []*http.Cookie{}\n\n\tfor _, v := range r.Cookies {\n\t\tt.Cookies = append(t.Cookies, v)\n\t}\n\n\tfor k, v := range t.Captures {\n\t\tr, ok := ref.Find(v)\n\t\tif ok {\n\t\t\tt.Captured[k] = r[0]\n\t\t} else {\n\t\t\te = fmt.Errorf(\"unable to capture data from response: %s\", k)\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn e\n}", "func (bot *botContext) callTask(t interface{}, command string, args ...string) (errString string, retval TaskRetVal) {\n\tbot.currentTask = t\n\tr := bot.makeRobot()\n\ttask, plugin, _ := getTask(t)\n\tisPlugin := plugin != nil\n\t// This should only happen in the rare case that a configured authorizer or elevator is disabled\n\tif task.Disabled {\n\t\tmsg := fmt.Sprintf(\"callTask failed on disabled task %s; reason: %s\", task.name, task.reason)\n\t\tLog(Error, msg)\n\t\tbot.debug(msg, false)\n\t\treturn msg, ConfigurationError\n\t}\n\tif bot.logger != nil {\n\t\tvar desc string\n\t\tif len(task.Description) > 0 {\n\t\t\tdesc = fmt.Sprintf(\"Starting task: %s\", task.Description)\n\t\t} else {\n\t\t\tdesc = \"Starting task\"\n\t\t}\n\t\tbot.logger.Section(task.name, desc)\n\t}\n\n\tif !(task.name == \"builtInadmin\" && command == \"abort\") {\n\t\tdefer checkPanic(r, fmt.Sprintf(\"Plugin: %s, command: %s, arguments: %v\", task.name, command, args))\n\t}\n\tLog(Debug, fmt.Sprintf(\"Dispatching command '%s' to plugin '%s' with arguments '%#v'\", command, task.name, args))\n\tif isPlugin && plugin.taskType == taskGo {\n\t\tif command != \"init\" {\n\t\t\temit(GoPluginRan)\n\t\t}\n\t\tLog(Debug, fmt.Sprintf(\"Call go plugin: '%s' with args: %q\", task.name, args))\n\t\treturn \"\", pluginHandlers[task.name].Handler(r, command, args...)\n\t}\n\tvar fullPath string // full path to the executable\n\tvar err error\n\tfullPath, err = getTaskPath(task)\n\tif err != nil {\n\t\temit(ScriptPluginBadPath)\n\t\treturn fmt.Sprintf(\"Error getting path for %s: %v\", task.name, err), MechanismFail\n\t}\n\tinterpreter, err := getInterpreter(fullPath)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"looking up interpreter for %s: %s\", fullPath, err)\n\t\tLog(Error, fmt.Sprintf(\"Unable to call external plugin %s, no interpreter found: %s\", fullPath, err))\n\t\terrString = \"There was a problem calling an external plugin\"\n\t\temit(ScriptPluginBadInterpreter)\n\t\treturn errString, MechanismFail\n\t}\n\texternalArgs := make([]string, 0, 5+len(args))\n\t// on Windows, we exec the interpreter with the script as first arg\n\tif runtime.GOOS == \"windows\" {\n\t\texternalArgs = append(externalArgs, fullPath)\n\t}\n\texternalArgs = append(externalArgs, command)\n\texternalArgs = append(externalArgs, args...)\n\texternalArgs = fixInterpreterArgs(interpreter, externalArgs)\n\tLog(Debug, fmt.Sprintf(\"Calling '%s' with interpreter '%s' and args: %q\", fullPath, interpreter, externalArgs))\n\tvar cmd *exec.Cmd\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd = exec.Command(interpreter, externalArgs...)\n\t} else {\n\t\tcmd = exec.Command(fullPath, externalArgs...)\n\t}\n\tbot.Lock()\n\tbot.taskName = task.name\n\tbot.taskDesc = task.Description\n\tbot.osCmd = cmd\n\tbot.Unlock()\n\tenvhash := make(map[string]string)\n\tif len(bot.environment) > 0 {\n\t\tfor k, v := range bot.environment {\n\t\t\tenvhash[k] = v\n\t\t}\n\t}\n\n\t// Pull stored env vars specific to this task and supply to this task only.\n\t// No effect if already defined. Useful mainly for specific tasks to have\n\t// secrets passed in but not handed to everything in the pipeline.\n\tif !bot.pipeStarting {\n\t\tstoredEnv := make(map[string]string)\n\t\t_, exists, _ := checkoutDatum(paramPrefix+task.NameSpace, &storedEnv, false)\n\t\tif exists {\n\t\t\tfor key, value := range storedEnv {\n\t\t\t\t// Dynamically provided and configured parameters take precedence over stored parameters\n\t\t\t\t_, exists := envhash[key]\n\t\t\t\tif !exists {\n\t\t\t\t\tenvhash[key] = value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbot.pipeStarting = false\n\t}\n\n\tenvhash[\"GOPHER_CHANNEL\"] = bot.Channel\n\tenvhash[\"GOPHER_USER\"] = bot.User\n\tenvhash[\"GOPHER_PROTOCOL\"] = fmt.Sprintf(\"%s\", bot.Protocol)\n\tenv := make([]string, 0, len(envhash))\n\tkeys := make([]string, 0, len(envhash))\n\tfor k, v := range envhash {\n\t\tif len(k) == 0 {\n\t\t\tLog(Error, fmt.Sprintf(\"Empty Name value while populating environment for '%s', skipping\", task.name))\n\t\t\tcontinue\n\t\t}\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", k, v))\n\t\tkeys = append(keys, k)\n\t}\n\tcmd.Env = env\n\tLog(Debug, fmt.Sprintf(\"Running '%s' with environment vars: '%s'\", fullPath, strings.Join(keys, \"', '\")))\n\tvar stderr, stdout io.ReadCloser\n\t// hold on to stderr in case we need to log an error\n\tstderr, err = cmd.StderrPipe()\n\tif err != nil {\n\t\tLog(Error, fmt.Errorf(\"Creating stderr pipe for external command '%s': %v\", fullPath, err))\n\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\treturn errString, MechanismFail\n\t}\n\tif bot.logger == nil {\n\t\t// close stdout on the external plugin...\n\t\tcmd.Stdout = nil\n\t} else {\n\t\tstdout, err = cmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tLog(Error, fmt.Errorf(\"Creating stdout pipe for external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\treturn errString, MechanismFail\n\t\t}\n\t}\n\tif err = cmd.Start(); err != nil {\n\t\tLog(Error, fmt.Errorf(\"Starting command '%s': %v\", fullPath, err))\n\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\treturn errString, MechanismFail\n\t}\n\tif command != \"init\" {\n\t\temit(ScriptTaskRan)\n\t}\n\tif bot.logger == nil {\n\t\tvar stdErrBytes []byte\n\t\tif stdErrBytes, err = ioutil.ReadAll(stderr); err != nil {\n\t\t\tLog(Error, fmt.Errorf(\"Reading from stderr for external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\treturn errString, MechanismFail\n\t\t}\n\t\tstdErrString := string(stdErrBytes)\n\t\tif len(stdErrString) > 0 {\n\t\t\tLog(Warn, fmt.Errorf(\"Output from stderr of external command '%s': %s\", fullPath, stdErrString))\n\t\t\terrString = fmt.Sprintf(\"There was error output while calling external task '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\temit(ScriptPluginStderrOutput)\n\t\t}\n\t} else {\n\t\tclosed := make(chan struct{})\n\t\tgo func() {\n\t\t\tscanner := bufio.NewScanner(stdout)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\tbot.logger.Log(\"OUT \" + line)\n\t\t\t}\n\t\t\tclosed <- struct{}{}\n\t\t}()\n\t\tgo func() {\n\t\t\tscanner := bufio.NewScanner(stderr)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\tbot.logger.Log(\"ERR \" + line)\n\t\t\t}\n\t\t\tclosed <- struct{}{}\n\t\t}()\n\t\thalfClosed := false\n\tcloseLoop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\tif halfClosed {\n\t\t\t\t\tbreak closeLoop\n\t\t\t\t}\n\t\t\t\thalfClosed = true\n\t\t\t}\n\t\t}\n\t}\n\tif err = cmd.Wait(); err != nil {\n\t\tretval = Fail\n\t\tsuccess := false\n\t\tif exitstatus, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := exitstatus.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tretval = TaskRetVal(status.ExitStatus())\n\t\t\t\tif retval == Success {\n\t\t\t\t\tsuccess = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !success {\n\t\t\tLog(Error, fmt.Errorf(\"Waiting on external command '%s': %v\", fullPath, err))\n\t\t\terrString = fmt.Sprintf(\"There were errors calling external plugin '%s', you might want to ask an administrator to check the logs\", task.name)\n\t\t\temit(ScriptPluginErrExit)\n\t\t}\n\t}\n\treturn errString, retval\n}", "func LoadRoutine(grpcDriver *GRPCDriver, number int, channel chan bool) {\n\tfmt.Printf(\"[goroutine %d] loadroutine started\\n\", number)\n\n\tconnectionState := grpcDriver.Connection.GetState()\n\tfmt.Printf(\"[goroutine %d] connection state: %v \\n\", number, connectionState)\n\t_, err := grpcDriver.GetHealth()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"[goroutine %d] health reveived\\n\", number)\n\n\tconnectionState = grpcDriver.Connection.GetState()\n\tfmt.Printf(\"[goroutine %d] connection state: %v \\n\", number, connectionState)\n\n\treturnedTask, err := grpcDriver.LoadTask(\"clientTest2\")\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tfmt.Printf(\"[goroutine %d] loadroutine done, loaded: %s\\n\", number, returnedTask.Body)\n\t// suite.Equal(len(\"0vNrL62AGAdIzRZ9pReEnKeMu4x\"), len(returnedTask.TaskID), \"TaskID doesn't look valid\")\n\t// suite.Equal(\"Task #1\", returnedTask.Body, \"Body doesn't match\")\n\n\tif returnedTask.Body != \"Task #1\" {\n\t\tchannel <- false\n\t} else {\n\t\tchannel <- true\n\t}\n}", "func (m *etcdMinion) TaskRunner(c <-chan *task.Task) error {\n\tlog.Println(\"Starting task runner\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-m.done:\n\t\t\tbreak\n\t\tcase t := <-c:\n\t\t\tlog.Printf(\"Processing task %s\\n\", t.ID)\n\t\t\tm.processTask(t)\n\t\t\tlog.Printf(\"Finished processing task %s\\n\", t.ID)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *task) ContinueWith(ctx context.Context, nextAction func(interface{}, error) (interface{}, error)) Task {\n\treturn Invoke(ctx, func(context.Context) (interface{}, error) {\n\t\tresult, err := t.Outcome()\n\t\treturn nextAction(result, err)\n\t})\n}", "func (w *WaitTask) startInner(taskContext *TaskContext) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\tklog.V(3).Infof(\"wait task progress: %d/%d\", 0, len(w.Ids))\n\n\tpending := object.ObjMetadataSet{}\n\tfor _, id := range w.Ids {\n\t\tswitch {\n\t\tcase w.skipped(taskContext, id):\n\t\t\terr := taskContext.InventoryManager().SetSkippedReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as skipped reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSkipped)\n\t\tcase w.changedUID(taskContext, id):\n\t\t\t// replaced\n\t\t\tw.handleChangedUID(taskContext, id)\n\t\tcase w.reconciledByID(taskContext, id):\n\t\t\terr := taskContext.InventoryManager().SetSuccessfulReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as successful reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSuccessful)\n\t\tdefault:\n\t\t\terr := taskContext.InventoryManager().SetPendingReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as pending reconcile: %v\", err)\n\t\t\t}\n\t\t\tpending = append(pending, id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcilePending)\n\t\t}\n\t}\n\tw.pending = pending\n\n\tklog.V(3).Infof(\"wait task progress: %d/%d\", len(w.Ids)-len(w.pending), len(w.Ids))\n\n\tif len(pending) == 0 {\n\t\t// all reconciled - clear pending and exit\n\t\tklog.V(3).Infof(\"all objects reconciled or skipped (name: %q)\", w.TaskName)\n\t\tw.cancelFunc()\n\t}\n}", "func (task *Task) listenAndDisplay(environment map[string]string) {\n\tscr := newScreen()\n\t// just wait for stuff to come back\n\n\tfor TaskStats.runningCmds > 0 {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tspinner.Next()\n\n\t\t\tif task.Config.CmdString != \"\" {\n\t\t\t\tif !task.Command.Complete && task.Command.Started {\n\t\t\t\t\ttask.Display.Values.Prefix = spinner.Current()\n\t\t\t\t\ttask.Display.Values.Eta = task.CurrentEta()\n\t\t\t\t}\n\t\t\t\ttask.display()\n\t\t\t}\n\n\t\t\tfor _, taskObj := range task.Children {\n\t\t\t\tif !taskObj.Command.Complete && taskObj.Command.Started {\n\t\t\t\t\ttaskObj.Display.Values.Prefix = spinner.Current()\n\t\t\t\t\ttaskObj.Display.Values.Eta = taskObj.CurrentEta()\n\t\t\t\t}\n\t\t\t\ttaskObj.display()\n\t\t\t}\n\n\t\t\t// update the summary line\n\t\t\tif Config.Options.ShowSummaryFooter {\n\t\t\t\tscr.DisplayFooter(footer(statusPending, \"\"))\n\t\t\t}\n\n\t\tcase msgObj := <-task.resultChan:\n\t\t\teventTask := msgObj.Task\n\n\t\t\t// update the state before displaying...\n\t\t\tif msgObj.Complete {\n\t\t\t\teventTask.Completed(msgObj.ReturnCode)\n\t\t\t\ttask.StartAvailableTasks(environment)\n\t\t\t\ttask.status = msgObj.Status\n\t\t\t\tif msgObj.Status == statusError {\n\t\t\t\t\t// update the group status to indicate a failed subtask\n\t\t\t\t\tTaskStats.totalFailedTasks++\n\n\t\t\t\t\t// keep note of the failed task for an after task report\n\t\t\t\t\ttask.failedTasks = append(task.failedTasks, eventTask)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !eventTask.Config.ShowTaskOutput {\n\t\t\t\tmsgObj.Stderr = \"\"\n\t\t\t\tmsgObj.Stdout = \"\"\n\t\t\t}\n\n\t\t\tif msgObj.Stderr != \"\" {\n\t\t\t\teventTask.Display.Values = LineInfo{Status: msgObj.Status.Color(\"i\"), Title: eventTask.Config.Name, Msg: msgObj.Stderr, Prefix: spinner.Current(), Eta: eventTask.CurrentEta()}\n\t\t\t} else {\n\t\t\t\teventTask.Display.Values = LineInfo{Status: msgObj.Status.Color(\"i\"), Title: eventTask.Config.Name, Msg: msgObj.Stdout, Prefix: spinner.Current(), Eta: eventTask.CurrentEta()}\n\t\t\t}\n\n\t\t\teventTask.display()\n\n\t\t\t// update the summary line\n\t\t\tif Config.Options.ShowSummaryFooter {\n\t\t\t\tscr.DisplayFooter(footer(statusPending, \"\"))\n\t\t\t} else {\n\t\t\t\tscr.MovePastFrame(false)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif !exitSignaled {\n\t\ttask.waiter.Wait()\n\t}\n\n}", "func (t *task) Await(\n\tctx context.Context,\n\ttimeout time.Duration) (result interface{}, err error) {\n\tresult = nil\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\t\tt.abortHandler(ctx, t.request) // abortHandler operation\n\tcase res := <-t.resultQ:\n\t\tresult = res.Result\n\t\terr = res.Err\n\t}\n\treturn\n}", "func newTask(ctx context.Context, cfg *taskConfig, f TaskFunc, args ...interface{}) *Task {\n\tctx, cancelCtx := context.WithCancel(ctx)\n\n\ttask := &Task{\n\t\tcfg: cfg,\n\n\t\tctx: ctx,\n\t\tcancelCtx: cancelCtx,\n\n\t\tf: f,\n\t\targs: args,\n\n\t\tstartedChan: make(chan struct{}),\n\t\trunningChan: make(chan struct{}),\n\t\tfinishedChan: make(chan struct{}),\n\n\t\tresultChan: make(chan TaskResult),\n\t}\n\n\treturn task\n}", "func (t *Task) Run() {\n\tt.tasker = tasks.get(t.Type)\n\n\tif t.errHandled(t.tasker.Do(t.Variables...)) {\n\t\treturn\n\t}\n\n\tt.NextRun = t.tasker.NextRun()\n\tt.Retry = 0 //reset any retries\n\tt.Owner = data.EmptyKey // throw it back into the queue\n\n\tif t.NextRun.IsZero() {\n\t\tt.Closed = true\n\t\tt.Completed = time.Now()\n\t}\n\n\terr := data.TaskUpdate(t, t.Key)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"taskKey\": t.Key,\n\t\t\t\"type\": t.Type,\n\t\t}).Errorf(\"An error occured when completing a task: %s\", err)\n\t}\n}", "func taskHandler(task *net.TCPConn) {\n\tworkLoadHandler()\n\twg.Done()\n}", "func RunTaskfile(appContext application.Context) {\n\tshell := execution.GetCommand(\"bin/task -p server ui\")\n\tshell.Dir = appContext.Root\n\tshell.Run()\n}" ]
[ "0.57467073", "0.5378316", "0.535708", "0.53224504", "0.52373546", "0.51839423", "0.51828736", "0.51617604", "0.51331645", "0.5115803", "0.5079198", "0.49825564", "0.49654242", "0.49452552", "0.49412638", "0.49362126", "0.49316382", "0.4887391", "0.48681155", "0.48676887", "0.48529476", "0.4838925", "0.481509", "0.47944313", "0.47912893", "0.47434556", "0.47433493", "0.4738791", "0.47310376", "0.47308496", "0.46833265", "0.46636698", "0.46600947", "0.46564943", "0.46487954", "0.46482116", "0.46393162", "0.4637977", "0.46359038", "0.46341255", "0.46314514", "0.46271896", "0.46245444", "0.46211216", "0.46209237", "0.4620601", "0.46185464", "0.46138927", "0.4602907", "0.46012923", "0.45892033", "0.45816627", "0.45787868", "0.45738807", "0.45662025", "0.45632237", "0.45608425", "0.45603096", "0.45587462", "0.45553112", "0.45482188", "0.45386177", "0.45373282", "0.45288435", "0.4525083", "0.45216158", "0.45175397", "0.45145345", "0.45145068", "0.45126817", "0.45073545", "0.45025694", "0.4500905", "0.44968265", "0.4485143", "0.44839862", "0.44829783", "0.44813484", "0.4476582", "0.44748598", "0.44733638", "0.44722798", "0.44683546", "0.44666702", "0.4466032", "0.44544426", "0.44540307", "0.44528255", "0.4444044", "0.44436073", "0.44414333", "0.4441104", "0.4440517", "0.44337383", "0.44268897", "0.4420544", "0.44195747", "0.44183895", "0.44124973", "0.4411145", "0.44041783" ]
0.0
-1
Intended to be executed as part of the pod monitoring loop, this fn (ultimately) checks with Docker whether the pod is running. It will only return false if the task is still registered and the pod is registered in Docker. Otherwise it returns true. If there's still a task record on file, but no pod in Docker, then we'll also send a TASK_LOST event.
func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool { // TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks) k.lock.Lock() defer k.lock.Unlock() // TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the // kubelet may constantly attempt to instantiate a pod as long as it's in the pod state that we're // handing to it. otherwise, we're probably reporting a TASK_LOST prematurely. Should probably // consult RestartPolicy to determine appropriate behavior. Should probably also gracefully handle // docker daemon restarts. if _, ok := k.tasks[taskId]; ok { if isKnownPod() { return false } else { log.Warningf("Detected lost pod, reporting lost task %v", taskId) k.reportLostTask(driver, taskId, messages.ContainersDisappeared) } } else { log.V(2).Infof("Task %v no longer registered, stop monitoring for lost pods", taskId) } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the kubelet\n\t// may constantly attempt to instantiate a pod as long as it's in the pod state that we're handing to it.\n\t// otherwise, we're probably reporting a TASK_LOST prematurely. Should probably consult RestartPolicy to\n\t// determine appropriate behavior. Should probably also gracefully handle docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}", "func IsTaskRunning() bool {\n\treturn persist.HasValue(taskPayloadKey)\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 onRunIsResolved(target *api.Container, run *api.Container) bool {\n\tif target.DesiredStatus >= api.ContainerCreated {\n\t\treturn run.KnownStatus >= api.ContainerRunning\n\t}\n\treturn false\n}", "func isRunning(on_node, operation, rcCode string) bool {\n\treturn on_node != \"\" && (operation == \"start\" || (operation == \"monitor\" && rcCode == \"0\"))\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 (t *task) IsRunning() bool {\n\treturn t.running\n}", "func isPodRunningAndReady(pod *v1.Pod) bool {\n\treturn pod.Status.Phase == v1.PodRunning && podutil.IsPodReady(pod) && pod.Status.PodIP != \"\"\n}", "func isPodRunning(pod *v1.Pod) bool {\n\tif pod.Status.Phase == v1.PodRunning {\n\t\t// If all conditions exists in ConditionTrue then service is guaranteed to be good.\n\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t// BEGIN WORKAROUND\n\t\t\t// Ignore condition Ready == false (i.e. consider the pod good assuming all other conditions are True)\n\t\t\t// Pods with readiness probes need special handling for resolution, see venice/cmd/services/resolver.go\n\t\t\tif condition.Type == v1.PodReady {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// END WORKAROUND\n\t\t\tif condition.Status != v1.ConditionTrue {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func (m *Machine) IsRunningSwarmingTask() bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\treturn m.runningTask\n}", "func (folderWatcher *FolderWatcher) IsRunning() bool {\n\treturn folderWatcher.running\n}", "func (d *dispatcher) monitorTask(taskID int64) (finished bool, subTaskErrs []error) {\n\t// TODO: Consider putting the following operations into a transaction.\n\tvar err error\n\td.task, err = d.taskMgr.GetGlobalTaskByID(taskID)\n\tif err != nil {\n\t\tlogutil.BgLogger().Error(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\treturn false, nil\n\t}\n\tswitch d.task.State {\n\tcase proto.TaskStateCancelling:\n\t\treturn false, []error{errors.New(\"cancel\")}\n\tcase proto.TaskStateReverting:\n\t\tcnt, err := d.taskMgr.GetSubtaskInStatesCnt(d.task.ID, proto.TaskStateRevertPending, proto.TaskStateReverting)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn cnt == 0, nil\n\tdefault:\n\t\tsubTaskErrs, err = d.taskMgr.CollectSubTaskError(d.task.ID)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"collect subtask error failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\tif len(subTaskErrs) > 0 {\n\t\t\treturn false, subTaskErrs\n\t\t}\n\t\t// check subtasks pending or running.\n\t\tcnt, err := d.taskMgr.GetSubtaskInStatesCnt(d.task.ID, proto.TaskStatePending, proto.TaskStateRunning)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn cnt == 0, nil\n\t}\n}", "func podRunningReady(p *v1.Pod) (bool, error) {\n\t// Check the phase is running.\n\tif p.Status.Phase != v1.PodRunning {\n\t\treturn false, fmt.Errorf(\"want pod '%s' on '%s' to be '%v' but was '%v'\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase)\n\t}\n\t// Check the ready condition is true.\n\n\tif !isPodReady(p) {\n\t\treturn false, fmt.Errorf(\"pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions)\n\t}\n\treturn true, nil\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 (p *statusUpdate) isOrphanTaskEvent(\n\tctx context.Context,\n\tevent *statusupdate.Event,\n) (bool, *pb_task.TaskInfo, error) {\n\ttaskInfo, err := p.taskStore.GetTaskByID(ctx, event.TaskID())\n\tif err != nil {\n\t\tif yarpcerrors.IsNotFound(err) {\n\t\t\t// if task runtime or config is not present in the DB,\n\t\t\t// then the task is orphan\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"mesos_task_id\": event.MesosTaskStatus(),\n\t\t\t\t\"task_status_event≠\": event.State().String(),\n\t\t\t}).Info(\"received status update for task not found in DB\")\n\t\t\treturn true, nil, nil\n\t\t}\n\n\t\tlog.WithError(err).\n\t\t\tWithField(\"task_id\", event.TaskID()).\n\t\t\tWithField(\"task_status_event\", event.MesosTaskStatus()).\n\t\t\tWithField(\"state\", event.State().String()).\n\t\t\tError(\"fail to find taskInfo for taskID for mesos event\")\n\t\treturn false, nil, err\n\t}\n\n\t// TODO p2k: verify v1 pod id in taskInfo\n\tif event.V0() != nil {\n\t\tdbTaskID := taskInfo.GetRuntime().GetMesosTaskId().GetValue()\n\t\tif dbTaskID != event.MesosTaskStatus().GetTaskId().GetValue() {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"orphan_task_id\": event.MesosTaskStatus().GetTaskId().GetValue(),\n\t\t\t\t\"db_task_id\": dbTaskID,\n\t\t\t\t\"db_task_runtime_state\": taskInfo.GetRuntime().GetState().String(),\n\t\t\t\t\"mesos_event_state\": event.State().String(),\n\t\t\t}).Info(\"received status update for orphan mesos task\")\n\t\t\treturn true, nil, nil\n\t\t}\n\t}\n\n\treturn false, taskInfo, nil\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 isContainerRunning(\n docker *client.Client, \n containerId string) (isrunning bool, err error) {\n\n inspect, err := docker.ContainerInspect(context.Background(), containerId)\n if err != nil {\n return\n }\n\n isrunning = inspect.State.Running\n return \n}", "func (d *DockerDriver) IsExist(TaskUUID string) []string {\n\tvar containerIDs = make([]string, 0)\n\n\tcli := d.getClient()\n\n\tcontainers, err := cli.ContainerList(context.TODO(), types.ContainerListOptions{})\n\tif err != nil {\n\t\tpanic(shadowerrors.ShadowError{\n\t\t\tOrigin: err,\n\t\t\tVisibleMessage: \"containers error\",\n\t\t})\n\t}\n\n\t// We go through the containers and pick the ones which match the task name and also they are in\n\t// running state. This should avoid situations the container is shutting down, request comes\n\t// and proxy sends it there.\n\tfor _, containerObject := range containers {\n\t\tfor _, name := range containerObject.Names {\n\t\t\tname = strings.Trim(name, \"/\")\n\t\t\tif strings.Split(name, \".\")[0] == TaskUUID && containerObject.Status == \"running\" {\n\t\t\t\tcontainerIDs = append(containerIDs, containerObject.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn containerIDs\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 (i *info) IsRunning() bool {\n\t_, ok := i.driver.activeContainers[i.ID]\n\treturn ok\n}", "func IsRunning(ep *endpoint.Endpoint) bool {\n\tif dockerClient == nil {\n\t\treturn false\n\t}\n\n\truntimeRunning := false\n\n\tnetworkID := ep.GetDockerNetworkID()\n\tcontainerID := ep.GetContainerID()\n\n\tif networkID != \"\" {\n\t\tnls, err := dockerClient.NetworkInspect(ctx.Background(), networkID)\n\t\tif client.IsErrNetworkNotFound(err) {\n\t\t\treturn false\n\t\t}\n\n\t\tif err == nil {\n\t\t\truntimeRunning = true\n\t\t\tfound := false\n\t\t\tfor _, v := range nls.Containers {\n\t\t\t\tif v.EndpointID == ep.DockerEndpointID {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\treturn found\n\t\t\t}\n\t\t}\n\t}\n\n\tif containerID != \"\" {\n\t\tcont, err := dockerClient.ContainerInspect(ctx.Background(), containerID)\n\t\tif client.IsErrContainerNotFound(err) {\n\t\t\treturn false\n\t\t}\n\n\t\tif err == nil {\n\t\t\truntimeRunning = true\n\n\t\t\t// Container may exist but is not in running state\n\t\t\treturn cont.State.Running\n\t\t}\n\t}\n\n\treturn !runtimeRunning\n}", "func (t *DeferredRecordingTaskImpl) IsRunning() bool {\n\treturn t.task.IsRunning()\n}", "func podIsExited(p *kcontainer.Pod) bool {\n\tfor _, c := range p.Containers {\n\t\tif c.State != kcontainer.ContainerStateExited {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func KubernetesPod() bool {\n\t_, exists := os.LookupEnv(\"KUBERNETES_PORT\")\n\treturn exists\n}", "func (k *KubeAPI) IsPodRunning(namespace, pod string) (bool, error) {\n\ttimeout := time.After(k.Timeout)\n\ttick := time.Tick(500 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\treturn false, fmt.Errorf(\"timed out waiting for pod to run: %s\", pod)\n\t\tcase <-tick:\n\t\t\tp, err := k.GetPod(namespace, pod)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tswitch p.Status.Phase {\n\t\t\tcase \"Pending\":\n\t\t\t\tcontinue\n\t\t\tcase \"ContainerCreating\":\n\t\t\t\tcontinue\n\t\t\tcase \"Failed\":\n\t\t\t\treturn false, fmt.Errorf(\"Pod failed to run: %s\", pod)\n\t\t\tcase \"Running\":\n\t\t\t\treturn true, nil\n\t\t\tcase \"Succeeded\":\n\t\t\t\treturn true, nil\n\t\t\tcase \"Unknown\":\n\t\t\t\treturn false, errors.New(\"Unknown error\")\n\t\t\tdefault:\n\t\t\t\treturn false, errors.New(\"Unknown pod status (this should not happen)\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (jm *JobManager) IsRunning(taskName string) (isRunning bool) {\n\tjm.Lock()\n\t_, isRunning = jm.tasks[taskName]\n\tjm.Unlock()\n\treturn\n}", "func (f *flushDaemon) isRunning() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\treturn f.stopC != nil\n}", "func (e *executor) isRunning(file string) *runInfo {\n\te.mRun.Lock()\n\tdefer e.mRun.Unlock()\n\treturn e.running[file]\n}", "func (p *procBase) Running() bool {\n\treturn p.cmd != nil\n}", "func (r *MonitorReconciler) checkInfraStatusRunning(infra infrav1.Infra) bool {\n\tif infra.Status.Status == infrav1.Running.String() {\n\t\treturn true\n\t}\n\tr.Logger.Info(\"infra status is not running\", \"infra name\", infra.Name, \"infra namespace\", infra.Namespace, \"infra status\", infra.Status.Status)\n\treturn false\n}", "func (r *RunCommand) onEvent(pod *corev1.Pod) error {\n\t// found more data races during unit testing with concurrent events coming in\n\tr.watchLock.Lock()\n\tdefer r.watchLock.Unlock()\n\tswitch pod.Status.Phase {\n\tcase corev1.PodRunning:\n\t\t// graceful time to wait for container start\n\t\ttime.Sleep(3 * time.Second)\n\t\t// start tailing container logs\n\t\tr.tailLogs(pod)\n\tcase corev1.PodFailed:\n\t\tmsg := \"\"\n\t\tbr, err := r.shpClientset.ShipwrightV1alpha1().BuildRuns(pod.Namespace).Get(r.cmd.Context(), r.buildRunName, metav1.GetOptions{})\n\t\tswitch {\n\t\tcase err == nil && br.IsCanceled():\n\t\t\tmsg = fmt.Sprintf(\"BuildRun '%s' has been canceled.\\n\", br.Name)\n\t\tcase err == nil && br.DeletionTimestamp != nil:\n\t\t\tmsg = fmt.Sprintf(\"BuildRun '%s' has been deleted.\\n\", br.Name)\n\t\tcase pod.DeletionTimestamp != nil:\n\t\t\tmsg = fmt.Sprintf(\"Pod '%s' has been deleted.\\n\", pod.GetName())\n\t\tdefault:\n\t\t\tmsg = fmt.Sprintf(\"Pod '%s' has failed!\\n\", pod.GetName())\n\t\t\terr = fmt.Errorf(\"build pod '%s' has failed\", pod.GetName())\n\t\t}\n\t\t// see if because of deletion or cancelation\n\t\tfmt.Fprintf(r.ioStreams.Out, msg)\n\t\tr.stop()\n\t\treturn err\n\tcase corev1.PodSucceeded:\n\t\tfmt.Fprintf(r.ioStreams.Out, \"Pod '%s' has succeeded!\\n\", pod.GetName())\n\t\tr.stop()\n\tdefault:\n\t\tfmt.Fprintf(r.ioStreams.Out, \"Pod '%s' is in state %q...\\n\", pod.GetName(), string(pod.Status.Phase))\n\t\t// handle any issues with pulling images that may fail\n\t\tfor _, c := range pod.Status.Conditions {\n\t\t\tif c.Type == corev1.PodInitialized || c.Type == corev1.ContainersReady {\n\t\t\t\tif c.Status == corev1.ConditionUnknown {\n\t\t\t\t\treturn fmt.Errorf(c.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (proc *Proc) IsAlive() bool {\n\tdir := fmt.Sprintf(\"/proc/%d\", proc.GetPid())\n\t_, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t\tlogger.Errorf(\"Error while checking process state: %s\", err)\n\t\treturn false\n\t}\n\treturn true\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 (worker *K8SPodWorker) Do() error {\n\n\tvar pod *apiv1.Pod\n\tvar err error\n\n\tcheck := func() (bool, error) {\n\n\t\t// change pod here\n\t\tpod, err = worker.Client().CoreV1().Pods(worker.namespace).Get(worker.pod.Name, meta_v1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tswitch pod.Status.Phase {\n\t\tcase apiv1.PodPending:\n\t\t\treturn false, nil\n\t\tcase apiv1.PodRunning:\n\t\t\treturn true, nil\n\t\tdefault:\n\t\t\treturn false, fmt.Errorf(\"K8SCloud: get an error pod status phase[%s]\", pod.Status.Phase)\n\t\t}\n\t}\n\n\tpod, err = worker.Client().CoreV1().Pods(worker.namespace).Create(worker.pod)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// wait until pod is running\n\terr = wait.Poll(7*time.Second, 2*time.Minute, check)\n\tif err != nil {\n\t\tlogdog.Error(\"K8SPodWorker: do worker error\", logdog.Fields{\"err\": err})\n\t\treturn err\n\t}\n\n\t// add time\n\tworker.createTime = time.Now()\n\tworker.dueTime = worker.createTime.Add(time.Duration(WorkerTimeout))\n\n\tworker.pod = pod\n\n\treturn nil\n}", "func (r *StorageImpl) IsTaskDelayed(ctx context.Context, qid, tid string) (bool, error) {\n\tvar res bool\n\tif err := retry(ctx, func() error {\n\t\tvar err error\n\t\tvar cursor uint64 = 0\n\t\tfor {\n\t\t\tvar found []string\n\t\t\tfound, cursor, err = r.client.ZScan(keyTreeDelayed(qid), cursor, tid, 50).Result()\n\t\t\tif err != nil {\n\t\t\t\treturn newTempError(err)\n\t\t\t}\n\t\t\tif len(found) > 0 {\n\t\t\t\tres = true\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif cursor == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}, defaultRetryLimit); err != nil {\n\t\treturn false, errors.Wrap(err, \"ZSCAN\")\n\t}\n\n\treturn res, nil\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 (w *worker) isRunningCorrectTask(actionDigest *remoteexecution.Digest) bool {\n\tt := w.currentTask\n\tif t == nil {\n\t\treturn false\n\t}\n\tdesiredDigest := t.desiredState.ActionDigest\n\treturn proto.Equal(actionDigest, desiredDigest)\n}", "func (svc *service) verifyStillRunning() (procStatData []string, stillRunning bool) {\n\tprocStatData, err := svc.readProcStatData()\n\tif err != nil {\n\t\tsvc.reset()\n\t\treturn nil, false\n\t}\n\tcurrentProcStartTime, err := strconv.ParseInt(procStatData[PROC_PID_STAT_STARTTIME], 10, 64)\n\tif err != nil {\n\t\tlog.Fatalf(\"garbage start_time for pid %d\", svc.pid)\n\t}\n\tif currentProcStartTime != svc.procStatStartTime {\n\t\tsvc.reset()\n\t\treturn nil, false\n\t}\n\treturn procStatData, true\n}", "func (w *Watcher) isWatching(pid int, event uint32) bool {\r\n\tw.watchesMutex.Lock()\r\n\tdefer w.watchesMutex.Unlock()\r\n\r\n\tif watch, ok := w.watches[pid]; ok {\r\n\t\treturn (watch.flags & event) == event\r\n\t}\r\n\t//for any process\r\n\tif watch, ok := w.watches[-1]; ok {\r\n\t\treturn (watch.flags & event) == event\r\n\t}\r\n\treturn false\r\n}", "func (w *worker) isRunning() bool {\n\treturn atomic.LoadInt32(&w.running) == 1\n}", "func isApplicationReady(c *types.ClusterConfig, kotsAppSpec *types.KOTSApplicationSpec) (bool, error) {\n\t// right now, we just check the status informers\n\n\tpathToKOTSBinary, err := downloadKOTSBinary(kotsAppSpec.Version)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to get kots binary\")\n\t}\n\n\tkubeconfigFile, err := ioutil.TempFile(\"\", \"kots\")\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to create temp file\")\n\t}\n\tdefer os.RemoveAll(kubeconfigFile.Name())\n\tif err := ioutil.WriteFile(kubeconfigFile.Name(), []byte(c.Kubeconfig), 0644); err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to create kubeconfig\")\n\t}\n\n\tnamespace := kotsAppSpec.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = kotsAppSpec.App\n\t}\n\n\tappSlug, err := getAppSlug(c, kotsAppSpec)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to get app slug\")\n\t}\n\n\targs := []string{\n\t\t\"--namespace\", namespace,\n\t\t\"--kubeconfig\", kubeconfigFile.Name(),\n\t}\n\n\tallArgs := []string{\n\t\t\"app-status\",\n\t\t\"-n\", namespace,\n\t\tappSlug,\n\t}\n\tallArgs = append(allArgs, args...)\n\tcmd := exec.Command(pathToKOTSBinary, allArgs...)\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tcmd.Start()\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- cmd.Wait()\n\t}()\n\ttimeout := time.After(time.Second * 5)\n\n\tselect {\n\tcase <-timeout:\n\t\tcmd.Process.Kill()\n\t\tfmt.Printf(\"timedout waiting for app ready. received std out: %s\\n\", stdout.String())\n\t\treturn false, nil\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrap(err, \"failed to run kots\")\n\t\t}\n\n\t\tappStatusResponse := AppStatusResponse{}\n\t\tif err := json.Unmarshal(stdout.Bytes(), &appStatusResponse); err != nil {\n\t\t\treturn false, errors.Wrap(err, \"faile to parse app status response\")\n\t\t}\n\n\t\treturn appStatusResponse.AppStatus.State == \"ready\", nil\n\t}\n}", "func (c CommitterProbe) IsTTLRunning() bool {\n\tstate := atomic.LoadUint32((*uint32)(&c.ttlManager.state))\n\treturn state == uint32(stateRunning)\n}", "func checkPodsFromTask(cluster *imec_db.DB_INFRASTRUCTURE_CLUSTER, namespace string, id string, expectedReplicas int) (string, map[string]interface{}, error) {\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Getting pods ...\")\n\n\t// get pods from task\n\t_, result, err := common.HTTPGETStruct(\n\t\turls.GetPathKubernetesPodsApp(cluster, namespace, id),\n\t\t//cfg.Config.Clusters[clusterIndex].KubernetesEndPoint+\"/api/v1/namespaces/\"+namespace+\"/pods?labelSelector=app=\"+id,\n\t\ttrue)\n\tif err != nil {\n\t\tlog.Error(pathLOG+\"COMPSs [checkPodsFromTask] ERROR\", err)\n\t\treturn \"error\", nil, err\n\t}\n\n\t// items\n\titems := result[\"items\"].([]interface{})\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Retrieved pods = \" + strconv.Itoa(len(items)))\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Expected pods = \" + strconv.Itoa(expectedReplicas))\n\n\tif len(items) == expectedReplicas {\n\t\treturn \"ready\", result, err\n\t}\n\n\treturn \"not-ready\", result, err\n}", "func (s *DockerKubeletService) IsReady() bool {\n\tpod, err := s.getPod()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn kubelet.IsPodReady(pod)\n}", "func PodRunning() PodWaitCriterion {\n\treturn func(a *MemberAwaitility, pod v1.Pod) bool {\n\t\tif pod.Status.Phase == v1.PodRunning {\n\t\t\ta.T.Logf(\"pod '%s` in the running phase\", pod.Name)\n\t\t\treturn true\n\t\t}\n\t\ta.T.Logf(\"Pod '%s' actual phase: '%s'; Expected: '%s'\", pod.Name, pod.Status.Phase, v1.PodRunning)\n\t\treturn false\n\t}\n}", "func (n *Ncd) IsRunning() bool {\n\treturn n.rtconf.Running\n}", "func PodRunningReady(p *v1.Pod) (bool, error) {\n\tif !hasReadyCondition(p) {\n\t\treturn false, nil\n\t}\n\n\t// Check the phase is running.\n\tif p.Status.Phase != v1.PodRunning {\n\t\treturn false, fmt.Errorf(\"want pod '%s' on '%s' to be '%v' but was '%v'\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase)\n\t}\n\t// Check the ready condition is true.\n\tif !IsPodReady(p) {\n\t\treturn false, fmt.Errorf(\"pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions)\n\t}\n\treturn true, nil\n}", "func (s *Supervisor) IsAlive() (int, bool) {\n\tr, err := execCommand(s.name, []string{\"status\", s.service})\n\tif err != nil {\n\t\treturn -1, false\n\t}\n\treturn -1, strings.Contains(r, \"RUNNING\")\n}", "func isDuplicateStateUpdate(\n\ttaskInfo *pb_task.TaskInfo,\n\tupdateEvent *statusupdate.Event,\n) bool {\n\tif updateEvent.State() != taskInfo.GetRuntime().GetState() {\n\t\treturn false\n\t}\n\n\tmesosTaskStatus := updateEvent.MesosTaskStatus()\n\tpodEvent := updateEvent.PodEvent()\n\n\tif updateEvent.State() != pb_task.TaskState_RUNNING {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if state is not RUNNING\")\n\t\treturn true\n\t}\n\n\tif taskInfo.GetConfig().GetHealthCheck() == nil ||\n\t\t!taskInfo.GetConfig().GetHealthCheck().GetEnabled() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check is not configured or \" +\n\t\t\t\"disabled\")\n\t\treturn true\n\t}\n\n\tnewStateReason := updateEvent.Reason()\n\t// TODO p2k: not sure which kubelet reason matches this.\n\t// Should we skip some status updates from kubelets?\n\tif newStateReason != mesos.TaskStatus_REASON_TASK_HEALTH_CHECK_STATUS_UPDATED.String() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if status update reason is not from health check\")\n\t\treturn true\n\t}\n\n\t// Current behavior will log consecutive negative health check results\n\t// ToDo (varung): Evaluate if consecutive negative results should be logged or not\n\tisPreviousStateHealthy := taskInfo.GetRuntime().GetHealthy() == pb_task.HealthState_HEALTHY\n\tif !isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"log each negative health check result\")\n\t\treturn false\n\t}\n\n\tif updateEvent.Healthy() == isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check result is positive consecutively\")\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *Reader) getTaskRunPodNames(run *v1.TaskRun) (<-chan string, <-chan error, error) {\n\topts := metav1.ListOptions{\n\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", r.run).String(),\n\t}\n\n\twatchRun, err := actions.Watch(taskrunGroupResource, r.clients, r.ns, opts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpodC := make(chan string)\n\terrC := make(chan error)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(podC)\n\t\t\tclose(errC)\n\t\t\twatchRun.Stop()\n\t\t}()\n\n\t\tpodMap := make(map[string]bool)\n\t\taddPod := func(name string) {\n\t\t\tif _, ok := podMap[name]; !ok {\n\t\t\t\tpodMap[name] = true\n\t\t\t\tpodC <- name\n\t\t\t}\n\t\t}\n\n\t\tif len(run.Status.RetriesStatus) != 0 {\n\t\t\tfor _, retryStatus := range run.Status.RetriesStatus {\n\t\t\t\taddPod(retryStatus.PodName)\n\t\t\t}\n\t\t}\n\t\tif run.Status.PodName != \"\" {\n\t\t\taddPod(run.Status.PodName)\n\t\t}\n\n\t\ttimeout := time.After(r.activityTimeout)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watchRun.ResultChan():\n\t\t\t\tvar err error\n\t\t\t\trun, err = cast2taskrun(event.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrC <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif run.Status.PodName != \"\" {\n\t\t\t\t\taddPod(run.Status.PodName)\n\t\t\t\t\tif areRetriesScheduled(run, r.retries) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase <-timeout:\n\t\t\t\t// Check if taskrun failed on start up\n\t\t\t\tif err := hasTaskRunFailed(run, r.task, r.retries); err != nil {\n\t\t\t\t\terrC <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// check if pod has been started and has a name\n\t\t\t\tif run.HasStarted() && run.Status.PodName != \"\" {\n\t\t\t\t\tif !areRetriesScheduled(run, r.retries) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terrC <- fmt.Errorf(\"task %s create has not started yet or pod for task not yet available\", r.task)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn podC, errC, nil\n}", "func (c Container) IsRunning() bool {\n\treturn c.containerInfo.State.Running\n}", "func checkRunningWithinDocker() bool {\n\t// Detect if we are running inside Docker; https://github.com/AppImage/AppImageKit/issues/912\n\t// If the file /.dockerenv exists, and/or if /proc/1/cgroup begins with /lxc/ or /docker/\n\tres, err := ioutil.ReadFile(\"/proc/1/cgroup\")\n\tif err == nil {\n\t\t// Do not exit if ioutil.ReadFile(\"/proc/1/cgroup\") fails. This happens, e.g., on FreeBSD\n\t\tif strings.HasPrefix(string(res), \"/lxc\") || strings.HasPrefix(string(res), \"/docker\") || helpers.Exists(\"/.dockerenv\") == true {\n\t\t\tlog.Println(\"Running inside Docker. Please make sure that the environment variables from Travis CI\")\n\t\t\tlog.Println(\"available inside Docker if you are running on Travis CI.\")\n\t\t\tlog.Println(\"This can be achieved by using something along the lines of 'docker run --env-file <(env)'.\")\n\t\t\tlog.Println(\"Please see https://github.com/docker/cli/issues/2210.\")\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n\n}", "func hasNotReadyContainer(p v1.Pod) bool {\n\tfor _, containerStatus := range p.Status.ContainerStatuses {\n\t\tif containerStatus.Ready == false {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isPodFailed(restartLimit int32, pod *v1.Pod) bool {\n\tif pod.Spec.RestartPolicy != v1.RestartPolicyOnFailure {\n\t\treturn false\n\t}\n\n\trestartCount := int32(0)\n\tfor i := range pod.Status.InitContainerStatuses {\n\t\tstat := pod.Status.InitContainerStatuses[i]\n\t\trestartCount += stat.RestartCount\n\t}\n\tfor i := range pod.Status.ContainerStatuses {\n\t\tstat := pod.Status.ContainerStatuses[i]\n\t\trestartCount += stat.RestartCount\n\t}\n\n\treturn restartCount > restartLimit\n}", "func (c *Container) RunningKafka() bool {\n\treturn c.Config.Image == \"kafkadocker_kafka\"\n}", "func (mgr *manager) IsReadyPod(pod *apiv1.Pod) bool {\n\t// since its a utility function, just ensuring there is no nil pointer exception\n\tif pod == nil {\n\t\treturn false\n\t}\n\n\t// pod is in \"Terminating\" status if deletionTimestamp is not nil\n\t// https://github.com/kubernetes/kubernetes/issues/61376\n\tif pod.ObjectMeta.DeletionTimestamp != nil {\n\t\treturn false\n\t}\n\n\tfor _, cStatus := range pod.Status.ContainerStatuses {\n\t\tif cStatus.Ready {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (v *ProcTableImpl) IsRunning(pvName string) bool {\n\tv.mutex.RLock()\n\tdefer v.mutex.RUnlock()\n\n\tif entry, ok := v.procTable[pvName]; !ok || entry.Status != CSRunning {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func monitored(pod *api.Pod, notMonitoredNodes map[string]struct{}) bool {\n\tif _, exist := notMonitoredNodes[pod.Spec.NodeName]; exist {\n\t\treturn false\n\t}\n\n\tif isMirrorPod(pod) || isPodCreatedBy(pod, Kind_DaemonSet) {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsDockerRunning() bool {\n\t_, err := docker.GetDockerUtil()\n\treturn err == nil\n}", "func (t *Task) Failed() bool {\n\tt.group.mutex.Lock()\n\tresult := (t.state == statePanicked || t.err != nil)\n\tt.group.mutex.Unlock()\n\treturn result\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 containerRunningById(id string) (bool, error) {\n\tcontainers, err := getContainers()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, c := range containers {\n\t\tif c.ID == id {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (r *RecordStream) Running() bool { return r.state == running }", "func (t ResolvedPipelineRunTask) IsStarted() bool {\n\tif t.IsCustomTask() {\n\t\treturn t.Run != nil && t.Run.Status.GetCondition(apis.ConditionSucceeded) != nil\n\n\t}\n\treturn t.TaskRun != nil && t.TaskRun.Status.GetCondition(apis.ConditionSucceeded) != nil\n}", "func (handler *AsyncHandler) Run(podEvent *PodAsyncEvent) bool {\n\tlog.Info(\"a new event has arrived for asynch handling\")\n\tlog.Info(\"\\t\", podEvent.ShortString())\n\tif handler.isRunning() {\n\t\thandler.events[podEvent.pod.Name] = podEvent\n\t} else {\n\t\thandler.events[podEvent.pod.Name] = podEvent\n\t\tgo handler.run()\n\t}\n\treturn true\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 (transmuxer *Transmuxer) IsRunning() bool {\n\treturn transmuxer.running\n}", "func (s *SegmentUpdateWorker) IsRunning() bool {\n\treturn s.lifecycle.IsRunning()\n}", "func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode task state from handle: %v\", err)\n\t}\n\td.logger.Debug(\"Checking for recoverable task\", \"task\", handle.Config.Name, \"taskid\", handle.Config.ID, \"container\", taskState.ContainerID)\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, taskState.ContainerID)\n\tif err != nil {\n\t\td.logger.Warn(\"Recovery lookup failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: taskState.ContainerID,\n\t\tdriver: d,\n\t\ttaskConfig: taskState.TaskConfig,\n\t\tprocState: drivers.TaskStateUnknown,\n\t\tstartedAt: taskState.StartedAt,\n\t\texitResult: &drivers.ExitResult{},\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tif inspectData.State.Running {\n\t\td.logger.Info(\"Recovered a still running container\", \"container\", inspectData.State.Pid)\n\t\th.procState = drivers.TaskStateRunning\n\t} else if inspectData.State.Status == \"exited\" {\n\t\t// are we allowed to restart a stopped container?\n\t\tif d.config.RecoverStopped {\n\t\t\td.logger.Debug(\"Found a stopped container, try to start it\", \"container\", inspectData.State.Pid)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery restart failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\t\t} else {\n\t\t\t\td.logger.Info(\"Restarted a container during recovery\", \"container\", inspectData.ID)\n\t\t\t\th.procState = drivers.TaskStateRunning\n\t\t\t}\n\t\t} else {\n\t\t\t// no, let's cleanup here to prepare for a StartTask()\n\t\t\td.logger.Debug(\"Found a stopped container, removing it\", \"container\", inspectData.ID)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery cleanup failed\", \"task\", handle.Config.ID, \"container\", inspectData.ID)\n\t\t\t}\n\t\t\th.procState = drivers.TaskStateExited\n\t\t}\n\t} else {\n\t\td.logger.Warn(\"Recovery restart failed, unknown container state\", \"state\", inspectData.State.Status, \"container\", taskState.ContainerID)\n\t\th.procState = drivers.TaskStateUnknown\n\t}\n\n\td.tasks.Set(taskState.TaskConfig.ID, h)\n\n\tgo h.runContainerMonitor()\n\td.logger.Debug(\"Recovered container handle\", \"container\", taskState.ContainerID)\n\n\treturn nil\n}", "func TaskCompleted(task *api.Task) bool {\n\tif task.KnownStatus < task.DesiredStatus {\n\t\treturn false\n\t}\n\tfor _, container := range task.Containers {\n\t\tif container.KnownStatus < container.DesiredStatus {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsRunningOn() bool {\n\tif _, err := GetHostname(); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func (b *Backtest) IsRunning() (ret bool) {\n\treturn b.running\n}", "func isPodComplete(pod *corev1.Pod) bool {\n\treturn pod != nil && pod.Status.Phase == corev1.PodSucceeded\n}", "func (o *Run) HasTaskID() bool {\n\tif o != nil && o.TaskID != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func Isalive( pid int ) bool {\n\tcmd := \"kill -0 \" + strconv.Itoa(pid)\n\tvar Errout bytes.Buffer\n\tcmds := exec.Command(\"sh\", \"-c\",cmd )\n\tcmds.Stderr = &Errout\n\tcmds.Run()\n\tif Errout.String() != \"\"{\n\t\treturn false\n\t}\n\treturn true\n}", "func detectContainer() bool {\n\tif runtime.GOOS != \"linux\" {\n\t\treturn false\n\t}\n\n\tfile, err := os.Open(\"/proc/1/cgroup\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer file.Close()\n\n\ti := 0\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\ti++\n\t\tif i > 1000 {\n\t\t\treturn false\n\t\t}\n\n\t\tline := scanner.Text()\n\t\tparts := strings.SplitN(line, \":\", 3)\n\t\tif len(parts) < 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(parts[2], \"docker\") ||\n\t\t\tstrings.Contains(parts[2], \"lxc\") ||\n\t\t\tstrings.Contains(parts[2], \"moby\") {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (d *portworx) IsIOsInProgressForTheVolume(n *node.Node, volumeNameOrID string) (bool, error) {\n\n\tlog.Infof(\"Got vol-id [%s] for checking IOs\", volumeNameOrID)\n\tcmd := fmt.Sprintf(\"%s v i %s| grep -e 'IOs in progress'\", d.getPxctlPath(*n), volumeNameOrID)\n\n\tout, err := d.nodeDriver.RunCommandWithNoRetry(*n, cmd, node.ConnectionOpts{\n\t\tTimeout: 2 * time.Minute,\n\t\tTimeBeforeRetry: 10 * time.Second,\n\t})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tline := strings.Trim(out, \" \")\n\tdata := strings.Split(line, \":\")[1]\n\tdata = strings.Trim(data, \"\\n\")\n\tdata = strings.Trim(data, \" \")\n\tval, err := strconv.Atoi(data)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif val > 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func IsContainerRunning(c *check.C, cname string) (bool, error) {\n\treturn isContainerStateEqual(c, cname, \"running\")\n}", "func (jm *JobManager) shouldRunTask(t Task) bool {\n\t_, serial := t.(SerialProvider)\n\tif serial {\n\t\t_, hasTask := jm.tasks[t.Name()]\n\t\treturn !hasTask\n\t}\n\treturn true\n}", "func (m *Master) Done() bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tfor _, val := range m.RTasks {\n\t\tif val.status == IDLE || val.status == RUNNING {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (r *StorageImpl) IsTaskTaken(ctx context.Context, qid, tid string) (bool, error) {\n\tsize, err := r.GetTakenListLen(ctx, qid)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"get taken list length\")\n\t}\n\n\treturn r.isTaskInList(ctx, keyListTaken(qid), tid, size)\n}", "func (task Task) IsPaused() bool {\n\treturn task.Status != TaskPaused\n}", "func (n *NodeVM) IsRunning() bool {\n\treturn n.running\n}", "func (r Ref) IsOnlyTask() bool {\n\treturn strings.HasPrefix(string(r), \":\")\n}", "func (p *DockerPod) Start() error {\n\tp.status = container.PodStatus_STARTING\n\tp.message = \"Pod is starting\"\n\t//add pod ipaddr to ENV\n\tenvHost := container.BcsKV{\n\t\tKey: \"BCS_CONTAINER_IP\",\n\t\tValue: util.GetIPAddress(),\n\t}\n\n\tlogs.Infof(\"docker pod start container...\")\n\n\tfor name, task := range p.conTasks {\n\t\t//create container attach to network infrastructure\n\t\ttask.NetworkName = \"container:\" + p.GetContainerID()\n\t\ttask.RuntimeConf = &container.BcsContainerInfo{\n\t\t\tName: name,\n\t\t}\n\t\ttask.Env = append(task.Env, envHost)\n\t\t//assignment for environments\n\t\tcontainer.EnvOperCopy(task)\n\t\tvar extendedErr error\n\t\t//if task contains extended resources, need connect device plugin to allocate resources\n\t\tfor _, ex := range task.ExtendedResources {\n\t\t\tlogs.Infof(\"task %s contains extended resource %s, then allocate it\", task.TaskId, ex.Name)\n\t\t\tenvs, err := p.resourceManager.ApplyExtendedResources(ex, p.netTask.TaskId)\n\t\t\tif err != nil {\n\t\t\t\tlogs.Errorf(\"apply extended resource failed, err %s\", err.Error())\n\t\t\t\textendedErr = err\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlogs.Infof(\"add env %v for task %s\", envs, task.TaskId)\n\n\t\t\t//append response docker envs to task.envs\n\t\t\tfor k, v := range envs {\n\t\t\t\tkv := container.BcsKV{\n\t\t\t\t\tKey: k,\n\t\t\t\t\tValue: v,\n\t\t\t\t}\n\t\t\t\ttask.Env = append(task.Env, kv)\n\t\t\t}\n\t\t}\n\n\t\t//if allocate extended resource failed, then return and exit\n\t\tif extendedErr != nil {\n\t\t\tlogs.Errorf(extendedErr.Error())\n\t\t\ttask.RuntimeConf.Status = container.ContainerStatus_EXITED\n\t\t\ttask.RuntimeConf.Message = extendedErr.Error()\n\t\t\tp.startFailedStop(extendedErr)\n\t\t\treturn extendedErr\n\t\t}\n\t\tcreatedInst, createErr := p.conClient.CreateContainer(name, task)\n\t\tif createErr != nil {\n\t\t\tlogs.Errorf(\"DockerPod create %s with name %s failed, err: %s\\n\", task.Image, name, createErr.Error())\n\t\t\ttask.RuntimeConf.Status = container.ContainerStatus_EXITED\n\t\t\ttask.RuntimeConf.Message = createErr.Error()\n\t\t\tp.startFailedStop(createErr)\n\t\t\treturn createErr\n\t\t}\n\t\ttask.RuntimeConf.ID = createdInst.ID\n\t\ttask.RuntimeConf.NodeAddress = util.GetIPAddress()\n\t\ttask.RuntimeConf.IPAddress = p.cnmIPAddr\n\t\ttask.RuntimeConf.Status = container.ContainerStatus_CREATED\n\t\ttask.RuntimeConf.Message = \"container created\"\n\t\ttask.RuntimeConf.Resource = task.Resource\n\n\t\tlogs.Infof(\"task %s cpu %f mem %f\", task.TaskId, task.RuntimeConf.Resource.Cpus, task.RuntimeConf.Resource.Mem)\n\n\t\t//crate success, event callback before start\n\t\tif p.events != nil && p.events.PreStart != nil {\n\t\t\tpreErr := p.events.PreStart(task)\n\t\t\tif preErr != nil {\n\t\t\t\tlogs.Errorf(\"DockerPod PreStart setting container %s err: %s\\n\", task.RuntimeConf.ID, preErr.Error())\n\t\t\t\tp.conClient.RemoveContainer(task.RuntimeConf.ID, true)\n\t\t\t\ttask.RuntimeConf.Status = container.ContainerStatus_EXITED\n\t\t\t\ttask.RuntimeConf.Message = preErr.Error()\n\t\t\t\tp.startFailedStop(createErr)\n\t\t\t\treturn preErr\n\t\t\t}\n\t\t}\n\t\t//ready to starting\n\t\tif err := p.conClient.StartContainer(task.RuntimeConf.Name); err != nil {\n\t\t\tlogs.Errorf(\"DockerPod Start %s with name %s failed, err: %s\\n\", task.Image, name, err.Error())\n\t\t\ttask.RuntimeConf.Status = container.ContainerStatus_EXITED\n\t\t\ttask.RuntimeConf.Message = err.Error()\n\t\t\tp.conClient.RemoveContainer(task.RuntimeConf.Name, true)\n\t\t\tp.startFailedStop(err)\n\t\t\treturn err\n\t\t}\n\t\ttask.RuntimeConf.Message = \"container is starting\"\n\t\tif p.events != nil && p.events.PostStart != nil {\n\t\t\tp.events.PostStart(task)\n\t\t}\n\t\tp.runningContainer[task.RuntimeConf.Name] = task.RuntimeConf\n\t\tlogs.Infof(\"Pod add container %s in running container.\\n\", task.RuntimeConf.Name)\n\t}\n\tp.conTasks[p.netTask.Name] = p.netTask\n\t//all container starting, start containerWatch\n\twatchCxt, _ := context.WithCancel(p.podCxt)\n\tgo p.containersWatch(watchCxt)\n\treturn nil\n}", "func (e *etcdCacheEntry) IsWatching() bool {\n e.RLock()\n defer e.RUnlock()\n return e.watching\n}", "func (s *Stopwatch) isRunning() bool {\n\treturn !s.refTime.IsZero()\n}", "func (s *Scanner) IsRunning() bool {\n\treturn s.state == running\n}", "func (a *apiServer) isTaskTerminalFunc(\n\ttaskID model.TaskID, buffer time.Duration,\n) api.TerminationCheckFn {\n\treturn func() (bool, error) {\n\t\tswitch task, err := a.m.db.TaskByID(taskID); {\n\t\tcase err != nil:\n\t\t\treturn true, err\n\t\tcase task.EndTime != nil && task.EndTime.UTC().Add(buffer).Before(time.Now().UTC()):\n\t\t\treturn true, nil\n\t\tdefault:\n\t\t\treturn false, nil\n\t\t}\n\t}\n}", "func WaitForPodStateRunning(core coreclient.CoreV1Interface, podName, ns string, timeout, interval time.Duration) error {\n\treturn wait.PollImmediate(interval, timeout, func() (done bool, err error) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tpod, err := core.Pods(ns).Get(ctx, podName, metav1.GetOptions{})\n\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tswitch pod.Status.Phase {\n\t\tcase corev1.PodRunning:\n\t\t\treturn true, nil\n\t\tcase corev1.PodFailed, corev1.PodSucceeded:\n\t\t\treturn false, errors.New(\"pod failed or succeeded but is not running\")\n\t\t}\n\t\treturn false, nil\n\t})\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 (p *DockerPod) IsHealthy() bool {\n\treturn p.healthy\n}", "func (t Task) IsDoneNow() bool {\n return t.Complete || time.Now().Before(t.SnoozedUntil)\n}", "func IsPodAvailable(pod *corev1.Pod) bool {\n\tfor _, containerStatus := range pod.Status.ContainerStatuses {\n\t\tisContainerStarted := containerStatus.Started\n\t\tisContainerReady := containerStatus.Ready\n\n\t\tif !isContainerReady || (isContainerStarted != nil && *isContainerStarted == false) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn pod.Status.Phase == corev1.PodRunning\n}", "func updateTaskState(task *api.Task) api.TaskStatus {\n\t//The task is the minimum status of all its essential containers unless the\n\t//status is terminal in which case it's that status\n\tlog.Debug(\"Updating task\", \"task\", task)\n\n\t// minContainerStatus is the minimum status of all essential containers\n\tminContainerStatus := api.ContainerDead + 1\n\t// minContainerStatus is the minimum status of all containers to be used in\n\t// the edge case of no essential containers\n\tabsoluteMinContainerStatus := minContainerStatus\n\tfor _, cont := range task.Containers {\n\t\tlog.Debug(\"On container\", \"cont\", cont)\n\t\tif cont.KnownStatus < absoluteMinContainerStatus {\n\t\t\tabsoluteMinContainerStatus = cont.KnownStatus\n\t\t}\n\t\tif !cont.Essential {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Terminal states\n\t\tif cont.KnownStatus == api.ContainerStopped {\n\t\t\tif task.KnownStatus < api.TaskStopped {\n\t\t\t\ttask.KnownStatus = api.TaskStopped\n\t\t\t\treturn task.KnownStatus\n\t\t\t}\n\t\t} else if cont.KnownStatus == api.ContainerDead {\n\t\t\tif task.KnownStatus < api.TaskDead {\n\t\t\t\ttask.KnownStatus = api.TaskDead\n\t\t\t\treturn task.KnownStatus\n\t\t\t}\n\t\t}\n\t\t// Non-terminal\n\t\tif cont.KnownStatus < minContainerStatus {\n\t\t\tminContainerStatus = cont.KnownStatus\n\t\t}\n\t}\n\n\tif minContainerStatus == api.ContainerDead+1 {\n\t\tlog.Warn(\"Task with no essential containers; all properly formed tasks should have at least one essential container\", \"task\", task)\n\n\t\t// If there's no essential containers, let's just assume the container\n\t\t// with the earliest status is essential and proceed.\n\t\tminContainerStatus = absoluteMinContainerStatus\n\t}\n\n\tlog.Info(\"MinContainerStatus is \" + minContainerStatus.String())\n\n\tif minContainerStatus == api.ContainerCreated {\n\t\tif task.KnownStatus < api.TaskCreated {\n\t\t\ttask.KnownStatus = api.TaskCreated\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerRunning {\n\t\tif task.KnownStatus < api.TaskRunning {\n\t\t\ttask.KnownStatus = api.TaskRunning\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerStopped {\n\t\tif task.KnownStatus < api.TaskStopped {\n\t\t\ttask.KnownStatus = api.TaskStopped\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerDead {\n\t\tif task.KnownStatus < api.TaskDead {\n\t\t\ttask.KnownStatus = api.TaskDead\n\t\t\treturn task.KnownStatus\n\t\t}\n\t}\n\treturn api.TaskStatusNone\n}", "func IsRunningInDocker() bool {\n\tif _, err := os.Stat(\"/.dockerenv\"); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (n *ParDo) HasOnTimer() bool {\n\treturn n.TimerTracker != nil\n}", "func (p *AbstractRunProvider) IsRunning() bool {\n\treturn p.running\n}", "func (d *Docker) IsDaemonRunning(ctx context.Context) bool {\n\tvar err error\n\tutils.WithTimeout(ctx, d.config.GlobalConnectionTimeout, func(ctx context.Context) {\n\t\t_, err = d.client.Ping(ctx)\n\t})\n\tif err != nil {\n\t\tlog.WithFunc(\"IsDaemonRunning\").Error(ctx, err, \"connect to docker daemon failed\")\n\t\treturn false\n\t}\n\treturn true\n}", "func IsRunning() bool {\n\treturn defaultDaemon.IsRunning()\n}" ]
[ "0.65130603", "0.60245293", "0.59841156", "0.5829231", "0.5784136", "0.57519615", "0.57033616", "0.569658", "0.56850153", "0.56686944", "0.56435555", "0.5642727", "0.5637483", "0.56374794", "0.5601638", "0.55919397", "0.55881757", "0.555765", "0.5501637", "0.5492997", "0.5483551", "0.54582953", "0.5388848", "0.5369454", "0.5368483", "0.5368173", "0.53668547", "0.52968407", "0.5273486", "0.5262714", "0.5253366", "0.5250331", "0.52487934", "0.52329236", "0.5224821", "0.52163965", "0.5215048", "0.5212442", "0.5207162", "0.51930565", "0.5189702", "0.5183692", "0.5181943", "0.5170575", "0.51596475", "0.5157963", "0.5151698", "0.5150525", "0.51499486", "0.5138434", "0.5137211", "0.5134501", "0.5131981", "0.5124236", "0.512041", "0.51102525", "0.5110145", "0.5104245", "0.5095401", "0.50892556", "0.5066852", "0.5053353", "0.5050527", "0.5047943", "0.50475556", "0.5037012", "0.50365514", "0.5033578", "0.5032462", "0.5028694", "0.50278157", "0.5027655", "0.50257736", "0.5024936", "0.5018268", "0.50164104", "0.5011875", "0.50021344", "0.50006443", "0.49824148", "0.49815035", "0.49804595", "0.49751058", "0.49690938", "0.4967397", "0.49663118", "0.49662492", "0.49655554", "0.49624187", "0.49617302", "0.49589702", "0.49545163", "0.49537325", "0.49537185", "0.4953309", "0.49307272", "0.49283868", "0.49270564", "0.49250013", "0.49243134" ]
0.64986366
1
KillTask is called when the executor receives a request to kill a task.
func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) { if k.isDone() { return } log.Infof("Kill task %v\n", taskId) if !k.isConnected() { //TODO(jdefelice) sent TASK_LOST here? log.Warningf("Ignore kill task because the executor is disconnected\n") return } k.lock.Lock() defer k.lock.Unlock() k.removePodTask(driver, taskId.GetValue(), messages.TaskKilled, mesos.TaskState_TASK_KILLED) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.killPodForTask(driver, taskId.GetValue(), messages.TaskKilled)\n}", "func (f *Failer) KillTask(host, task string) error {\n\tscript := \"sudo pkill -x %s\"\n\tlog.V(1).Infof(\"Killing task %s on host %s\", task, host)\n\treturn f.runWithEvilTag(host, fmt.Sprintf(script, task))\n}", "func KillTask(tid int) Errno {\n\t_, e := internal.Syscall1(KILLTASK, uintptr(tid))\n\treturn Errno(e)\n}", "func (ts *TaskService) Kill(ctx context.Context, req *taskAPI.KillRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"kill\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.Kill(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"kill failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).Debug(\"kill succeeded\")\n\treturn resp, nil\n}", "func (tr *TaskRunner) Kill(ctx context.Context, event *structs.TaskEvent) error {\n\ttr.logger.Trace(\"Kill requested\")\n\n\t// Cancel the task runner to break out of restart delay or the main run\n\t// loop.\n\ttr.killCtxCancel()\n\n\t// Emit kill event\n\tif event != nil {\n\t\ttr.logger.Trace(\"Kill event\", \"event_type\", event.Type, \"event_reason\", event.KillReason)\n\t\ttr.EmitEvent(event)\n\t}\n\n\tselect {\n\tcase <-tr.WaitCh():\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn tr.getKillErr()\n}", "func (ts *TaskService) Kill(requestCtx context.Context, req *taskAPI.KillRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\tlog.G(requestCtx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"kill\")\n\n\tresp, err := ts.runcService.Kill(requestCtx, req)\n\tif err != nil {\n\t\tlog.G(requestCtx).WithError(err).Error(\"kill failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(requestCtx).Debug(\"kill succeeded\")\n\treturn resp, nil\n}", "func (h *Hub) StopTask(ctx context.Context, request *pb.StopTaskRequest) (*pb.StopTaskReply, error) {\n\tlog.G(h.ctx).Info(\"handling StopTask request\", zap.Any(\"req\", request))\n\ttaskID := request.Id\n\tminerID, ok := h.getMinerByTaskID(taskID)\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.NotFound, \"no such task %s\", taskID)\n\t}\n\n\tminer, ok := h.getMinerByID(minerID)\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.NotFound, \"no miner with task %s\", minerID)\n\t}\n\n\t_, err := miner.Client.Stop(ctx, &pb.StopTaskRequest{Id: taskID})\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.NotFound, \"failed to stop the task %s\", taskID)\n\t}\n\n\tminer.deregisterRoute(taskID)\n\tminer.Retain(taskID)\n\n\th.deleteTaskByID(taskID)\n\n\treturn &pb.StopTaskReply{}, nil\n}", "func (t *task) Kill(_ context.Context, signal syscall.Signal) error {\n\thcsContainer, err := t.getHCSContainer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := t.ctr.client.logger.WithFields(log.Fields{\n\t\t\"container\": t.ctr.id,\n\t\t\"process\": t.id,\n\t\t\"pid\": t.Pid(),\n\t\t\"signal\": signal,\n\t})\n\tlogger.Debug(\"Signal()\")\n\n\tvar op string\n\tif signal == syscall.SIGKILL {\n\t\t// Terminate the compute system\n\t\tt.ctr.mu.Lock()\n\t\tt.ctr.terminateInvoked = true\n\t\tt.ctr.mu.Unlock()\n\t\top, err = \"terminate\", hcsContainer.Terminate()\n\t} else {\n\t\t// Shut down the container\n\t\top, err = \"shutdown\", hcsContainer.Shutdown()\n\t}\n\tif err != nil {\n\t\tif !hcsshim.IsPending(err) && !hcsshim.IsAlreadyStopped(err) {\n\t\t\t// ignore errors\n\t\t\tlogger.WithError(err).Errorf(\"failed to %s hccshim container\", op)\n\t\t}\n\t}\n\n\treturn nil\n}", "func HandleStopTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleStopTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStopTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleStopTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\ttaskCapacity, err := node.StopTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStopTask Stop task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleStopTask END\")\n\tHttpResponseData(w, H{\n\t\t\"taskCapacity\": taskCapacity,\n\t})\n\treturn\n}", "func (t *TimeTask) DeleteTask(task *RawTask) {\n\tt.deleteChan <- task\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"DELETE\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tparams := mux.Vars(r)\n\tdeleteOneTask(params[\"id\"])\n\tjson.NewEncoder(w).Encode(params[\"id\"])\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"DELETE\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tparams := mux.Vars(r)\n\tdeleteOneTask(params[\"id\"])\n\tjson.NewEncoder(w).Encode(params[\"id\"])\n\t// json.NewEncoder(w).Encode(\"Task not found\")\n\n}", "func (c Control) ServeStopTask(w http.ResponseWriter, r *http.Request) {\n\tc.ServeTaskAction(w, r, false)\n}", "func (d *Driver) StopTask(taskID string, timeout time.Duration, signal string) error {\n\td.logger.Info(\"Stopping task\", \"taskID\", taskID, \"signal\", signal)\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\t// fixme send proper signal to container\n\terr := d.podman.ContainerStop(d.ctx, handle.containerID, int(timeout.Seconds()))\n\tif err != nil {\n\t\td.logger.Error(\"Could not stop/kill container\", \"containerID\", handle.containerID, \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (task *Task) Kill() {\n\tif task.Config.CmdString != \"\" && task.Command.Started && !task.Command.Complete {\n\t\tsyscall.Kill(-task.Command.Cmd.Process.Pid, syscall.SIGKILL)\n\t}\n\n\tfor _, subTask := range task.Children {\n\t\tif subTask.Config.CmdString != \"\" && subTask.Command.Started && !subTask.Command.Complete {\n\t\t\tsyscall.Kill(-subTask.Command.Cmd.Process.Pid, syscall.SIGKILL)\n\t\t}\n\t}\n\n}", "func HandleDeleteTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleDeleteTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleDeleteTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleDeleteTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\terr = node.DeleteTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleDeleteTask Delete task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleDeleteTask END\")\n\tHttpResponseOk(w)\n\treturn\n}", "func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error {\n\treturn nil\n}", "func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error {\n\treturn nil\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprint(w, \"DeleteTask\\n\")\n}", "func (d *Driver) SignalTask(taskID string, signal string) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\treturn d.podman.ContainerKill(d.ctx, handle.containerID, signal)\n}", "func DeleteTask(c *gin.Context) {\n\tfmt.Println(\"deleteTask\")\n\ttask := c.Param(\"id\")\n\tfmt.Println(\"task_id: \", task)\n\tdeleteOneTask(task)\n\tc.JSON(http.StatusOK, task)\n\t// json.NewEncoder(w).Encode(\"Task not found\")\n\n}", "func runTask(bFunc taskFunc, tFunc taskFunc, name string, interval time.Duration) {\n\tif err := bFunc(name); err != nil {\n\t\tglog.Errorf(\"%s: %s\", name, err)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-killTask:\n\t\t\tglog.V(vvLevel).Infof(\"Exiting %s\", name)\n\t\t\theartbeatWG.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\tif err := tFunc(name); err != nil {\n\t\t\t\tglog.Errorf(\"%s: %s\", name, err)\n\t\t\t}\n\t\t\ttime.Sleep(interval)\n\t\t}\n\t}\n}", "func KillProcess(w http.ResponseWriter, r *http.Request) {\n \n params := mux.Vars(r)\n ip = params[\"id\"]\n\n wg := new(sync.WaitGroup) // wait till process killed.\n out, err := exec.Command(\"pkill\", \"-f\", ip).Output()\n if err != nil {\n fmt.Printf(\"%s\", err)\n return json.NewEncoder(w).Encode(err)\n }\n fmt.Printf(\"%s\", out)\n wg.Done()\n\n return json.NewEncoder(w).Encode(\"success\")\n\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\tif params[\"id\"] == \"\" {\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttaskID := bson.ObjectIdHex(params[\"id\"])\n\n\tdeleted, err := repository.DeleteTask(taskID)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !deleted {\n\t\thttp.Error(w, http.StatusText(500), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (ctrl *TaskController) DeleteTask(w http.ResponseWriter, r *http.Request) {\n\ttaskId := ParamAsString(\"id\", r)\n\tlogrus.Println(\"delete task : \", taskId)\n\n\terr := ctrl.taskDao.Delete(taskId)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\tSendJSONError(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlogrus.Println(\"deleted task : \", taskId)\n\tSendJSONWithHTTPCode(w, nil, http.StatusNoContent)\n}", "func (c *ECS) StopTaskRequest(input *StopTaskInput) (req *aws.Request, output *StopTaskOutput) {\n\toprw.Lock()\n\tdefer oprw.Unlock()\n\n\tif opStopTask == nil {\n\t\topStopTask = &aws.Operation{\n\t\t\tName: \"StopTask\",\n\t\t\tHTTPMethod: \"POST\",\n\t\t\tHTTPPath: \"/\",\n\t\t}\n\t}\n\n\treq = c.newRequest(opStopTask, input, output)\n\toutput = &StopTaskOutput{}\n\treq.Data = output\n\treturn\n}", "func (c *Client) TerminateTask(guid string) error {\n\treq := c.NewRequest(\"PUT\", fmt.Sprintf(\"/v3/tasks/%s/cancel\", guid))\n\tresp, err := c.DoRequest(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error terminating task\")\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 202 {\n\t\treturn errors.Wrapf(err, \"Failed terminating task, response status code %d\", resp.StatusCode)\n\t}\n\treturn nil\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request, repo *tasks.TaskRepository) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\ttaskID, err := strconv.Atoi(params[\"id\"])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttask, err := repo.DeleteTask(taskID)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.NewEncoder(w).Encode(apiIndexTask(task))\n}", "func (s *K8sSvc) DeleteTask(ctx context.Context, cluster string, service string, taskType string) error {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\ttaskID := service + common.NameSeparator + taskType\n\n\terr := s.cliset.BatchV1().Jobs(s.namespace).Delete(taskID, &metav1.DeleteOptions{})\n\tif err != nil {\n\t\tif k8errors.IsNotFound(err) {\n\t\t\tglog.Infoln(\"task not found\", taskID, \"requuid\", requuid)\n\t\t\treturn nil\n\t\t}\n\t\tglog.Errorln(\"delete task error\", err, \"taskID\", taskID, \"requuid\", requuid)\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"deleted task\", taskID, \"requuid\", requuid)\n\treturn nil\n}", "func (ts *TaskService) Delete(ctx context.Context, req *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"delete\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.Delete(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"delete failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).WithFields(logrus.Fields{\n\t\t\"pid\": resp.Pid,\n\t\t\"exit_status\": resp.ExitStatus,\n\t}).Debug(\"delete succeeded\")\n\treturn resp, nil\n}", "func (t TaskService) DeleteTask(ctx context.Context, id platform.ID) error {\n\tspan, _ := tracing.StartSpanFromContext(ctx)\n\tdefer span.Finish()\n\n\treturn t.Client.\n\t\tDelete(taskIDPath(id)).\n\t\tDo(ctx)\n}", "func (ts *TaskService) Delete(requestCtx context.Context, req *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\tlog.G(requestCtx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"delete\")\n\n\tresp, err := ts.taskManager.DeleteProcess(requestCtx, req, ts.runcService)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.G(requestCtx).WithFields(logrus.Fields{\n\t\t\"pid\": resp.Pid,\n\t\t\"exit_status\": resp.ExitStatus,\n\t}).Debug(\"delete succeeded\")\n\treturn resp, nil\n}", "func (e *ECS) StopTask(req *StopTaskReq) (*StopTaskResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"StopTask\")\n\tif req.Cluster != \"\" {\n\t\tparams[\"cluster\"] = req.Cluster\n\t}\n\tif req.Task != \"\" {\n\t\tparams[\"task\"] = req.Task\n\t}\n\n\tresp := new(StopTaskResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (c *Client) DeleteTask(ctx context.Context, in *todopb.TaskQuery, opts ...grpc.CallOption) (*empty.Empty, error) {\n\treturn c.client.DeleteTask(ctx, in, opts...)\n}", "func (p *AuroraSchedulerManagerClient) KillTasks(ctx context.Context, job *JobKey, instances []int32, message string) (r *Response, err error) {\n var _args192 AuroraSchedulerManagerKillTasksArgs\n _args192.Job = job\n _args192.Instances = instances\n _args192.Message = message\n var _result193 AuroraSchedulerManagerKillTasksResult\n var meta thrift.ResponseMeta\n meta, err = p.Client_().Call(ctx, \"killTasks\", &_args192, &_result193)\n p.SetLastResponseMeta_(meta)\n if err != nil {\n return\n }\n return _result193.GetSuccess(), nil\n}", "func (t *TaskController[T, U, C, CT, TF]) Wait() {\n\tt.wg.Wait()\n\tclose(t.resultCh)\n\tt.pool.DeleteTask(t.taskID)\n}", "func (c *BasicECSClient) StopTask(ctx context.Context, in *ecs.StopTaskInput) (*ecs.StopTaskOutput, error) {\n\tif err := c.setup(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"setting up client\")\n\t}\n\n\tvar out *ecs.StopTaskOutput\n\tvar err error\n\tmsg := awsutil.MakeAPILogMessage(\"StopTask\", in)\n\tif err := utility.Retry(ctx,\n\t\tfunc() (bool, error) {\n\t\t\tout, err = c.ecs.StopTaskWithContext(ctx, in)\n\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\tgrip.Debug(message.WrapError(awsErr, msg))\n\t\t\t\tif c.isNonRetryableErrorCode(awsErr.Code()) {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, err\n\t\t}, *c.opts.RetryOpts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (domain *Domain) DeleteTask(uuid string) error {\n\t// determine task\n\tdomain.TasksX.RLock()\n\t_, ok := domain.Tasks[uuid]\n\tdomain.TasksX.RUnlock()\n\n\tif !ok {\n\t\treturn errors.New(\"task not found\")\n\t}\n\n\t// remove task\n\tdomain.TasksX.Lock()\n\tdelete(domain.Tasks, uuid)\n\tdomain.TasksX.Unlock()\n\n\t// success\n\treturn nil\n}", "func (na *cnmNetworkAllocator) DeallocateTask(t *api.Task) error {\n\tdelete(na.tasks, t.ID)\n\treturn na.releaseEndpoints(t.Networks)\n}", "func (k *KubernetesExecutor) killPodForTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_KILLED)\n}", "func (c Control) ServeDeleteTask(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tc.Config.Lock()\n\tdefer c.Config.Unlock()\n\tindex, task := c.findTaskById(id)\n\tif task == nil {\n\t\thttp.Error(w, \"Invalid task ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttask.StopLoop()\n\tfor i := index; i < len(c.Config.Tasks)-1; i++ {\n\t\tc.Config.Tasks[i] = c.Config.Tasks[i+1]\n\t}\n\tc.Config.Tasks = c.Config.Tasks[0 : len(c.Config.Tasks)-1]\n\tc.Config.Save()\n\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}", "func cleanupTask(ctx context.Context, t *testing.T, c cocoa.ECSClient, runOut *ecs.RunTaskOutput) {\n\tif runOut != nil && len(runOut.Tasks) > 0 && runOut.Tasks[0].TaskArn != nil {\n\t\tout, err := c.StopTask(ctx, &ecs.StopTaskInput{\n\t\t\tCluster: aws.String(testutil.ECSClusterName()),\n\t\t\tTask: aws.String(*runOut.Tasks[0].TaskArn),\n\t\t})\n\t\trequire.NoError(t, err)\n\t\trequire.NotZero(t, out)\n\t}\n}", "func (d *Driver) DestroyTask(taskID string, force bool) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\tif handle.isRunning() && !force {\n\t\treturn fmt.Errorf(\"cannot destroy running task\")\n\t}\n\n\tif handle.isRunning() {\n\t\td.logger.Debug(\"Have to destroyTask but container is still running\", \"containerID\", handle.containerID)\n\t\t// we can not do anything, so catching the error is useless\n\t\terr := d.podman.ContainerStop(d.ctx, handle.containerID, 60)\n\t\tif err != nil {\n\t\t\td.logger.Warn(\"failed to stop/kill container during destroy\", \"error\", err)\n\t\t}\n\t\t// wait a while for stats emitter to collect exit code etc.\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tif !handle.isRunning() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 250)\n\t\t}\n\t\tif handle.isRunning() {\n\t\t\td.logger.Warn(\"stats emitter did not exit while stop/kill container during destroy\", \"error\", err)\n\t\t}\n\t}\n\n\tif handle.removeContainerOnExit {\n\t\terr := d.podman.ContainerDelete(d.ctx, handle.containerID, true, true)\n\t\tif err != nil {\n\t\t\td.logger.Warn(\"Could not remove container\", \"container\", handle.containerID, \"error\", err)\n\t\t}\n\t}\n\n\td.tasks.Delete(taskID)\n\treturn nil\n}", "func (t Task) Close() error {\n\tpath := fmt.Sprintf(\"tasks/%d/close\", t.ID)\n\t_, err := makeRequest(http.MethodPost, path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deleteTask(w http.ResponseWriter, r *http.Request){\n\t//definimos variable de vars que devuelve las variables de ruta\n\tvars := mux.Vars(r)\n\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil{\n\t\tfmt.Fprintf(w, \"Invalid ID\")\n\t\treturn\n\t}\n\n\t//Se elimina la task a la lista, guardando todas las que estan hasta su indice, y la que le sigue en adelante.\n\tfor i, task := range tasks {\n\t\tif task.ID == taskID {\n\t\t\ttasks = append(tasks[:i], tasks[i + 1:] ...)\n\t\t\tfmt.Fprintf(w, \"The task with ID %v has been removed succesfully\", taskID)\n\t\t}\n\t}\n}", "func (p *AuroraSchedulerManagerClient) KillTasks(ctx context.Context, job *JobKey, instances []int32, message string) (r *Response, err error) {\n var _args142 AuroraSchedulerManagerKillTasksArgs\n _args142.Job = job\n _args142.Instances = instances\n _args142.Message = message\n var _result143 AuroraSchedulerManagerKillTasksResult\n if err = p.Client_().Call(ctx, \"killTasks\", &_args142, &_result143); err != nil {\n return\n }\n return _result143.GetSuccess(), nil\n}", "func (c *restClient) DeleteTask(ctx context.Context, req *cloudtaskspb.DeleteTaskRequest, opts ...gax.CallOption) error {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2beta3/%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\treturn 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(\"DELETE\", 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\t// Returns nil if there is no error, otherwise wraps\n\t\t// the response code and body into a non-nil error\n\t\treturn googleapi.CheckResponse(httpRsp)\n\t}, opts...)\n}", "func (d *JobManager) killJobExecution(request *restful.Request, response *restful.Response) {\n\tInfo(\"Enter killJobExecution\\n\")\n\tns := request.PathParameter(\"namespace\")\n\tjobId := request.PathParameter(\"job-id\")\n\tif seqno, err := strconv.Atoi(request.PathParameter(\"execution_id\")); err != nil {\n\t\tresponse.AddHeader(\"Content-Type\", \"text/plain\")\n\t\tresponse.WriteErrorString(http.StatusInternalServerError, err.Error())\n\t\treturn\n\t} else {\n\t\tkey := Key{Ns: ns, Id: jobId}\n\t\tInfo(\"killJobExecution key.Ns=%s key.Id=%s\\n\", key.Ns, key.Id)\n\t\t//update the execution as cancelled in the database\n\t\tSetExecutionCancelled(key.Ns, key.Id, seqno)\n\t\tgo func() {\n\t\t\tif _, OK := d.KillExecChan[key]; !OK {\n\t\t\t\tInfo(\"Init d.KillExecChan\\n\")\n\t\t\t\td.KillExecChan[key] = make(chan int, 1)\n\t\t\t}\n\t\t\tInfo(\"write to d.KillExecChan\\n\")\n\t\t\td.KillExecChan[key] <- seqno\n\t\t}()\n\n\t\tresponse.WriteHeader(http.StatusAccepted)\n\t\treturn\n\t}\n}", "func (t *TaskService) Delete(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\temptyUUID gocql.UUID\n\t\ttaskIDStr = mux.Vars(r)[\"taskID\"]\n\t\tpartnerID = mux.Vars(r)[\"partnerID\"]\n\t\tctx = r.Context()\n\t\tcurrentUser = t.userService.GetUser(r, t.httpClient)\n\t)\n\n\ttaskID, err := gocql.ParseUUID(taskIDStr)\n\tif err != nil || taskID == emptyUUID {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorTaskIDHasBadFormat, \"TaskService.Delete: task ID(UUID=%s) has bad format or empty. err=%v\", taskIDStr, err)\n\t\tcommon.SendBadRequest(w, r, errorcode.ErrorTaskIDHasBadFormat)\n\t\treturn\n\t}\n\n\tinternalTasks, err := t.taskPersistence.GetByIDs(ctx, nil, partnerID, false, taskID)\n\tif err != nil {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorCantGetTaskByTaskID, \"TaskService.Delete: can't get internal tasks by task ID %v. err=%v\", taskID, err)\n\t\tcommon.SendInternalServerError(w, r, errorcode.ErrorCantGetTaskByTaskID)\n\t\treturn\n\t}\n\n\tif len(internalTasks) == 0 {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorTaskIsNotFoundByTaskID, \"TaskService.Delete: task with ID %v not found.\", taskID)\n\t\tcommon.SendBadRequest(w, r, errorcode.ErrorTaskIsNotFoundByTaskID)\n\t\treturn\n\t}\n\n\tcommonTaskData := internalTasks[0]\n\tif currentUser.HasNOCAccess() != commonTaskData.IsRequireNOCAccess {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorAccessDenied, \"TaskService.Delete: current user %s is not authorized to delete task with ID %v for partnerID %v\", currentUser.UID(), commonTaskData.ID, commonTaskData.PartnerID)\n\t\tcommon.SendForbidden(w, r, errorcode.ErrorAccessDenied)\n\t\treturn\n\t}\n\n\tdto, err := t.getDataToDelete(ctx, taskID, r, w, partnerID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdto.tasks = internalTasks\n\tif err = t.executeDeleting(dto); err != nil {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorCantDeleteTask, \"TaskService.Delete: can't process deleting of the task. err=%v\", err)\n\t\tcommon.SendInternalServerError(w, r, errorcode.ErrorCantDeleteTask)\n\t\treturn\n\t}\n\n\tif !currentUser.HasNOCAccess() {\n\t\t// update counters for tasks in separate goroutine\n\t\tgo func(ctx context.Context, iTasks []models.Task) {\n\t\t\tcounters := getCountersForInternalTasks(iTasks)\n\t\t\tif len(counters) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr := t.taskCounterRepo.DecreaseCounter(commonTaskData.PartnerID, counters, false)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.ErrfCtx(ctx, errorcode.ErrorCantProcessData, \"Delete: error while trying to increase counter: \", err)\n\t\t\t}\n\t\t}(ctx, internalTasks)\n\t}\n\n\tlogger.Log.InfofCtx(r.Context(), \"TaskService.Delete: successfully deleted task with ID = %v\", taskID)\n\tcommon.SendNoContent(w)\n}", "func taskDeleteHandler(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tdn := getRequestParam(r, \"model\")\r\n\ttn := getRequestParam(r, \"task\")\r\n\r\n\t// delete modeling task\r\n\tok, err := theCatalog.DeleteTask(dn, tn)\r\n\tif err != nil {\r\n\t\thttp.Error(w, \"Task delete failed \"+dn+\": \"+tn, http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\tif ok {\r\n\t\tw.Header().Set(\"Content-Location\", \"/api/model/\"+dn+\"/task/\"+tn)\r\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\r\n\t}\r\n}", "func DeleteJobTask(w http.ResponseWriter, r *http.Request) {\n\tresponse := services.DeleteJobTask(r)\n\n\trender.Status(r, response.Code)\n\trender.JSON(w, r, response)\n}", "func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST)\n}", "func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST)\n}", "func (r *Runhcs) Kill(context context.Context, id, signal string) error {\n\treturn r.runOrError(r.command(context, \"kill\", id, signal))\n}", "func (jm *JobManager) CancelTask(taskName string) (err error) {\n\tjm.Lock()\n\tdefer jm.Unlock()\n\n\tif task, hasTask := jm.tasks[taskName]; hasTask {\n\t\tjm.onTaskCancellation(task.Task, Since(task.StartTime))\n\t\ttask.Cancel()\n\t} else {\n\t\terr = exception.New(ErrTaskNotFound).WithMessagef(\"task: %s\", taskName)\n\t}\n\treturn\n}", "func taskHandlerTunny(task interface{}) interface{} {\n\tworkLoadHandler()\n\twg.Done()\n\treturn nil\n}", "func (p k8sPodResources) Kill(ctx *actor.System, _ logger.Context) {\n\tctx.Tell(p.podsActor, KillTaskPod{\n\t\tPodID: p.containerID,\n\t})\n}", "func (h *Heartbeat) RemoveTask(name string) error {\n\th.lock <- struct{}{}\n\tdefer func() {\n\t\t<-h.lock\n\t}()\n\tif _, ok := h.slavesTs[name]; !ok {\n\t\treturn terror.ErrSyncerUnitHeartbeatRecordNotFound.Generate(name)\n\t}\n\tdelete(h.slavesTs, name)\n\n\tif len(h.slavesTs) == 0 {\n\t\t// cancel work\n\t\th.cancel()\n\t\th.cancel = nil\n\t\th.wg.Wait()\n\n\t\t// close DB\n\t\th.master.Close()\n\t\th.master = nil\n\t}\n\n\treturn nil\n}", "func (w *Worker) handleTask() {\n\tvar handleTaskInterval = time.Second\n\tfailpoint.Inject(\"handleTaskInterval\", func(val failpoint.Value) {\n\t\tif milliseconds, ok := val.(int); ok {\n\t\t\thandleTaskInterval = time.Duration(milliseconds) * time.Millisecond\n\t\t\tw.l.Info(\"set handleTaskInterval\", zap.String(\"failpoint\", \"handleTaskInterval\"), zap.Int(\"value\", milliseconds))\n\t\t}\n\t})\n\tticker := time.NewTicker(handleTaskInterval)\n\tdefer ticker.Stop()\n\n\tretryCnt := 0\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.l.Info(\"handle task process exits!\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tif w.closed.Get() == closedTrue {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\topLog := w.meta.PeekLog()\n\t\t\tif opLog == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.l.Info(\"start to execute operation\", zap.Reflect(\"oplog\", opLog))\n\n\t\t\tst := w.subTaskHolder.findSubTask(opLog.Task.Name)\n\t\t\tvar err error\n\t\t\tswitch opLog.Task.Op {\n\t\t\tcase pb.TaskOp_Start:\n\t\t\t\tif st != nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskExists.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif w.relayPurger.Purging() {\n\t\t\t\t\tif retryCnt < maxRetryCount {\n\t\t\t\t\t\tretryCnt++\n\t\t\t\t\t\tw.l.Warn(\"relay log purger is purging, cannot start subtask, would try again later\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t\t\tcontinue Loop\n\t\t\t\t\t}\n\n\t\t\t\t\tretryCnt = 0\n\t\t\t\t\terr = terror.ErrWorkerRelayIsPurging.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tretryCnt = 0\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar cfgDecrypted *config.SubTaskConfig\n\t\t\t\tcfgDecrypted, err = taskCfg.DecryptPassword()\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = terror.WithClass(err, terror.ClassDMWorker)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"started sub task\", zap.Stringer(\"config\", cfgDecrypted))\n\t\t\t\tst = NewSubTask(cfgDecrypted)\n\t\t\t\tw.subTaskHolder.recordSubTask(st)\n\t\t\t\tst.Run()\n\n\t\t\tcase pb.TaskOp_Update:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"updated sub task\", zap.String(\"task\", opLog.Task.Name), zap.Stringer(\"new config\", taskCfg))\n\t\t\t\terr = st.Update(taskCfg)\n\t\t\tcase pb.TaskOp_Stop:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"stop sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\tst.Close()\n\t\t\t\tw.subTaskHolder.removeSubTask(opLog.Task.Name)\n\t\t\tcase pb.TaskOp_Pause:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"pause sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Pause()\n\t\t\tcase pb.TaskOp_Resume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\tcase pb.TaskOp_AutoResume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"auto_resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\t}\n\n\t\t\tw.l.Info(\"end to execute operation\", zap.Int64(\"oplog ID\", opLog.Id), log.ShortError(err))\n\n\t\t\tif err != nil {\n\t\t\t\topLog.Message = err.Error()\n\t\t\t} else {\n\t\t\t\topLog.Task.Stage = st.Stage()\n\t\t\t\topLog.Success = true\n\t\t\t}\n\n\t\t\t// fill current task config\n\t\t\tif len(opLog.Task.Task) == 0 {\n\t\t\t\ttm := w.meta.GetTask(opLog.Task.Name)\n\t\t\t\tif tm == nil {\n\t\t\t\t\tw.l.Warn(\"task meta not found\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t} else {\n\t\t\t\t\topLog.Task.Task = append([]byte{}, tm.Task...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr = w.meta.MarkOperation(opLog)\n\t\t\tif err != nil {\n\t\t\t\tw.l.Error(\"fail to mark subtask operation\", zap.Reflect(\"oplog\", opLog))\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *hostCommunicator) EndTask(ctx context.Context, detail *apimodels.TaskEndDetail, taskData TaskData) (*apimodels.EndTaskResponse, error) {\n\tgrip.Info(message.Fields{\n\t\t\"message\": \"started EndTask\",\n\t\t\"task_id\": taskData.ID,\n\t})\n\ttaskEndResp := &apimodels.EndTaskResponse{}\n\tinfo := requestInfo{\n\t\tmethod: http.MethodPost,\n\t\ttaskData: &taskData,\n\t\tpath: fmt.Sprintf(\"hosts/%s/task/%s/end\", c.hostID, taskData.ID),\n\t}\n\tresp, err := c.retryRequest(ctx, info, detail)\n\tif err != nil {\n\t\treturn nil, util.RespErrorf(resp, errors.Wrap(err, \"ending task\").Error())\n\t}\n\tdefer resp.Body.Close()\n\tif err = utility.ReadJSON(resp.Body, taskEndResp); err != nil {\n\t\treturn nil, errors.Wrap(err, \"reading end task reply from response\")\n\t}\n\tgrip.Info(message.Fields{\n\t\t\"message\": \"finished EndTask\",\n\t\t\"task_id\": taskData.ID,\n\t})\n\treturn taskEndResp, nil\n}", "func (md *ManagementNode) DelTask(id string) {\n\tmd.scheduledTasksMtx.Lock()\n\tdefer md.scheduledTasksMtx.Unlock()\n\n\tdelete(md.scheduledTasks, id)\n\n}", "func deleteTask(w http.ResponseWriter, r *http.Request) {\r\n\tvars := mux.Vars(r) //copio del anterior porque el metodo de busqueda es el mismo\r\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\r\n\tif err != nil {\r\n\t\tfmt.Fprintf(w, \"Invalid ID\")\r\n\t\treturn\r\n\t}\r\n\tfor i, task := range tasks { //misma busqueda que en el caso anterior\r\n\t\tif task.ID == taskID {\r\n\t\t\ttasks = append(tasks[:i], tasks[i+1:]...) //en realidad no borra sino que arma un slice con los elementos previos y posteriores al indice dado\r\n\t\t\tfmt.Fprintf(w, \"The task with ID: %v has been successfully removed.\", taskID)\r\n\t\t}\r\n\t}\r\n}", "func (t Task) Delete() error {\n\tpath := fmt.Sprintf(\"tasks/%d\", t.ID)\n\t_, err := makeRequest(http.MethodDelete, path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (b Bot) CancelTask(taskID string) error {\n\ttask, err := b.repository.GetTask(taskID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif task.executed {\n\t\treturn fmt.Errorf(\"task %s has already been executed\", taskID)\n\t}\n\n\ttask.cancelled = true\n\tb.repository.UpdateTask(task)\n\treturn nil\n}", "func DeleteTask(id int) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(taskBucket)\n\t\treturn b.Delete(itob(id))\n\t})\n}", "func (self Future) Kill() error {\n\terr := self.checkExists()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn kill(regexp.QuoteMeta(self.socketFile()))\n}", "func handleTimeout(task *task.MessageTask, env *task.Env) {\n\tkey := fmt.Sprintf(\"%x\", task.GetMessage().Token)\n\tdelete(env.Requests(), key)\n\tlog.Info(\"<<< handleTimeout >>>\")\n}", "func (t *task) deleteTask() {\n\t// There is no state to clean up as of now.\n\t// If the goal state was set to DELETED, then let the\n\t// listeners know that the task has been deleted.\n\n\tvar runtimeCopy *pbtask.RuntimeInfo\n\tvar labelsCopy []*peloton.Label\n\n\t// notify listeners after dropping the lock\n\tdefer func() {\n\t\tif runtimeCopy != nil {\n\t\t\tt.jobFactory.notifyTaskRuntimeChanged(\n\t\t\t\tt.jobID,\n\t\t\t\tt.id,\n\t\t\t\tt.jobType,\n\t\t\t\truntimeCopy,\n\t\t\t\tlabelsCopy,\n\t\t\t)\n\t\t}\n\t}()\n\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\tif t.runtime == nil {\n\t\treturn\n\t}\n\n\tif t.runtime.GetGoalState() != pbtask.TaskState_DELETED {\n\t\treturn\n\t}\n\n\truntimeCopy = proto.Clone(t.runtime).(*pbtask.RuntimeInfo)\n\truntimeCopy.State = pbtask.TaskState_DELETED\n\tlabelsCopy = t.copyLabelsInCache()\n}", "func (i *DeleteOrUpdateInvTask) Cancel(_ *taskrunner.TaskContext) {}", "func (w *WaitTask) Cancel(_ *TaskContext) {\n\tw.cancelFunc()\n}", "func (tr *TaskRunner) restartImpl(ctx context.Context, event *structs.TaskEvent, failure bool) error {\n\n\t// Check if the task is able to restart based on its state and the type of\n\t// restart event that was triggered.\n\ttaskState := tr.TaskState()\n\tif taskState == nil {\n\t\treturn ErrTaskNotRunning\n\t}\n\n\t// Emit the event since it may take a long time to kill\n\ttr.EmitEvent(event)\n\n\t// Tell the restart tracker that a restart triggered the exit\n\ttr.restartTracker.SetRestartTriggered(failure)\n\n\t// Signal a restart to unblock tasks that are in the \"dead\" state, but\n\t// don't block since the channel is buffered. Only one signal is enough to\n\t// notify the tr.Run() loop.\n\t// The channel must be signaled after SetRestartTriggered is called so the\n\t// tr.Run() loop runs again.\n\tif taskState.State == structs.TaskStateDead {\n\t\tselect {\n\t\tcase tr.restartCh <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\n\t// Grab the handle to see if the task is still running and needs to be\n\t// killed.\n\thandle := tr.getDriverHandle()\n\tif handle == nil {\n\t\treturn nil\n\t}\n\n\t// Run the pre-kill hooks prior to restarting the task\n\ttr.preKill()\n\n\t// Grab a handle to the wait channel that will timeout with context cancelation\n\t// _before_ killing the task.\n\twaitCh, err := handle.WaitCh(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Kill the task using an exponential backoff in-case of failures.\n\tif _, err := tr.killTask(handle, waitCh); err != nil {\n\t\t// We couldn't successfully destroy the resource created.\n\t\ttr.logger.Error(\"failed to kill task. Resources may have been leaked\", \"error\", err)\n\t}\n\n\tselect {\n\tcase <-waitCh:\n\tcase <-ctx.Done():\n\t}\n\treturn nil\n}", "func delete5xxTask(app string, c *gin.Context) error {\n\tdb, err := utils.GetDBFromContext(c)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to access database\")\n\t}\n\n\tclient := http.Client{}\n\treq, err := http.NewRequest(\"DELETE\", os.Getenv(\"KAPACITOR_URL\")+\"/kapacitor/v1/tasks/\"+app+\"-5xx\", nil)\n\tif err != nil {\n\t\treturn errors.New(\"Server Error while reading response\")\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"Server Error while reading response\")\n\t}\n\n\tdefer resp.Body.Close()\n\tbodybytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn errors.New(\"Server Error while reading response\")\n\t}\n\n\tif resp.StatusCode != 204 {\n\t\tvar er structs.ErrorResponse\n\t\terr = json.Unmarshal(bodybytes, &er)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Server Error while reading response\")\n\t\t}\n\t\treturn errors.New(er.Error)\n\t}\n\n\t_, err = db.Exec(\"DELETE FROM _5xx_tasks WHERE app=$1\", app)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to access database\")\n\t}\n\n\treturn nil\n}", "func handleTimeoutNotification(task *task.MessageTask, env *task.Env) {\n\tkey := fmt.Sprintf(\"%x\", task.GetMessage().Token)\n\tdelete(env.Requests(), key)\n\tlog.Info(\"<<< handleTimeout Notification>>>\")\n}", "func DeleteTaskFunc(w http.ResponseWriter, r *http.Request) {\n\tusername := sessions.GetCurrentUserName(r)\n\tif r.Method != \"GET\" {\n\t\thttp.Redirect(w, r, \"/\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tid := r.URL.Path[len(\"/delete/\"):]\n\tif id == \"all\" {\n\t\terr := db.DeleteAll(username)\n\t\tif err != nil {\n\t\t\tmessage = \"Error deleting tasks\"\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusInternalServerError)\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusFound)\n\t} else {\n\t\tid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusBadRequest)\n\t\t} else {\n\t\t\terr = db.DeleteTask(username, id)\n\t\t\tif err != nil {\n\t\t\t\tmessage = \"Error deleting task\"\n\t\t\t} else {\n\t\t\t\tmessage = \"Task deleted\"\n\t\t\t}\n\t\t\thttp.Redirect(w, r, \"/deleted\", http.StatusFound)\n\t\t}\n\t}\n\n}", "func (mgr *ClientMgr) onTaskEnd(ctx context.Context, client *Client, task *Task,\n\terr error, reply *jarviscrawlercore.ReplyCrawler, endChan chan int) {\n\n\tif err != nil {\n\t\tif task.Logger != nil {\n\t\t\ttask.Logger.Warn(\"onTaskEnd: error\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"servaddr\", client.servAddr),\n\t\t\t\tJSON(\"task\", task))\n\t\t}\n\n\t\t// if !(strings.Index(err.Error(), \"Error: noretry:\") == 0 ||\n\t\t// \tstrings.Index(err.Error(), \"noretry:\") == 0) {\n\t\tif !IsNoRetryError(err) {\n\n\t\t\tif task.RetryNums > 0 {\n\t\t\t\ttask.RetryNums--\n\n\t\t\t\t// time.Sleep(time.Second * time.Duration(mgr.cfg.SleepTime))\n\n\t\t\t\ttask.Running = false\n\t\t\t\tclient.Running = false\n\t\t\t\tendChan <- 0\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// task.Fail = true\n\t\t\t// task.running = false\n\t\t}\n\n\t\ttask.Fail = true\n\t}\n\n\tgo task.Callback(ctx, task, err, reply)\n\n\t// time.Sleep(time.Second * time.Duration(mgr.cfg.SleepTime))\n\n\ttask.Running = false\n\tclient.Running = false\n\tendChan <- task.TaskID\n}", "func startTaskWorker(id uint8, signalChannel chan bool, responseChannel chan bool) {\n\t// Startup\n\tsubSocket, err := zmq4.NewSocket(zmq4.Type(zmq4.REP))\n\tif err != nil {\n\t\tlog.Printf(\"Could Not Start Task Worker! ID: %d\\n\", id)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\terr = subSocket.Connect(zeromq.ZeromqHost + ProxyBEPort)\n\tif err != nil {\n\t\tlog.Printf(\"Could Not Start Task Worker! ID: %d\\n\", id)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\terr = subSocket.SetRcvtimeo(time.Duration(time.Second))\n\tif err != nil {\n\t\tlog.Printf(\"Could Not Start Task Worker! ID: %d\\n\", id)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t// Consume Tasks\n\tfor {\n\t\tmsg, err := subSocket.Recv(zmq4.Flag(zmq4.DONTWAIT))\n\t\tif err != nil && zmq4.AsErrno(err) == zmq4.Errno(syscall.EAGAIN) {\n\t\t\tlog.Printf(\"Nothing to Consume! ID: %d\\n\", id)\n\t\t\ttime.Sleep(EmptyQueueSleepDuration)\n\t\t} else if err != nil {\n\t\t\tlog.Printf(\"Error Upon Consuming! ID: %d\\n\", id)\n\t\t\tlog.Println(err)\n\n\t\t\tlog.Printf(\"Cleaning Up Thread ID: %d\\n\", id)\n\t\t\treturn\n\t\t} else {\n\t\t\tsubSocket.Send(\"OK\", zmq4.DONTWAIT)\n\t\t\tonTask(msg)\n\t\t\tsubSocket.Send(\"DONE\", zmq4.DONTWAIT)\n\t\t}\n\n\t\tselect {\n\t\tcase <-signalChannel:\n\t\t\tresponseChannel <- true\n\t\t\tlog.Printf(\"Cleaning Up Thread ID: %d\\n\", id)\n\t\t\tsubSocket.Close()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t}\n\n}", "func ProcessKill(p *os.Process,) error", "func JobKillHandler(c *Context, w http.ResponseWriter, r *http.Request) {\n\t//\n}", "func (r *Runsc) Kill(context context.Context, id string, sig int, opts *KillOpts) error {\n\targs := []string{\n\t\t\"kill\",\n\t}\n\tif opts != nil {\n\t\targs = append(args, opts.args()...)\n\t}\n\treturn r.runOrError(r.command(context, append(args, id, strconv.Itoa(sig))...))\n}", "func execTask(ctx context.Context) error {\n\t// Do pseudo-task. Here, it is just a \"sleep\".\n\tn := 500 + rand.Intn(3500)\n\ttimer := time.NewTimer(time.Duration(n) * time.Millisecond)\n\tselect {\n\tcase <-ctx.Done():\n\t\t// Cancel the pseudo-task here.\n\t\ttimer.Stop()\n\t\treturn ctx.Err()\n\tcase <-timer.C:\n\t\t// Do nothing here. Proceed to the following code\n\t}\n\n\t// Return result of the task. Here, failure means the random number is a\n\t// multiples of 9.\n\tif (n % 9) == 0 {\n\t\treturn errors.New(\"bad luck\")\n\t}\n\treturn nil\n}", "func (c *Client) CancelTask(ctx context.Context, taskID string) error {\n\tctx, cf := context.WithTimeout(ctx, 60*time.Second)\n\tdefer cf()\n\tvar tc *swarming_api.SwarmingRpcsCancelResponse\n\tgetResult := func() error {\n\t\tvar err error\n\t\treq := &swarming_api.SwarmingRpcsTaskCancelRequest{\n\t\t\tKillRunning: true,\n\t\t}\n\t\ttc, err = c.SwarmingService.Task.Cancel(taskID, req).Context(ctx).Do()\n\t\treturn err\n\t}\n\tif err := callWithRetries(ctx, getResult); err != nil {\n\t\treturn errors.Annotate(err, fmt.Sprintf(\"cancel task %s\", taskID)).Err()\n\t}\n\tif !tc.Ok {\n\t\treturn errors.New(fmt.Sprintf(\"task %s is not successfully canceled\", taskID))\n\t}\n\treturn nil\n}", "func (t *Task) Reject() (interface{}, error) {\n\tpar := map[string]interface{}{\n\t\t\"taskid\": t.taskId,\n\t}\n\treturn t.nc.Exec(\"task.reject\", par)\n}", "func taskHandler(task *net.TCPConn) {\n\tworkLoadHandler()\n\twg.Done()\n}", "func (ts *TaskService) Shutdown(ctx context.Context, req *taskAPI.ShutdownRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"now\": req.Now}).Debug(\"shutdown\")\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\n\t// We don't want to call runc.Shutdown here as it just os.Exits behind.\n\t// calling all cancels here for graceful shutdown instead and call runc Shutdown at end.\n\tts.taskManager.RemoveAll(ctx)\n\tts.cancel()\n\n\tlog.G(ctx).Debug(\"going to gracefully shutdown agent\")\n\treturn &types.Empty{}, nil\n}", "func (a *Client) DeleteTask(params *DeleteTaskParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteTaskNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteTaskParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"deleteTask\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/tasks/{id}\",\n\t\tProducesMediaTypes: []string{\"application/vnd.goswagger.examples.task-tracker.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/vnd.goswagger.examples.task-tracker.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteTaskReader{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.(*DeleteTaskNoContent)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*DeleteTaskDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (w *taskWorker) handleTask(ctx context.Context, task queue.Task) (err error) {\n\tspan, ctx := w.StartSpan(ctx, \"handleTask\")\n\tctx, cancel := context.WithCancel(ctx)\n\tlabels := prometheus.Labels{\"queue\": task.Queue, \"type\": task.Type.String()}\n\tdefer func() {\n\t\tcancel()\n\t\tw.FinishSpan(span, err)\n\t}()\n\n\ttimer := prometheus.NewTimer(queue.TaskWorkerMetrics.ProcessingDuration)\n\tdefer timer.ObserveDuration()\n\n\tlogger := logrus.WithContext(ctx).\n\t\tWithField(\"worker\", \"handleTask\").\n\t\tWithField(\"queue\", task.Queue)\n\n\theartbeats := make(chan queue.Progress)\n\tprocessDone := make(chan error, 1)\n\n\tgo func() {\n\t\t// handle panics because we force close the heartbeats if the beats are too slow\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlogger.Errorf(\"Recovered in task handler.Process: %v\", r)\n\t\t\t}\n\t\t}()\n\t\t// force cleanup heartbeats, this might cause a panic ....\n\t\tdefer func() {\n\t\t\t//nolint: errcheck // we don't care about any errors here because we are force closing the channel\n\t\t\tdefer recover()\n\t\t\tdefer close(heartbeats)\n\t\t\tdefer close(processDone)\n\t\t}()\n\n\t\t// handler.Process is responsible for closing the heartbeats channel\n\t\t// if `Process` returns an error it means the task failed\n\t\tprocessDone <- w.handler.Process(ctx, task, heartbeats)\n\t}()\n\n\t// block while we process the heartbeats\n\tprogress, err := w.processHeartbeats(ctx, task, heartbeats)\n\tif err == ErrHeartbeatTimeout {\n\t\t// we must try to put the error message in the latest version of progress\n\t\t// empty progress (no heartbeats) is also fine\n\t\tspan.SetTag(\"err\", err)\n\t\tqueue.TaskWorkerMetrics.ProcessingErrorsCounter.With(labels).Inc()\n\n\t\tprogress = w.setError(progress, err)\n\t\treturn w.dequeuer.Fail(ctx, task.ID, progress)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// now wait for the worker processing error\n\tworkErr := <-processDone\n\tif workErr != nil {\n\t\t// we must try to put the error message in the latest version of progress\n\t\t// empty progress (no heartbeats) is also fine\n\t\tspan.SetTag(\"workErr\", workErr)\n\t\tqueue.TaskWorkerMetrics.ProcessingErrorsCounter.With(labels).Inc()\n\n\t\tprogress = w.setError(progress, workErr)\n\t\treturn w.dequeuer.Fail(ctx, task.ID, progress)\n\t}\n\n\terr = w.dequeuer.Finish(ctx, task.ID, progress)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueue.TaskWorkerMetrics.ProcessedCounter.With(labels).Inc()\n\treturn nil\n}", "func (r DeregisterTaskFromMaintenanceWindowRequest) Send() (*DeregisterTaskFromMaintenanceWindowOutput, error) {\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*DeregisterTaskFromMaintenanceWindowOutput), nil\n}", "func (t ThriftHandler) RemoveTask(ctx context.Context, request *shared.RemoveTaskRequest) (err error) {\n\terr = t.h.RemoveTask(ctx, request)\n\treturn thrift.FromError(err)\n}", "func RejectTask(applicationName string, update bool) error {\n\tgetTaskResp, err := GetTaskByApplicationName(applicationName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(getTaskResp) == 0 {\n\t\treturn fmt.Errorf(\"no tasks for application %s\", applicationName)\n\t}\n\n\terr = HTTPClient(http.MethodPost, fmt.Sprintf(RejectTaskURI, getTaskResp[0].ID, update), nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Server) KillOne(c echo.Context) error {\n\tspan := opentracing.StartSpan(\"API.KillOne\")\n\tdefer span.Finish()\n\n\ttask := new(KillTaskID)\n\n\tif err := c.Bind(task); err != nil {\n\t\treturn err\n\t}\n\n\terr := s.Killer.KillOne(task.ID, \"terminated from UI\", s.Storage)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn err\n\t}\n\n\tc.JSON(http.StatusOK, task.ID)\n\treturn nil\n}", "func (_Node *NodeTransactor) Kill(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Node.contract.Transact(opts, \"kill\")\n}", "func HandleStartTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleStartTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStartTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleStartTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\ttaskCapacity, err := node.StartTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStartTask Start task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tif taskCapacity < 0 {\n\t\tlog.Root.Error(\"HandleStartTask Lack of computing resources\")\n\t\tHttpResponseError(w, ErrLackResources)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleStartTask END\")\n\tHttpResponseData(w, H{\n\t\t\"taskCapacity\": taskCapacity,\n\t})\n\treturn\n}", "func (t *TaskController[T, U, C, CT, TF]) Stop() {\n\tclose(t.productExitCh)\n\t// Clear all the task in the task queue and mark all task complete.\n\t// so that ```t.Wait``` is able to close resultCh\n\tfor range t.inputCh {\n\t\tt.wg.Done()\n\t}\n\tt.pool.StopTask(t.TaskID())\n\t// Clear the resultCh to avoid blocking the consumer put result into the channel and cannot exit.\n\tchannel.Clear(t.resultCh)\n}", "func (_NodeSpace *NodeSpaceTransactor) Kill(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _NodeSpace.contract.Transact(opts, \"kill\")\n}", "func DeleteCloudNodeGroupTask(taskID string, stepName string) error {\n\tstart := time.Now()\n\t//get task information and validate\n\tstate, step, err := cloudprovider.GetTaskStateAndCurrentStep(taskID, stepName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif step == nil {\n\t\treturn nil\n\t}\n\n\t// step login started here\n\tcloudID := step.Params[\"CloudID\"]\n\tnodeGroupID := step.Params[\"NodeGroupID\"]\n\tkeepInstance := false\n\tif step.Params[\"KeepInstance\"] == \"true\" {\n\t\tkeepInstance = true\n\t}\n\tgroup, err := cloudprovider.GetStorageModel().GetNodeGroup(context.Background(), nodeGroupID)\n\tif err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s]: get nodegroup for %s failed\", taskID, nodeGroupID)\n\t\tretErr := fmt.Errorf(\"get nodegroup information failed, %s\", err.Error())\n\t\t_ = state.UpdateStepFailure(start, stepName, retErr)\n\t\treturn retErr\n\t}\n\n\t// get cloud and cluster info\n\tcloud, cluster, err := actions.GetCloudAndCluster(cloudprovider.GetStorageModel(), cloudID, group.ClusterID)\n\tif err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s]: get cloud/cluster for nodegroup %s in task %s step %s failed, %s\",\n\t\t\ttaskID, nodeGroupID, taskID, stepName, err.Error())\n\t\tretErr := fmt.Errorf(\"get cloud/cluster information failed, %s\", err.Error())\n\t\t_ = state.UpdateStepFailure(start, stepName, retErr)\n\t\treturn retErr\n\t}\n\n\t// get dependency resource for cloudprovider operation\n\tcmOption, err := cloudprovider.GetCredential(&cloudprovider.CredentialData{\n\t\tCloud: cloud,\n\t\tAccountID: cluster.CloudAccountID,\n\t})\n\tif err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s]: get credential for nodegroup %s in task %s step %s failed, %s\",\n\t\t\ttaskID, nodeGroupID, taskID, stepName, err.Error())\n\t\tretErr := fmt.Errorf(\"get cloud credential err, %s\", err.Error())\n\t\t_ = state.UpdateStepFailure(start, stepName, retErr)\n\t\treturn retErr\n\t}\n\tcmOption.Region = group.Region\n\n\t// create node group\n\ttkeCli, err := api.NewTkeClient(cmOption)\n\tif err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s]: get tke client for nodegroup[%s] in task %s step %s failed, %s\",\n\t\t\ttaskID, nodeGroupID, taskID, stepName, err.Error())\n\t\tretErr := fmt.Errorf(\"get cloud tke client err, %s\", err.Error())\n\t\t_ = state.UpdateStepFailure(start, stepName, retErr)\n\t\treturn err\n\t}\n\terr = tkeCli.DeleteClusterNodePool(cluster.SystemID, []string{group.CloudNodeGroupID}, keepInstance)\n\tif err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s]: call DeleteClusterNodePool[%s] api in task %s step %s failed, %s\",\n\t\t\ttaskID, nodeGroupID, taskID, stepName, err.Error())\n\t\tretErr := fmt.Errorf(\"call DeleteClusterNodePool[%s] api err, %s\", nodeGroupID, err.Error())\n\t\t_ = state.UpdateStepFailure(start, stepName, retErr)\n\t\treturn retErr\n\t}\n\tblog.Infof(\"DeleteCloudNodeGroupTask[%s]: call DeleteClusterNodePool successful\", taskID)\n\n\t// update response information to task common params\n\tif state.Task.CommonParams == nil {\n\t\tstate.Task.CommonParams = make(map[string]string)\n\t}\n\n\t// update step\n\tif err := state.UpdateStepSucc(start, stepName); err != nil {\n\t\tblog.Errorf(\"DeleteCloudNodeGroupTask[%s] task %s %s update to storage fatal\", taskID, taskID, stepName)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Task) Discard() {\n\t// Start a goroutine to listen to the task result channel and discard the result,\n\t// then exit.\n\tt.discardOnce.Do(func() {\n\t\tgo func() {\n\t\t\t<-t.resultChan\n\t\t\tt.completed(nil)\n\t\t}()\n\t})\n}", "func Delete(taskName string, repository repository.Repository) string {\n\tif taskName == \"\" {\n\t\treturn \"Empty task nothing is deleted from the repository\"\n\t}\n\n\tdeletetaskInstance := &models.TaskDeleteDomain{\n\t\tTaskName: taskName,\n\t}\n\tresp, err := repository.DeleteTask(*deletetaskInstance)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn resp\n}", "func (c *ECS) StopTask(input *StopTaskInput) (output *StopTaskOutput, err error) {\n\treq, out := c.StopTaskRequest(input)\n\toutput = out\n\terr = req.Send()\n\treturn\n}", "func (s *Storage) DeleteTask(id uint) error {\n\tif _, err := s.db.Exec(\"DELETE FROM tasks WHERE id=$1\", id); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deleteTask(msg BackendPayload) {\n\tincomingTaskID := msg.ID // attempt to retreive the id of the task in the case its an update POST\n\t// _, exists := TodoList[incomingTaskID]\n\t// if exists { // only attempt to delete if it exists\n\t// \tdelete(TodoList, incomingTaskID)\n\t// }\n\tTodoList.Delete(incomingTaskID)\n\treturn\n}" ]
[ "0.7103705", "0.66131", "0.635042", "0.6349494", "0.6305433", "0.62947786", "0.6287619", "0.6046641", "0.5978734", "0.5950175", "0.5887274", "0.58670336", "0.58401954", "0.5828122", "0.5799748", "0.57968193", "0.5729903", "0.5729903", "0.57245743", "0.55422145", "0.54591155", "0.5453775", "0.54179937", "0.53865623", "0.53702736", "0.53158164", "0.5311991", "0.52896917", "0.52646035", "0.52393353", "0.5222834", "0.52212566", "0.5216627", "0.5199587", "0.51936823", "0.51868606", "0.5157227", "0.51567554", "0.51477194", "0.5119705", "0.51188433", "0.5118746", "0.5106934", "0.5104544", "0.505413", "0.50515324", "0.5047054", "0.5041527", "0.50393003", "0.5036059", "0.50317115", "0.500281", "0.500281", "0.49885252", "0.49862206", "0.4969859", "0.49638972", "0.49398428", "0.49340937", "0.49239242", "0.49169636", "0.4899587", "0.48658505", "0.48653468", "0.48586032", "0.48549563", "0.48540428", "0.48537213", "0.4833736", "0.48159036", "0.48111323", "0.48103666", "0.48092803", "0.47793576", "0.47768566", "0.47679728", "0.4755572", "0.4754182", "0.47482526", "0.47438008", "0.47351322", "0.47238246", "0.4716296", "0.4709537", "0.4709341", "0.47084644", "0.47007707", "0.470008", "0.46959612", "0.46947372", "0.46941867", "0.46941206", "0.46887866", "0.46725845", "0.46665934", "0.4665158", "0.4658627", "0.46580428", "0.4657721", "0.46518594" ]
0.70807004
1
Reports a lost task to the slave and updates internal task and pod tracking state. Assumes that the caller is locking around pod and task state.
func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) { k.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the kubelet\n\t// may constantly attempt to instantiate a pod as long as it's in the pod state that we're handing to it.\n\t// otherwise, we're probably reporting a TASK_LOST prematurely. Should probably consult RestartPolicy to\n\t// determine appropriate behavior. Should probably also gracefully handle docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}", "func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the\n\t// kubelet may constantly attempt to instantiate a pod as long as it's in the pod state that we're\n\t// handing to it. otherwise, we're probably reporting a TASK_LOST prematurely. Should probably\n\t// consult RestartPolicy to determine appropriate behavior. Should probably also gracefully handle\n\t// docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}", "func (suite *TaskFailRetryTestSuite) TestLostTaskNoRetry() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 0,\n\t\t},\n\t}\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.lostTaskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}", "func (suite *TaskFailRetryTestSuite) TestLostTaskRetry() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 3,\n\t\t},\n\t}\n\n\tsuite.cachedTask.EXPECT().\n\t\tID().\n\t\tReturn(uint32(0)).\n\t\tAnyTimes()\n\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedJob.EXPECT().\n\t\tID().Return(suite.jobID)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.lostTaskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tPatchTasks(gomock.Any(), gomock.Any(), false).\n\t\tDo(func(ctx context.Context,\n\t\t\truntimeDiffs map[uint32]jobmgrcommon.RuntimeDiff,\n\t\t\t_ bool) {\n\t\t\truntimeDiff := runtimeDiffs[suite.instanceID]\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.MesosTaskIDField].(*mesosv1.TaskID).GetValue() != suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.PrevMesosTaskIDField].(*mesosv1.TaskID).GetValue() == suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.StateField].(pbtask.TaskState) == pbtask.TaskState_INITIALIZED)\n\t\t}).Return(nil, nil, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetJobType().Return(pbjob.JobType_BATCH)\n\n\tsuite.taskGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\tsuite.jobGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}", "func (k *KubernetesScheduler) SlaveLost(driver mesos.SchedulerDriver, slaveId *mesos.SlaveID) {\n\tlog.Infof(\"Slave %v is lost\\n\", slaveId)\n\t// TODO(yifan): Restart any unfinished tasks on that slave.\n}", "func (t *Task) fail() {\n\tif t.Retry >= t.tasker.Retry() && t.tasker.Retry() != -1 {\n\t\tt.Failed = time.Now()\n\t\tt.Closed = true\n\t} else {\n\t\tt.Retry++\n\t}\n\n\tt.Owner = data.EmptyKey //throw it back in the queue for processing by any available task runner\n\n\terr := data.TaskUpdate(t, t.Key)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"taskKey\": t.Key,\n\t\t\t\"type\": t.Type,\n\t\t}).Errorf(\"An error occured when updating a task for failure: %s\", err)\n\t}\n}", "func (ctx *coordinatorContext) Lost(taskID string) {\n\tErrorf(\"Lost task %s\", taskID)\n\tctx.stopTask(taskID)\n}", "func (m *TaskManager) ResetOverdueTask() {\n\tm.WIPTable.Range(func(key, value interface{}) bool {\n\t\tif t := value.(*Task); t.IsTimeout() {\n\t\t\tif t.LifeCycle != WIP {\n\t\t\t\tlog.Logger.Fatalf(\"the LifeCycle of the task under check is %d, but `WIP` is expected\", t.LifeCycle)\n\t\t\t}\n\t\t\tt.LifeCycle = READY\n\t\t\tm.ReadyQueue <- t\n\t\t\tm.WIPTable.Delete(key)\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\t\"ID\": t.ID,\n\t\t\t\t\"TaskType\": t.TaskType,\n\t\t\t}).Warn(\"reset an overdue task\")\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}", "func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode task state from handle: %v\", err)\n\t}\n\td.logger.Debug(\"Checking for recoverable task\", \"task\", handle.Config.Name, \"taskid\", handle.Config.ID, \"container\", taskState.ContainerID)\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, taskState.ContainerID)\n\tif err != nil {\n\t\td.logger.Warn(\"Recovery lookup failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: taskState.ContainerID,\n\t\tdriver: d,\n\t\ttaskConfig: taskState.TaskConfig,\n\t\tprocState: drivers.TaskStateUnknown,\n\t\tstartedAt: taskState.StartedAt,\n\t\texitResult: &drivers.ExitResult{},\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tif inspectData.State.Running {\n\t\td.logger.Info(\"Recovered a still running container\", \"container\", inspectData.State.Pid)\n\t\th.procState = drivers.TaskStateRunning\n\t} else if inspectData.State.Status == \"exited\" {\n\t\t// are we allowed to restart a stopped container?\n\t\tif d.config.RecoverStopped {\n\t\t\td.logger.Debug(\"Found a stopped container, try to start it\", \"container\", inspectData.State.Pid)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery restart failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\t\t} else {\n\t\t\t\td.logger.Info(\"Restarted a container during recovery\", \"container\", inspectData.ID)\n\t\t\t\th.procState = drivers.TaskStateRunning\n\t\t\t}\n\t\t} else {\n\t\t\t// no, let's cleanup here to prepare for a StartTask()\n\t\t\td.logger.Debug(\"Found a stopped container, removing it\", \"container\", inspectData.ID)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery cleanup failed\", \"task\", handle.Config.ID, \"container\", inspectData.ID)\n\t\t\t}\n\t\t\th.procState = drivers.TaskStateExited\n\t\t}\n\t} else {\n\t\td.logger.Warn(\"Recovery restart failed, unknown container state\", \"state\", inspectData.State.Status, \"container\", taskState.ContainerID)\n\t\th.procState = drivers.TaskStateUnknown\n\t}\n\n\td.tasks.Set(taskState.TaskConfig.ID, h)\n\n\tgo h.runContainerMonitor()\n\td.logger.Debug(\"Recovered container handle\", \"container\", taskState.ContainerID)\n\n\treturn nil\n}", "func (mgr *DataCheckMgr) checkTaskgroupWhetherLost(taskGroups []*types.TaskGroup, reschedule bool) int {\n\tnow := time.Now().Unix()\n\tlostnum := 0\n\tfor _, taskGroup := range taskGroups {\n\t\tif taskGroup.LastUpdateTime == 0 ||\n\t\t\t(taskGroup.Status != types.TASKGROUP_STATUS_RUNNING &&\n\t\t\t\ttaskGroup.Status != types.TASKGROUP_STATUS_STAGING &&\n\t\t\t\ttaskGroup.Status != types.TASKGROUP_STATUS_STARTING) {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar updateInterval int64\n\n\t\tswitch taskGroup.Status {\n\t\tcase types.TASKGROUP_STATUS_RUNNING, types.TASKGROUP_STATUS_STARTING:\n\t\t\tupdateInterval = 4 * MAX_DATA_UPDATE_INTERVAL\n\t\t\t/*case types.TASKGROUP_STATUS_STAGING:\n\t\t\tupdateInterval = 4 * MAX_STAGING_UPDATE_INTERVAL*/\n\t\t}\n\n\t\tif taskGroup.LastUpdateTime+updateInterval < now {\n\t\t\tfor _, task := range taskGroup.Taskgroup {\n\t\t\t\tif task.Status != types.TASK_STATUS_RUNNING && task.Status != types.TASK_STATUS_STAGING && task.Status != types.TASK_STATUS_STARTING {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif task.LastUpdateTime+updateInterval < now {\n\t\t\t\t\tblog.Warn(\"data checker: task(%s) lost for long time not report status under status(%s)\",\n\t\t\t\t\t\ttask.ID, task.Status)\n\t\t\t\t\ttask.LastStatus = task.Status\n\t\t\t\t\ttask.Status = types.TASK_STATUS_LOST\n\t\t\t\t\ttask.LastUpdateTime = now\n\t\t\t\t\tmgr.sched.SendHealthMsg(alarm.WarnKind, taskGroup.RunAs, task.ID+\"(\"+taskGroup.HostName+\")\"+\"long time not report status, set status to lost\", \"\", nil)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlostnum++\n\t\t\tblog.Warn(\"data checker: taskgroup(%s) lost for long time not report status under status(%s)\",\n\t\t\t\ttaskGroup.ID, taskGroup.Status)\n\t\t\ttaskGroupStatus := taskGroup.Status\n\t\t\ttaskGroup.LastStatus = taskGroup.Status\n\t\t\ttaskGroup.Status = types.TASKGROUP_STATUS_LOST\n\t\t\ttaskGroup.LastUpdateTime = now\n\t\t\t//if reschedule==true, then trigger reschedule function\n\t\t\tif reschedule {\n\t\t\t\tmgr.sched.taskGroupStatusUpdated(taskGroup, taskGroupStatus)\n\t\t\t\tmgr.sched.ServiceMgr.TaskgroupUpdate(taskGroup)\n\t\t\t}\n\t\t\tif err := mgr.sched.store.SaveTaskGroup(taskGroup); err != nil {\n\t\t\t\tblog.Errorf(\"data checker: save taskgroup(%s) into db failed! err:%s\", taskGroup.ID, err.Error())\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lostnum\n}", "func (m *MeasurementData) lossMeasurementTasks(){\n\tm.hdrData.loss = true\n}", "func (c *TowerClient) taskRejected(task *backupTask, curStatus reserveStatus) {\n\tswitch curStatus {\n\n\t// The sessionQueue has available capacity but the task was rejected,\n\t// this indicates that the task was ineligible for backup.\n\tcase reserveAvailable:\n\t\tc.stats.taskIneligible()\n\n\t\tlog.Infof(\"Backup chanid=%s commit-height=%d is ineligible\",\n\t\t\ttask.id.ChanID, task.id.CommitHeight)\n\n\t\terr := c.cfg.DB.MarkBackupIneligible(\n\t\t\ttask.id.ChanID, task.id.CommitHeight,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to mark task chanid=%s \"+\n\t\t\t\t\"commit-height=%d ineligible: %v\",\n\t\t\t\ttask.id.ChanID, task.id.CommitHeight, err)\n\n\t\t\t// It is safe to not handle this error, even if we could\n\t\t\t// not persist the result. At worst, this task may be\n\t\t\t// reprocessed on a subsequent start up, and will either\n\t\t\t// succeed do a change in session parameters or fail in\n\t\t\t// the same manner.\n\t\t}\n\n\t\t// If this task was rejected *and* the session had available\n\t\t// capacity, we discard anything held in the prevTask. Either it\n\t\t// was nil before, or is the task which was just rejected.\n\t\tc.prevTask = nil\n\n\t// The sessionQueue rejected the task because it is full, we will stash\n\t// this task and try to add it to the next available sessionQueue.\n\tcase reserveExhausted:\n\t\tc.stats.sessionExhausted()\n\n\t\tlog.Debugf(\"Session %s exhausted, backup chanid=%s \"+\n\t\t\t\"commit-height=%d queued for next session\",\n\t\t\tc.sessionQueue.ID(), task.id.ChanID,\n\t\t\ttask.id.CommitHeight)\n\n\t\t// Cache the task that we pulled off, so that we can process it\n\t\t// once a new session queue is available.\n\t\tc.sessionQueue = nil\n\t\tc.prevTask = task\n\t}\n}", "func (_this *RaftNode) ReportUnreachable(id uint64) {}", "func (suite *TaskFailRetryTestSuite) TestTaskFailNoRetry() {\n\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 0,\n\t\t},\n\t}\n\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.taskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}", "func (h *Heartbeat) RemoveTask(name string) error {\n\th.lock <- struct{}{}\n\tdefer func() {\n\t\t<-h.lock\n\t}()\n\tif _, ok := h.slavesTs[name]; !ok {\n\t\treturn terror.ErrSyncerUnitHeartbeatRecordNotFound.Generate(name)\n\t}\n\tdelete(h.slavesTs, name)\n\n\tif len(h.slavesTs) == 0 {\n\t\t// cancel work\n\t\th.cancel()\n\t\th.cancel = nil\n\t\th.wg.Wait()\n\n\t\t// close DB\n\t\th.master.Close()\n\t\th.master = nil\n\t}\n\n\treturn nil\n}", "func (f *Sink) recoverFailed(endpoint *Endpoint) {\n\t// Ignore if we haven't failed\n\tif !endpoint.IsAlive() {\n\t\treturn\n\t}\n\n\tendpoint.mutex.Lock()\n\tendpoint.status = endpointStatusIdle\n\tendpoint.mutex.Unlock()\n\n\tf.failedList.Remove(&endpoint.failedElement)\n\tf.markReady(endpoint)\n}", "func (nm *NodeMonitor) bumpLost() {\n\tnm.pipeLock.Lock()\n\tnm.lost++\n\tnm.pipeLock.Unlock()\n}", "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.killPodForTask(driver, taskId.GetValue(), messages.TaskKilled)\n}", "func (suite *TaskFailRetryTestSuite) TestTaskFailRetryNoTask() {\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(nil)\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.Nil(err)\n\n}", "func (k *KubernetesScheduler) ExecutorLost(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, status int) {\n\tlog.Infof(\"Executor %v of slave %v is lost, status: %v\\n\", executorId, slaveId, status)\n\t// TODO(yifan): Restart any unfinished tasks of the executor.\n}", "func (w *worker) assignUnqueuedTask(bq *InMemoryBuildQueue, t *task) {\n\tif w.currentTask != nil {\n\t\tpanic(\"Worker is already associated with a task\")\n\t}\n\tif t.currentWorker != nil {\n\t\tpanic(\"Task is already associated with a worker\")\n\t}\n\n\tt.registerQueuedStageFinished(bq)\n\tw.currentTask = t\n\tt.currentWorker = w\n\tt.retryCount = 0\n\tfor i := range t.operations {\n\t\ti.incrementExecutingWorkersCount()\n\t}\n\tw.clearLastInvocations()\n}", "func (r *Robot) FailTask(name string, args ...string) RetVal {\n\treturn r.pipeTask(flavorFail, typeTask, name, args...)\n}", "func TrackTaskEnd() {\n\tpersist.DeleteValue(taskPayloadKey)\n\tpersist.DeleteValue(taskEndTimeKey)\n}", "func resetTask(ctx context.Context, settings *evergreen.Settings, taskId, username string, failedOnly bool) error {\n\tt, err := task.FindOneId(taskId)\n\tif err != nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tMessage: errors.Wrapf(err, \"finding task '%s'\", t).Error(),\n\t\t}\n\t}\n\tif t == nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"task '%s' not found\", taskId),\n\t\t}\n\t}\n\treturn errors.Wrapf(serviceModel.ResetTaskOrDisplayTask(ctx, settings, t, username, evergreen.RESTV2Package, failedOnly, nil), \"resetting task '%s'\", taskId)\n}", "func (svc *Service) Fail(ctx context.Context, id, claimID uuid.UUID, reason string) error {\n\tsvc.tasksFailed.Inc()\n\treturn svc.taskGateway.MarkAsFailed(ctx, id, claimID, reason)\n}", "func (this *SyncFlightInfo) MarkFailedNode() {\n\tthis.lock.Lock()\n\tdefer this.lock.Unlock()\n\tthis.failedNodes[this.nodeId] += 1\n\tthis.totalFailed++\n}", "func (fd *FailureDetector) fail() {\n\tfd.curr.Status = statusFailMap[fd.curr.Status.(string)]\n\tfd.ring.UpdateStatus(fd.curr)\n\tif fd.curr.Status.(string) == FAULTY {\n\t\tfd.ring.RemoveSync(fd.curr)\n\t}\n}", "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.removePodTask(driver, taskId.GetValue(), messages.TaskKilled, mesos.TaskState_TASK_KILLED)\n}", "func UpdateRemoveNodeDBInfoTask(taskID string, stepName string) error {\n\tstart := time.Now()\n\n\t// get task form database\n\ttask, err := cloudprovider.GetStorageModel().GetTask(context.Background(), taskID)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s get detail task information from storage failed: %s, task retry\", taskID, taskID, err.Error())\n\t\treturn err\n\t}\n\n\t// task state check\n\tstate := &cloudprovider.TaskState{\n\t\tTask: task,\n\t\tJobResult: cloudprovider.NewJobSyncResult(task),\n\t}\n\t// check task already terminated\n\tif state.IsTerminated() {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s is terminated, step %s skip\", taskID, taskID, stepName)\n\t\treturn fmt.Errorf(\"task %s terminated\", taskID)\n\t}\n\t// workflow switch current step to stepName when previous task exec successful\n\tstep, err := state.IsReadyToStep(stepName)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s not turn ro run step %s, err %s\", taskID, taskID, stepName, err.Error())\n\t\treturn err\n\t}\n\t// previous step successful when retry task\n\tif step == nil {\n\t\tblog.Infof(\"UpdateRemoveNodeDBInfoTask[%s]: current step[%s] successful and skip\", taskID, stepName)\n\t\treturn nil\n\t}\n\n\tblog.Infof(\"UpdateRemoveNodeDBInfoTask[%s] task %s run current step %s, system: %s, old state: %s, params %v\",\n\t\ttaskID, taskID, stepName, step.System, step.Status, step.Params)\n\n\t// extract valid info\n\tsuccess := strings.Split(step.Params[\"NodeIPs\"], \",\")\n\tif len(success) > 0 {\n\t\tfor i := range success {\n\t\t\terr = cloudprovider.GetStorageModel().DeleteNodeByIP(context.Background(), success[i])\n\t\t\tif err != nil {\n\t\t\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s DeleteNodeByIP failed: %v\", taskID, taskID, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// update step\n\tif err := state.UpdateStepSucc(start, stepName); err != nil {\n\t\tblog.Errorf(\"UpdateNodeDBInfoTask[%s] task %s %s update to storage fatal\", taskID, taskID, stepName)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tc *DBTaskConnector) ResetTask(taskId, username string, proj *serviceModel.Project) error {\n\treturn errors.Wrap(serviceModel.TryResetTask(taskId, username, evergreen.RESTV2Package, proj, nil),\n\t\t\"Reset task error\")\n}", "func (r BadgerRepository) Write(t domain.Task) error {\n\tvar buffer bytes.Buffer\n\tencoder := gob.NewEncoder(&buffer)\n\terr := encoder.Encode(t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"badgerrepository: encode task: %w\", err)\n\t}\n\treturn r.badgerOp.Update([]byte(t.ID), buffer.Bytes())\n}", "func (suite *TaskFailRetryTestSuite) TestTaskFailRetry() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 3,\n\t\t},\n\t}\n\n\tsuite.cachedTask.EXPECT().\n\t\tID().\n\t\tReturn(uint32(0)).\n\t\tAnyTimes()\n\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedJob.EXPECT().\n\t\tID().Return(suite.jobID)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.taskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tPatchTasks(gomock.Any(), gomock.Any(), false).\n\t\tDo(func(ctx context.Context,\n\t\t\truntimeDiffs map[uint32]jobmgrcommon.RuntimeDiff,\n\t\t\t_ bool) {\n\t\t\truntimeDiff := runtimeDiffs[suite.instanceID]\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.MesosTaskIDField].(*mesosv1.TaskID).GetValue() != suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.PrevMesosTaskIDField].(*mesosv1.TaskID).GetValue() == suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.StateField].(pbtask.TaskState) == pbtask.TaskState_INITIALIZED)\n\t\t}).Return(nil, nil, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetJobType().Return(pbjob.JobType_BATCH)\n\n\tsuite.taskGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\tsuite.jobGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}", "func (wen *workErrNotifier) Fail(err error) {\n\twen.mutex.Lock()\n\tdefer wen.mutex.Unlock()\n\tif wen.err != nil {\n\t\treturn\n\t}\n\twen.err = err\n\tclose(wen.exitC)\n}", "func (m *Master) ReportTask(args *ReportTaskRequest, reply *ReportTaskResponse) error {\n\tmu.Lock()\n\tif args.Action == 1 {\n\t\t// Task complete\n\t\ttaskStatus := &m.taskStatus[m.workerIDToTaskStatusMap[args.WorkerID]]\n\t\ttaskNode := m.workerIDToTaskNodeMap[args.WorkerID]\n\t\tif taskNode.Value.(TaskStatus).runtime != -1 {\n\t\t\tm.taskStatusList.Remove(taskNode)\n\t\t\tm.finishedTasks = append(m.finishedTasks, taskNode.Value.(TaskStatus).task)\n\t\t}\n\t\t// Mark done if task not time out yet\n\t\tif taskStatus.runtime != -1 {\n\t\t\ttaskStatus.runtime = -1\n\t\t\tm.finishedTasks = append(m.finishedTasks, taskStatus.task)\n\t\t}\n\t}\n\tmu.Unlock()\n\treturn nil\n}", "func (w *Worker) handleTask() {\n\tvar handleTaskInterval = time.Second\n\tfailpoint.Inject(\"handleTaskInterval\", func(val failpoint.Value) {\n\t\tif milliseconds, ok := val.(int); ok {\n\t\t\thandleTaskInterval = time.Duration(milliseconds) * time.Millisecond\n\t\t\tw.l.Info(\"set handleTaskInterval\", zap.String(\"failpoint\", \"handleTaskInterval\"), zap.Int(\"value\", milliseconds))\n\t\t}\n\t})\n\tticker := time.NewTicker(handleTaskInterval)\n\tdefer ticker.Stop()\n\n\tretryCnt := 0\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.l.Info(\"handle task process exits!\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tif w.closed.Get() == closedTrue {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\topLog := w.meta.PeekLog()\n\t\t\tif opLog == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.l.Info(\"start to execute operation\", zap.Reflect(\"oplog\", opLog))\n\n\t\t\tst := w.subTaskHolder.findSubTask(opLog.Task.Name)\n\t\t\tvar err error\n\t\t\tswitch opLog.Task.Op {\n\t\t\tcase pb.TaskOp_Start:\n\t\t\t\tif st != nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskExists.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif w.relayPurger.Purging() {\n\t\t\t\t\tif retryCnt < maxRetryCount {\n\t\t\t\t\t\tretryCnt++\n\t\t\t\t\t\tw.l.Warn(\"relay log purger is purging, cannot start subtask, would try again later\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t\t\tcontinue Loop\n\t\t\t\t\t}\n\n\t\t\t\t\tretryCnt = 0\n\t\t\t\t\terr = terror.ErrWorkerRelayIsPurging.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tretryCnt = 0\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar cfgDecrypted *config.SubTaskConfig\n\t\t\t\tcfgDecrypted, err = taskCfg.DecryptPassword()\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = terror.WithClass(err, terror.ClassDMWorker)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"started sub task\", zap.Stringer(\"config\", cfgDecrypted))\n\t\t\t\tst = NewSubTask(cfgDecrypted)\n\t\t\t\tw.subTaskHolder.recordSubTask(st)\n\t\t\t\tst.Run()\n\n\t\t\tcase pb.TaskOp_Update:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"updated sub task\", zap.String(\"task\", opLog.Task.Name), zap.Stringer(\"new config\", taskCfg))\n\t\t\t\terr = st.Update(taskCfg)\n\t\t\tcase pb.TaskOp_Stop:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"stop sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\tst.Close()\n\t\t\t\tw.subTaskHolder.removeSubTask(opLog.Task.Name)\n\t\t\tcase pb.TaskOp_Pause:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"pause sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Pause()\n\t\t\tcase pb.TaskOp_Resume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\tcase pb.TaskOp_AutoResume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"auto_resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\t}\n\n\t\t\tw.l.Info(\"end to execute operation\", zap.Int64(\"oplog ID\", opLog.Id), log.ShortError(err))\n\n\t\t\tif err != nil {\n\t\t\t\topLog.Message = err.Error()\n\t\t\t} else {\n\t\t\t\topLog.Task.Stage = st.Stage()\n\t\t\t\topLog.Success = true\n\t\t\t}\n\n\t\t\t// fill current task config\n\t\t\tif len(opLog.Task.Task) == 0 {\n\t\t\t\ttm := w.meta.GetTask(opLog.Task.Name)\n\t\t\t\tif tm == nil {\n\t\t\t\t\tw.l.Warn(\"task meta not found\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t} else {\n\t\t\t\t\topLog.Task.Task = append([]byte{}, tm.Task...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr = w.meta.MarkOperation(opLog)\n\t\t\tif err != nil {\n\t\t\t\tw.l.Error(\"fail to mark subtask operation\", zap.Reflect(\"oplog\", opLog))\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Scheduler) noSuitableNode(ctx context.Context, taskGroup map[string]*api.Task, schedulingDecisions map[string]schedulingDecision) {\n\texplanation := s.pipeline.Explain()\n\tfor _, t := range taskGroup {\n\t\tvar service *api.Service\n\t\ts.store.View(func(tx store.ReadTx) {\n\t\t\tservice = store.GetService(tx, t.ServiceID)\n\t\t})\n\t\tif service == nil {\n\t\t\tlog.G(ctx).WithField(\"task.id\", t.ID).Debug(\"removing task from the scheduler\")\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.G(ctx).WithField(\"task.id\", t.ID).Debug(\"no suitable node available for task\")\n\n\t\tnewT := *t\n\t\tnewT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())\n\t\tsv := service.SpecVersion\n\t\ttv := newT.SpecVersion\n\t\tif sv != nil && tv != nil && sv.Index > tv.Index {\n\t\t\tlog.G(ctx).WithField(\"task.id\", t.ID).Debug(\n\t\t\t\t\"task belongs to old revision of service\",\n\t\t\t)\n\t\t\tif t.Status.State == api.TaskStatePending && t.DesiredState >= api.TaskStateShutdown {\n\t\t\t\tlog.G(ctx).WithField(\"task.id\", t.ID).Debug(\n\t\t\t\t\t\"task is desired shutdown, scheduler will go ahead and do so\",\n\t\t\t\t)\n\t\t\t\tnewT.Status.State = api.TaskStateShutdown\n\t\t\t\tnewT.Status.Err = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tif explanation != \"\" {\n\t\t\t\tnewT.Status.Err = \"no suitable node (\" + explanation + \")\"\n\t\t\t} else {\n\t\t\t\tnewT.Status.Err = \"no suitable node\"\n\t\t\t}\n\n\t\t\t// re-enqueue a task that should still be attempted\n\t\t\ts.enqueue(&newT)\n\t\t}\n\n\t\ts.allTasks[t.ID] = &newT\n\t\tschedulingDecisions[t.ID] = schedulingDecision{old: t, new: &newT}\n\t}\n}", "func (suite *TaskFailRetryTestSuite) TestTaskFailSystemFailure() {\n\tsuite.taskRuntime.Reason = mesosv1.TaskStatus_REASON_CONTAINER_LAUNCH_FAILED.String()\n\n\ttestTable := []*pbtask.RuntimeInfo{\n\t\t{\n\t\t\tMesosTaskId: &mesosv1.TaskID{Value: &suite.mesosTaskID},\n\t\t\tState: pbtask.TaskState_FAILED,\n\t\t\tGoalState: pbtask.TaskState_SUCCEEDED,\n\t\t\tConfigVersion: 1,\n\t\t\tMessage: \"testFailure\",\n\t\t\tReason: mesosv1.TaskStatus_REASON_CONTAINER_LAUNCH_FAILED.String(),\n\t\t},\n\t\t{\n\t\t\tMesosTaskId: &mesosv1.TaskID{Value: &suite.mesosTaskID},\n\t\t\tState: pbtask.TaskState_FAILED,\n\t\t\tGoalState: pbtask.TaskState_SUCCEEDED,\n\t\t\tConfigVersion: 1,\n\t\t\tMessage: \"Container terminated with signal Broken pipe\",\n\t\t\tReason: mesosv1.TaskStatus_REASON_COMMAND_EXECUTOR_FAILED.String(),\n\t\t},\n\t}\n\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 0,\n\t\t},\n\t}\n\n\tsuite.cachedTask.EXPECT().\n\t\tID().\n\t\tReturn(uint32(0)).\n\t\tAnyTimes()\n\n\tfor _, taskRuntime := range testTable {\n\n\t\tsuite.jobFactory.EXPECT().\n\t\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\t\tsuite.cachedJob.EXPECT().\n\t\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\t\tsuite.cachedJob.EXPECT().\n\t\t\tID().Return(suite.jobID)\n\n\t\tsuite.cachedTask.EXPECT().\n\t\t\tGetRuntime(gomock.Any()).Return(taskRuntime, nil)\n\n\t\tsuite.taskConfigV2Ops.EXPECT().\n\t\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\t\tsuite.cachedJob.EXPECT().\n\t\t\tPatchTasks(gomock.Any(), gomock.Any(), false).\n\t\t\tDo(func(ctx context.Context,\n\t\t\t\truntimeDiffs map[uint32]jobmgrcommon.RuntimeDiff,\n\t\t\t\t_ bool) {\n\t\t\t\truntimeDiff := runtimeDiffs[suite.instanceID]\n\t\t\t\tsuite.True(\n\t\t\t\t\truntimeDiff[jobmgrcommon.MesosTaskIDField].(*mesosv1.TaskID).GetValue() != suite.mesosTaskID)\n\t\t\t\tsuite.True(\n\t\t\t\t\truntimeDiff[jobmgrcommon.PrevMesosTaskIDField].(*mesosv1.TaskID).GetValue() == suite.mesosTaskID)\n\t\t\t\tsuite.True(\n\t\t\t\t\truntimeDiff[jobmgrcommon.StateField].(pbtask.TaskState) == pbtask.TaskState_INITIALIZED)\n\t\t\t}).Return(nil, nil, nil)\n\n\t\tsuite.cachedJob.EXPECT().\n\t\t\tGetJobType().Return(pbjob.JobType_BATCH)\n\n\t\tsuite.taskGoalStateEngine.EXPECT().\n\t\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\t\tReturn()\n\n\t\tsuite.jobGoalStateEngine.EXPECT().\n\t\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\t\tReturn()\n\n\t\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\t\tsuite.NoError(err)\n\t}\n}", "func (m *Master) checkTask(taskType int, taskId int) {\n\ttime.Sleep(time.Second * 10)\n\tif taskType == MapTask {\n\t\t_, exists := m.mapInProgress[taskId]\n\t\tif exists {\n\t\t\tm.mapNotAssigned.PushBack(taskId)\n\t\t\tlog.Println(\"1 map task failed\")\n\t\t}\n\t} else if taskType == ReduceTask {\n\t\t_, exists := m.reduceInProgress[taskId]\n\t\tif exists {\n\t\t\tm.reduceNotAssigned.PushBack(taskId)\n\t\t\tlog.Println(\"1 reduce task failed\")\n\t\t}\n\t}\n}", "func (p *statusUpdate) logTaskMetrics(event *statusupdate.Event) {\n\tif event.V0() == nil {\n\t\treturn\n\t}\n\t// Update task state counter for non-reconcilication update.\n\treason := event.MesosTaskStatus().GetReason()\n\tif reason != mesos.TaskStatus_REASON_RECONCILIATION {\n\t\tswitch event.State() {\n\t\tcase pb_task.TaskState_RUNNING:\n\t\t\tp.metrics.TasksRunningTotal.Inc(1)\n\t\tcase pb_task.TaskState_SUCCEEDED:\n\t\t\tp.metrics.TasksSucceededTotal.Inc(1)\n\t\tcase pb_task.TaskState_FAILED:\n\t\t\tp.metrics.TasksFailedTotal.Inc(1)\n\t\t\tp.metrics.TasksFailedReason[int32(reason)].Inc(1)\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"task_id\": event.TaskID(),\n\t\t\t\t\"failed_reason\": mesos.TaskStatus_Reason_name[int32(reason)],\n\t\t\t}).Debug(\"received failed task\")\n\t\tcase pb_task.TaskState_KILLED:\n\t\t\tp.metrics.TasksKilledTotal.Inc(1)\n\t\tcase pb_task.TaskState_LOST:\n\t\t\tp.metrics.TasksLostTotal.Inc(1)\n\t\tcase pb_task.TaskState_LAUNCHED:\n\t\t\tp.metrics.TasksLaunchedTotal.Inc(1)\n\t\tcase pb_task.TaskState_STARTING:\n\t\t\tp.metrics.TasksStartingTotal.Inc(1)\n\t\t}\n\t} else {\n\t\tp.metrics.TasksReconciledTotal.Inc(1)\n\t}\n}", "func (r *Residency) SetTaskLostBehavior(behavior TaskLostBehaviorType) *Residency {\n\tr.TaskLostBehavior = behavior\n\treturn r\n}", "func (p *statusUpdate) isOrphanTaskEvent(\n\tctx context.Context,\n\tevent *statusupdate.Event,\n) (bool, *pb_task.TaskInfo, error) {\n\ttaskInfo, err := p.taskStore.GetTaskByID(ctx, event.TaskID())\n\tif err != nil {\n\t\tif yarpcerrors.IsNotFound(err) {\n\t\t\t// if task runtime or config is not present in the DB,\n\t\t\t// then the task is orphan\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"mesos_task_id\": event.MesosTaskStatus(),\n\t\t\t\t\"task_status_event≠\": event.State().String(),\n\t\t\t}).Info(\"received status update for task not found in DB\")\n\t\t\treturn true, nil, nil\n\t\t}\n\n\t\tlog.WithError(err).\n\t\t\tWithField(\"task_id\", event.TaskID()).\n\t\t\tWithField(\"task_status_event\", event.MesosTaskStatus()).\n\t\t\tWithField(\"state\", event.State().String()).\n\t\t\tError(\"fail to find taskInfo for taskID for mesos event\")\n\t\treturn false, nil, err\n\t}\n\n\t// TODO p2k: verify v1 pod id in taskInfo\n\tif event.V0() != nil {\n\t\tdbTaskID := taskInfo.GetRuntime().GetMesosTaskId().GetValue()\n\t\tif dbTaskID != event.MesosTaskStatus().GetTaskId().GetValue() {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"orphan_task_id\": event.MesosTaskStatus().GetTaskId().GetValue(),\n\t\t\t\t\"db_task_id\": dbTaskID,\n\t\t\t\t\"db_task_runtime_state\": taskInfo.GetRuntime().GetState().String(),\n\t\t\t\t\"mesos_event_state\": event.State().String(),\n\t\t\t}).Info(\"received status update for orphan mesos task\")\n\t\t\treturn true, nil, nil\n\t\t}\n\t}\n\n\treturn false, taskInfo, nil\n}", "func (t *NqmAgent) Task(request commonModel.NqmTaskRequest, response *commonModel.NqmTaskResponse) (err error) {\n\tdefer rpc.HandleError(&err)()\n\n\t/**\n\t * Validates data\n\t */\n\tif err = validatePingTask(&request); err != nil {\n\t\treturn fmt.Errorf(\"[NQM Heartbeat] Validate request(%v) error: %v\", request, err)\n\t}\n\t// :~)\n\n\tresponse.NeedPing = false\n\tresponse.Agent = nil\n\tresponse.Targets = nil\n\tresponse.Measurements = nil\n\n\tagentHeartbeatReq := &nqmModel.HeartbeatRequest{\n\t\tConnectionId: request.ConnectionId,\n\t\tHostname: request.Hostname,\n\t\tIpAddress: json.NewIP(request.IpAddress),\n\t\tTimestamp: json.JsonTime(time.Now()),\n\t}\n\n\tnqmAgentHeartbeatResp, err := service.NqmAgentHeartbeat(agentHeartbeatReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[NQM Heartbeat] Heartbeat call error: (request=%v) %v\", request, err)\n\t}\n\n\tif !nqmAgentHeartbeatResp.Status {\n\t\treturn\n\t}\n\n\tnqmAgentHeartbeatTargetList, err := service.NqmAgentHeartbeatTargetList(nqmAgentHeartbeatResp.Id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[NQM Heartbeat] Get target list of agent(%v) error: %v\", nqmAgentHeartbeatResp, err)\n\t}\n\n\tresponse.NeedPing = true\n\tresponse.Agent = toOldAgent(nqmAgentHeartbeatResp)\n\tresponse.Targets = toOldTargets(nqmAgentHeartbeatTargetList)\n\tresponse.Measurements = map[string]commonModel.MeasurementsProperty{\n\t\t\"fping\": {true, []string{\"fping\", \"-p\", \"20\", \"-i\", \"10\", \"-C\", \"4\", \"-q\", \"-a\"}, 300},\n\t\t\"tcpping\": {false, []string{\"tcpping\", \"-i\", \"0.01\", \"-c\", \"4\"}, 300},\n\t\t\"tcpconn\": {false, []string{\"tcpconn\"}, 300},\n\t}\n\treturn\n}", "func (t *task) reportNonFinalStageChange() {\n\tclose(t.stageChangeWakeup)\n\tt.stageChangeWakeup = make(chan struct{})\n}", "func TestPromoteReplicaHealthTicksStopped(t *testing.T) {\n\tctx := context.Background()\n\tts := memorytopo.NewServer(\"cell1\")\n\tstatsTabletTypeCount.ResetAll()\n\ttm := newTestTM(t, ts, 100, keyspace, shard)\n\tdefer tm.Stop()\n\n\t_, err := tm.PromoteReplica(ctx, false)\n\trequire.NoError(t, err)\n\trequire.False(t, tm.replManager.ticks.Running())\n}", "func (k *KubernetesExecutor) removePodTask(driver bindings.ExecutorDriver, tid, reason string, state mesos.TaskState) {\n\ttask, ok := k.tasks[tid]\n\tif !ok {\n\t\tlog.V(1).Infof(\"Failed to remove task, unknown task %v\\n\", tid)\n\t\treturn\n\t}\n\tdelete(k.tasks, tid)\n\n\tpid := task.podName\n\tif _, found := k.pods[pid]; !found {\n\t\tlog.Warningf(\"Cannot remove unknown pod %v for task %v\", pid, tid)\n\t} else {\n\t\tlog.V(2).Infof(\"deleting pod %v for task %v\", pid, tid)\n\t\tdelete(k.pods, pid)\n\n\t\t// Send the pod updates to the channel.\n\t\tupdate := kubelet.PodUpdate{Op: kubelet.SET}\n\t\tfor _, p := range k.pods {\n\t\t\tupdate.Pods = append(update.Pods, *p)\n\t\t}\n\t\tk.updateChan <- update\n\t}\n\t// TODO(jdef): ensure that the update propagates, perhaps return a signal chan?\n\tk.sendStatus(driver, newStatus(mutil.NewTaskID(tid), state, reason))\n}", "func (t *task) deleteTask() {\n\t// There is no state to clean up as of now.\n\t// If the goal state was set to DELETED, then let the\n\t// listeners know that the task has been deleted.\n\n\tvar runtimeCopy *pbtask.RuntimeInfo\n\tvar labelsCopy []*peloton.Label\n\n\t// notify listeners after dropping the lock\n\tdefer func() {\n\t\tif runtimeCopy != nil {\n\t\t\tt.jobFactory.notifyTaskRuntimeChanged(\n\t\t\t\tt.jobID,\n\t\t\t\tt.id,\n\t\t\t\tt.jobType,\n\t\t\t\truntimeCopy,\n\t\t\t\tlabelsCopy,\n\t\t\t)\n\t\t}\n\t}()\n\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\tif t.runtime == nil {\n\t\treturn\n\t}\n\n\tif t.runtime.GetGoalState() != pbtask.TaskState_DELETED {\n\t\treturn\n\t}\n\n\truntimeCopy = proto.Clone(t.runtime).(*pbtask.RuntimeInfo)\n\truntimeCopy.State = pbtask.TaskState_DELETED\n\tlabelsCopy = t.copyLabelsInCache()\n}", "func (h *Heartbeat) AddTask(name string) error {\n\th.lock <- struct{}{} // send to chan, acquire the lock\n\tdefer func() {\n\t\t<-h.lock // read from the chan, release the lock\n\t}()\n\tif _, ok := h.slavesTs[name]; ok {\n\t\treturn terror.ErrSyncerUnitHeartbeatRecordExists.Generate(name)\n\t}\n\tif h.master == nil {\n\t\t// open DB\n\t\tdbCfg := h.cfg.masterCfg\n\t\tdbDSN := fmt.Sprintf(\"%s:%s@tcp(%s:%d)/?charset=utf8&interpolateParams=true&readTimeout=1m\", dbCfg.User, dbCfg.Password, dbCfg.Host, dbCfg.Port)\n\t\tmaster, err := sql.Open(\"mysql\", dbDSN)\n\t\tif err != nil {\n\t\t\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n\t\t}\n\t\th.master = master\n\n\t\t// init table\n\t\terr = h.init()\n\t\tif err != nil {\n\t\t\th.master.Close()\n\t\t\th.master = nil\n\t\t\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n\t\t}\n\n\t\t// run work\n\t\tif h.cancel != nil {\n\t\t\th.cancel()\n\t\t\th.cancel = nil\n\t\t\th.wg.Wait()\n\t\t}\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\th.cancel = cancel\n\n\t\th.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer h.wg.Done()\n\t\t\th.run(ctx)\n\t\t}()\n\t}\n\th.slavesTs[name] = 0 // init to 0\n\treturn nil\n}", "func (r *reporter) Fail() {\n\tatomic.StoreInt32(&r.failed, 1)\n}", "func (ps *raftFollowerStats) Fail() {\n\tps.Counts.Fail++\n}", "func (k *KubernetesExecutor) killPodForTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_KILLED)\n}", "func (k *KubernetesExecutor) removePodTask(driver bindings.ExecutorDriver, tid, reason string, state mesos.TaskState) {\n\ttask, ok := k.tasks[tid]\n\tif !ok {\n\t\tlog.V(1).Infof(\"Failed to remove task, unknown task %v\\n\", tid)\n\t\treturn\n\t}\n\tdelete(k.tasks, tid)\n\tk.resetSuicideWatch(driver)\n\n\tpid := task.podName\n\tpod, found := k.pods[pid]\n\tif !found {\n\t\tlog.Warningf(\"Cannot remove unknown pod %v for task %v\", pid, tid)\n\t} else {\n\t\tlog.V(2).Infof(\"deleting pod %v for task %v\", pid, tid)\n\t\tdelete(k.pods, pid)\n\n\t\t// tell the kubelet to remove the pod\n\t\tupdate := kubelet.PodUpdate{\n\t\t\tOp: kubelet.REMOVE,\n\t\t\tPods: []*api.Pod{pod},\n\t\t}\n\t\tk.updateChan <- update\n\t}\n\t// TODO(jdef): ensure that the update propagates, perhaps return a signal chan?\n\tk.sendStatus(driver, newStatus(mutil.NewTaskID(tid), state, reason))\n}", "func RejectTask(applicationName string, update bool) error {\n\tgetTaskResp, err := GetTaskByApplicationName(applicationName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(getTaskResp) == 0 {\n\t\treturn fmt.Errorf(\"no tasks for application %s\", applicationName)\n\t}\n\n\terr = HTTPClient(http.MethodPost, fmt.Sprintf(RejectTaskURI, getTaskResp[0].ID, update), nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func testUpdateTaskWithRetriesTaskNotFound(t sktest.TestingT, db TaskDB) {\n\tctx := context.Background()\n\tbegin := time.Now()\n\n\t// Assign ID for a task, but don't put it in the DB.\n\tt1 := types.MakeTestTask(begin.Add(TS_RESOLUTION), []string{\"a\", \"b\", \"c\", \"d\"})\n\trequire.NoError(t, db.AssignId(ctx, t1))\n\n\t// Attempt to update non-existent task. Function shouldn't be called.\n\tcallCount := 0\n\tnoTask, err := UpdateTaskWithRetries(ctx, db, t1.Id, func(task *types.Task) error {\n\t\tcallCount++\n\t\ttask.Status = types.TASK_STATUS_RUNNING\n\t\treturn nil\n\t})\n\trequire.True(t, IsNotFound(err))\n\trequire.Nil(t, noTask)\n\trequire.Equal(t, 0, callCount)\n\n\t// Check no tasks in the DB.\n\ttasks, err := db.GetTasksFromDateRange(ctx, begin, time.Now().Add(2*TS_RESOLUTION), \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(tasks))\n}", "func (r *reporter) Fail() {\n\tif r.parent != nil && !r.retryable {\n\t\tr.parent.Fail()\n\t}\n\tatomic.StoreInt32(&r.failed, 1)\n}", "func (w *taskWorker) handleTask(ctx context.Context, task queue.Task) (err error) {\n\tspan, ctx := w.StartSpan(ctx, \"handleTask\")\n\tctx, cancel := context.WithCancel(ctx)\n\tlabels := prometheus.Labels{\"queue\": task.Queue, \"type\": task.Type.String()}\n\tdefer func() {\n\t\tcancel()\n\t\tw.FinishSpan(span, err)\n\t}()\n\n\ttimer := prometheus.NewTimer(queue.TaskWorkerMetrics.ProcessingDuration)\n\tdefer timer.ObserveDuration()\n\n\tlogger := logrus.WithContext(ctx).\n\t\tWithField(\"worker\", \"handleTask\").\n\t\tWithField(\"queue\", task.Queue)\n\n\theartbeats := make(chan queue.Progress)\n\tprocessDone := make(chan error, 1)\n\n\tgo func() {\n\t\t// handle panics because we force close the heartbeats if the beats are too slow\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlogger.Errorf(\"Recovered in task handler.Process: %v\", r)\n\t\t\t}\n\t\t}()\n\t\t// force cleanup heartbeats, this might cause a panic ....\n\t\tdefer func() {\n\t\t\t//nolint: errcheck // we don't care about any errors here because we are force closing the channel\n\t\t\tdefer recover()\n\t\t\tdefer close(heartbeats)\n\t\t\tdefer close(processDone)\n\t\t}()\n\n\t\t// handler.Process is responsible for closing the heartbeats channel\n\t\t// if `Process` returns an error it means the task failed\n\t\tprocessDone <- w.handler.Process(ctx, task, heartbeats)\n\t}()\n\n\t// block while we process the heartbeats\n\tprogress, err := w.processHeartbeats(ctx, task, heartbeats)\n\tif err == ErrHeartbeatTimeout {\n\t\t// we must try to put the error message in the latest version of progress\n\t\t// empty progress (no heartbeats) is also fine\n\t\tspan.SetTag(\"err\", err)\n\t\tqueue.TaskWorkerMetrics.ProcessingErrorsCounter.With(labels).Inc()\n\n\t\tprogress = w.setError(progress, err)\n\t\treturn w.dequeuer.Fail(ctx, task.ID, progress)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// now wait for the worker processing error\n\tworkErr := <-processDone\n\tif workErr != nil {\n\t\t// we must try to put the error message in the latest version of progress\n\t\t// empty progress (no heartbeats) is also fine\n\t\tspan.SetTag(\"workErr\", workErr)\n\t\tqueue.TaskWorkerMetrics.ProcessingErrorsCounter.With(labels).Inc()\n\n\t\tprogress = w.setError(progress, workErr)\n\t\treturn w.dequeuer.Fail(ctx, task.ID, progress)\n\t}\n\n\terr = w.dequeuer.Finish(ctx, task.ID, progress)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueue.TaskWorkerMetrics.ProcessedCounter.With(labels).Inc()\n\treturn nil\n}", "func (k *KubernetesScheduler) Disconnected(driver mesos.SchedulerDriver) {\n\tlog.Infof(\"Master disconnected!\\n\")\n\tk.registered = false\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// discard all cached offers to avoid unnecessary TASK_LOST updates\n\tfor offerId := range k.offers {\n\t\tk.deleteOffer(offerId)\n\t}\n\n\t// TODO(jdef): it's possible that a task is pending, in between Schedule() and\n\t// Bind(), such that it's offer is now invalid. We should check for that and\n\t// clearing the offer from the task (along with a related check in Bind())\n}", "func isDuplicateStateUpdate(\n\ttaskInfo *pb_task.TaskInfo,\n\tupdateEvent *statusupdate.Event,\n) bool {\n\tif updateEvent.State() != taskInfo.GetRuntime().GetState() {\n\t\treturn false\n\t}\n\n\tmesosTaskStatus := updateEvent.MesosTaskStatus()\n\tpodEvent := updateEvent.PodEvent()\n\n\tif updateEvent.State() != pb_task.TaskState_RUNNING {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if state is not RUNNING\")\n\t\treturn true\n\t}\n\n\tif taskInfo.GetConfig().GetHealthCheck() == nil ||\n\t\t!taskInfo.GetConfig().GetHealthCheck().GetEnabled() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check is not configured or \" +\n\t\t\t\"disabled\")\n\t\treturn true\n\t}\n\n\tnewStateReason := updateEvent.Reason()\n\t// TODO p2k: not sure which kubelet reason matches this.\n\t// Should we skip some status updates from kubelets?\n\tif newStateReason != mesos.TaskStatus_REASON_TASK_HEALTH_CHECK_STATUS_UPDATED.String() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if status update reason is not from health check\")\n\t\treturn true\n\t}\n\n\t// Current behavior will log consecutive negative health check results\n\t// ToDo (varung): Evaluate if consecutive negative results should be logged or not\n\tisPreviousStateHealthy := taskInfo.GetRuntime().GetHealthy() == pb_task.HealthState_HEALTHY\n\tif !isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"log each negative health check result\")\n\t\treturn false\n\t}\n\n\tif updateEvent.Healthy() == isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check result is positive consecutively\")\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (d *dispatcher) scheduleTask(taskID int64) {\n\tticker := time.NewTicker(checkTaskFinishedInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-d.ctx.Done():\n\t\t\tlogutil.BgLogger().Info(\"schedule task exits\", zap.Int64(\"task ID\", taskID), zap.Error(d.ctx.Err()))\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tstepIsFinished, errs := d.monitorTask(taskID)\n\t\t\tfailpoint.Inject(\"cancelTaskAfterMonitorTask\", func(val failpoint.Value) {\n\t\t\t\tif val.(bool) && d.task.State == proto.TaskStateRunning {\n\t\t\t\t\terr := d.taskMgr.CancelGlobalTask(taskID)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogutil.BgLogger().Error(\"cancel task failed\", zap.Error(err))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t// The global task isn't finished and not failed.\n\t\t\tif !stepIsFinished && len(errs) == 0 {\n\t\t\t\tGetTaskFlowHandle(d.task.Type).OnTicker(d.ctx, d.task)\n\t\t\t\tlogutil.BgLogger().Debug(\"schedule task, this task keeps current state\",\n\t\t\t\t\tzap.Int64(\"task-id\", d.task.ID), zap.String(\"state\", d.task.State))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\terr := d.processFlow(d.task, errs)\n\t\t\tif err == nil && d.task.IsFinished() {\n\t\t\t\tlogutil.BgLogger().Info(\"schedule task, task is finished\",\n\t\t\t\t\tzap.Int64(\"task-id\", d.task.ID), zap.String(\"state\", d.task.State))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfailpoint.Inject(\"mockOwnerChange\", func(val failpoint.Value) {\n\t\t\tif val.(bool) {\n\t\t\t\tlogutil.BgLogger().Info(\"mockOwnerChange called\")\n\t\t\t\tMockOwnerChange()\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t})\n\t}\n}", "func (p *Prober) NotHealthy(err error) {\n\told := atomic.SwapUint32(&p.healthy, 0)\n\n\tif old == 1 {\n\t\tlevel.Info(p.logger).Log(\"msg\", \"changing probe status\", \"status\", \"healthy\")\n\t}\n}", "func (c *Curator) reportBadTS(id core.TractID, badAddr string) core.Error {\n\tbadID, found := c.tsMon.getIDByAddr(badAddr)\n\n\t// The client is complaining about this host but we haven't gotten a heartbeat from it yet.\n\tif !found {\n\t\tlog.Errorf(\"reportBadTS: %s tsMon didn't have id for addr %s\", id, badAddr)\n\t\treturn core.ErrHostNotExist\n\t}\n\n\tselect {\n\tcase c.blockedChan <- clientComplaint{id: id, tsid: badID}:\n\t\tlog.Infof(\"reportBadTS: %s added to blocked list\", id)\n\t\treturn core.NoError\n\tdefault:\n\t\tlog.Errorf(\"reportBadTS: %s blocked list too full, dropped\", id)\n\t\treturn core.ErrTooBusy\n\t}\n}", "func (_m *StateOps) RefreshTaskState() {\n\t_m.Called()\n}", "func (m *Master) finishTask(args *Args) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif m.status == MapStage {\n\t\tdelete(m.mapInProgress, args.TaskId)\n\t\tm.mapFinished++\n\t\tif m.mapFinished == len(m.mapTasks) {\n\t\t\tm.status = ReduceStage\n\t\t}\n\t\tfmt.Println(\"finished 1 map task\")\n\t} else if m.status == ReduceStage {\n\t\tdelete(m.reduceInProgress, args.TaskId)\n\t\tm.reduceFinished++\n\t\tif m.reduceFinished == m.reduceTasks {\n\t\t\tm.status = FinishedStage\n\t\t}\n\t\tm.deleteIntermediates(args.TaskId)\n\t\tfmt.Println(\"finished 1 reduce task\")\n\t}\n}", "func (m *Memberlist) deadNode(d *dead) {\n\tm.nodeLock.Lock()\n\tdefer m.nodeLock.Unlock()\n\tstate, ok := m.nodeMap[d.Node]\n\n\t// If we've never heard about this node before, ignore it\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Ignore old incarnation numbers\n\tif d.Incarnation < state.Incarnation {\n\t\treturn\n\t}\n\n\t// Clear out any suspicion timer that may be in effect.\n\tdelete(m.nodeTimers, d.Node)\n\n\t// Ignore if node is already dead\n\tif state.DeadOrLeft() {\n\t\treturn\n\t}\n\n\t// Check if this is us\n\tif state.Name == m.config.Name {\n\t\t// If we are not leaving we need to refute\n\t\tif !m.hasLeft() {\n\t\t\tm.refute(state, d.Incarnation)\n\t\t\tm.logger.Printf(\"[WARN] memberlist: Refuting a dead message (from: %s)\", d.From)\n\t\t\treturn // Do not mark ourself dead\n\t\t}\n\n\t\t// If we are leaving, we broadcast and wait\n\t\tm.encodeBroadcastNotify(d.Node, deadMsg, d, m.leaveBroadcast)\n\t} else {\n\t\tm.encodeAndBroadcast(d.Node, deadMsg, d)\n\t}\n\n\t// Update metrics\n\tmetrics.IncrCounterWithLabels([]string{\"memberlist\", \"msg\", \"dead\"}, 1, m.metricLabels)\n\n\t// Update the state\n\tstate.Incarnation = d.Incarnation\n\n\t// If the dead message was send by the node itself, mark it is left\n\t// instead of dead.\n\tif d.Node == d.From {\n\t\tstate.State = StateLeft\n\t} else {\n\t\tstate.State = StateDead\n\t}\n\tstate.StateChange = time.Now()\n\n\t// Notify of death\n\tif m.config.Events != nil {\n\t\tm.config.Events.NotifyLeave(&state.Node)\n\t}\n}", "func (p *promise) Fail() {\n\trt := int64((time.Since(initTime) - p.sinceTime) / time.Millisecond)\n\tp.bbr.rtStat.Add(rt)\n\tatomic.AddInt64(&p.bbr.inFlight, -1)\n}", "func (_m *MutableNodeStatus) ClearTaskStatus() {\n\t_m.Called()\n}", "func (ts *TasksRPC) GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) {\n\tvar rsp taskproto.TaskResponse\n\tctx = common.GetContextData(ctx)\n\tctx = common.ModifyContext(ctx, common.TaskService, podName)\n\n\tl.LogWithFields(ctx).Debugf(\"Incoming request to get the task details and response body for the task %v\", req.TaskID)\n\trsp.Header = map[string]string{\n\t\t\"Date\": time.Now().Format(http.TimeFormat),\n\t}\n\tprivileges := []string{common.PrivilegeLogin}\n\tauthResp, err := ts.AuthenticationRPC(ctx, req.SessionToken, privileges)\n\tif authResp.StatusCode != http.StatusOK {\n\t\tif err != nil {\n\t\t\tl.LogWithFields(ctx).Errorf(\"Error while authorizing the session token : %s\", err.Error())\n\t\t}\n\t\tfillProtoResponse(ctx, &rsp, authResp)\n\t\treturn &rsp, nil\n\t}\n\t_, err = ts.GetSessionUserNameRPC(ctx, req.SessionToken)\n\tif err != nil {\n\t\tl.LogWithFields(ctx).Printf(authErrorMessage)\n\t\tfillProtoResponse(ctx, &rsp, common.GeneralError(http.StatusUnauthorized, response.NoValidSession, authErrorMessage, nil, nil))\n\t\treturn &rsp, nil\n\t}\n\t// get task status from database using task id\n\ttask, err := ts.GetTaskStatusModel(ctx, req.TaskID, common.InMemory)\n\tif err != nil {\n\t\tl.LogWithFields(ctx).Printf(\"error getting task status : %v\", err)\n\t\tfillProtoResponse(ctx, &rsp, common.GeneralError(http.StatusNotFound, response.ResourceNotFound, err.Error(), []interface{}{\"Task\", req.TaskID}, nil))\n\t\treturn &rsp, nil\n\t}\n\n\t// Check the state of the task\n\tif task.TaskState == \"Completed\" || task.TaskState == \"Cancelled\" || task.TaskState == \"Killed\" || task.TaskState == \"Exception\" {\n\t\t// return with the actual status code, along with response header and response body\n\t\t//Build the response Body\n\t\trsp.Header = task.Payload.HTTPHeaders\n\t\trsp.Body = task.TaskResponse\n\t\trsp.StatusCode = task.StatusCode\n\t\t// Delete the task from db as it is completed and user requested for the details.\n\t\t// return the user with task details by deleting the task from db\n\t\t// User should be careful as this is the last call to Task monitor API.\n\t\t/*\n\t\t\terr := task.Delete()\n\t\t\tif err != nil {\n\t\t\t\tl.Log.Printf(\"error while deleting the task from db: %v\", err)\n\t\t\t}\n\t\t*/\n\t\treturn &rsp, nil\n\t}\n\t// Construct the Task object to return as long as 202 code is being returned.\n\n\tmessageList := []tresponse.Messages{}\n\tfor _, element := range task.Messages {\n\t\tmessage := tresponse.Messages{\n\t\t\tMessageID: element.MessageID,\n\t\t\tRelatedProperties: element.RelatedProperties,\n\t\t\tMessage: element.Message,\n\t\t\tMessageArgs: element.MessageArgs,\n\t\t\tSeverity: element.Severity,\n\t\t}\n\t\tmessageList = append(messageList, message)\n\t}\n\n\tcommonResponse := response.Response{\n\t\tOdataType: common.TaskType,\n\t\tID: task.ID,\n\t\tName: task.Name,\n\t\tOdataContext: \"/redfish/v1/$metadata#Task.Task\",\n\t\tOdataID: \"/redfish/v1/TaskService/Tasks/\" + task.ID,\n\t}\n\trsp.StatusCode = http.StatusAccepted\n\trsp.StatusMessage = response.TaskStarted\n\tcommonResponse.MessageArgs = []string{task.ID}\n\tcommonResponse.CreateGenericResponse(rsp.StatusMessage)\n\n\thttpHeaders := []string{}\n\tfor key, value := range task.Payload.HTTPHeaders {\n\t\thttpHeaders = append(httpHeaders, fmt.Sprintf(\"%v: %v\", key, value))\n\t}\n\n\ttaskResponse := tresponse.Task{\n\t\tResponse: commonResponse,\n\t\tTaskState: task.TaskState,\n\t\tStartTime: task.StartTime.UTC(),\n\t\tEndTime: task.EndTime.UTC(),\n\t\tTaskStatus: task.TaskStatus,\n\t\tMessages: messageList,\n\t\tTaskMonitor: task.TaskMonitor,\n\t\tPayload: tresponse.Payload{\n\t\t\tHTTPHeaders: httpHeaders,\n\t\t\tHTTPOperation: task.Payload.HTTPOperation,\n\t\t\tJSONBody: string(task.Payload.JSONBody),\n\t\t\tTargetURI: task.Payload.TargetURI,\n\t\t},\n\t\tPercentComplete: task.PercentComplete,\n\t}\n\tif task.ParentID == \"\" {\n\t\tvar subTask = tresponse.ListMember{\n\t\t\tOdataID: \"/redfish/v1/TaskService/Tasks/\" + task.ID + \"/SubTasks\",\n\t\t}\n\t\ttaskResponse.SubTasks = &subTask\n\t}\n\trespBody := generateResponse(ctx, taskResponse)\n\trsp.Body = respBody\n\tl.LogWithFields(ctx).Debugf(\"Outgoing response for getting subtasks: %v\", string(respBody))\n\n\trsp.Header[\"location\"] = task.TaskMonitor\n\treturn &rsp, nil\n}", "func (r *Raft) handleStaleTerm(replication *followerReplication) {\n\tklog.Errorf(fmt.Sprintf(\"peer:%s/%s has newer term, stopping replication\", replication.peer.ID, replication.peer.Address))\n\treplication.notifyAll(false) // No longer leader\n\tselect {\n\tcase replication.stepDown <- struct{}{}:\n\tdefault:\n\t}\n}", "func (b *Consecutive) Fail() {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\n\tb.failures++\n\n\tif b.state == open {\n\t\treturn\n\t}\n\n\tif b.instantProvider == nil {\n\t\tb.instantProvider = systemTimer\n\t}\n\n\tif b.failures > b.FailureAllowance {\n\t\tb.nextClose = b.instantProvider.Now().Add(b.RetryTimeout)\n\t\tb.state = open\n\t}\n}", "func (f *Failer) KillTask(host, task string) error {\n\tscript := \"sudo pkill -x %s\"\n\tlog.V(1).Infof(\"Killing task %s on host %s\", task, host)\n\treturn f.runWithEvilTag(host, fmt.Sprintf(script, task))\n}", "func (r NopReporter) Recover(ctx context.Context) { _ = recover() }", "func reportASorrowfulDeathToPeers(node *Node) {\n\tmsg := &Message{IsDeathReport: true, Node: *node}\n\tlogMsg := \"Node \" + node.Id + \"is dead, reporting sorrowful death\"\n\tsendPacketsToPeers(logMsg, msg)\n}", "func underwaterUnschedule(distroID string) error {\n\tif underwaterPruningEnabled {\n\t\tnum, err := task.UnscheduleStaleUnderwaterTasks(distroID)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tgrip.InfoWhen(num > 0, message.Fields{\n\t\t\t\"message\": \"unscheduled stale tasks\",\n\t\t\t\"runner\": RunnerName,\n\t\t\t\"count\": num,\n\t\t})\n\t}\n\n\treturn nil\n}", "func underwaterUnschedule(distroID string) error {\n\tif underwaterPruningEnabled {\n\t\tnum, err := task.UnscheduleStaleUnderwaterTasks(distroID)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tgrip.InfoWhen(num > 0, message.Fields{\n\t\t\t\"message\": \"unscheduled stale tasks\",\n\t\t\t\"runner\": RunnerName,\n\t\t\t\"count\": num,\n\t\t})\n\t}\n\n\treturn nil\n}", "func (n *NameService) ReportFailedNode(nodeID fred.NodeID, kg fred.KeygroupName, id string) error {\n\n}", "func (n *resPool) AddInvalidTask(task *peloton.TaskID) {\n\tn.Lock()\n\tdefer n.Unlock()\n\tn.invalidTasks[task.Value] = true\n}", "func testUpdateTaskWithRetriesExhausted(t sktest.TestingT, db TaskDB) {\n\tctx := context.Background()\n\tbegin := time.Now()\n\n\t// Create new task t1.\n\tt1 := types.MakeTestTask(begin.Add(TS_RESOLUTION), []string{\"a\", \"b\", \"c\", \"d\"})\n\trequire.NoError(t, db.PutTask(ctx, t1))\n\n\t// Update original.\n\tt1.Status = types.TASK_STATUS_RUNNING\n\trequire.NoError(t, db.PutTask(ctx, t1))\n\n\t// Attempt update.\n\tcallCount := 0\n\tnoTask, err := UpdateTaskWithRetries(ctx, db, t1.Id, func(task *types.Task) error {\n\t\tcallCount++\n\t\t// Sneakily make an update in the background.\n\t\tt1.Commits = append(t1.Commits, fmt.Sprintf(\"z%d\", callCount))\n\t\trequire.NoError(t, db.PutTask(ctx, t1))\n\n\t\ttask.Status = types.TASK_STATUS_SUCCESS\n\t\treturn nil\n\t})\n\trequire.True(t, IsConcurrentUpdate(err))\n\trequire.Equal(t, NUM_RETRIES, callCount)\n\trequire.Nil(t, noTask)\n\n\t// Check task did not change in the DB.\n\tt1Again, err := db.GetTaskById(ctx, t1.Id)\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, t1, t1Again)\n\n\t// Check no extra tasks in the DB.\n\ttasks, err := db.GetTasksFromDateRange(ctx, begin, time.Now().Add(2*TS_RESOLUTION), \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(tasks))\n\trequire.Equal(t, t1.Id, tasks[0].Id)\n}", "func (kube Kubernetes) setHardKillLock(node string) bool {\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tkube.log.PrintErr(err.(error))\n\t\t}\n\t}()\n\n\tnow := time.Now()\n\tleaseDuration := time.Minute * 10\n\n\tfor i := 0; i < 10; i++ {\n\n\t\t// 1. get current value\n\n\t\tnsInstance, err := kube.Kubeclient.CoreV1().Nodes().Get(node, meta.GetOptions{})\n\n\t\tif err != nil {\n\t\t\tkube.log.PrintErr(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrentAnnotations := nsInstance.GetAnnotations()\n\n\t\tif value, exists := currentAnnotations[\"ZombieKiller.HardKill\"]; exists {\n\n\t\t\texistingTimeStamp, err := strconv.ParseInt(value, 10, 64)\n\n\t\t\t// no error can proceed\n\t\t\tif err == nil {\n\t\t\t\t// this is our annotation means we have the lock\n\t\t\t\tif existingTimeStamp == now.Unix() {\n\n\t\t\t\t\tleaseTimeStamp := now.Add(leaseDuration).Unix()\n\t\t\t\t\tcurrentAnnotations[\"ZombieKiller.HardKill\"] = strconv.FormatInt(leaseTimeStamp, 10)\n\t\t\t\t\tnsInstance.SetAnnotations(currentAnnotations)\n\t\t\t\t\t_, err = kube.Kubeclient.CoreV1().Nodes().Update(nsInstance)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tkube.log.PrintErr(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif existingTimeStamp > now.Unix() {\n\t\t\t\t\t// someone else lease is current, wont do anything\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// update now value since it is different retry\n\t\tnow = time.Now()\n\n\t\t// if we are here then annotation is old or garbage or missing so we overwrite it\n\t\tcurrentAnnotations[\"ZombieKiller.HardKill\"] = strconv.FormatInt(now.Unix(), 10)\n\n\t\tnsInstance.SetAnnotations(currentAnnotations)\n\t\t_, err = kube.Kubeclient.CoreV1().Nodes().Update(nsInstance)\n\n\t\tif err != nil {\n\t\t\tkube.log.PrintErr(err)\n\t\t\tcontinue\n\t\t}\n\t}\n\t// fallback since we unable to get the lock\n\treturn false\n}", "func (p *offerPool) AddLostSlave(hostname string) {\n\tp.slaveLock.Lock()\n\tblog.Infof(\"slave %s lost\", hostname)\n\tp.lostSlaves[hostname] = -1\n\tp.slaveLock.Unlock()\n\n\tp.Lock()\n\tp.deleteOfferByHostname(hostname)\n\tblog.Infof(\"after delete lost offers from %s, offers num(%d)\", hostname, p.offerList.Len())\n\tp.Unlock()\n}", "func (s *sharedPullerState) fail(context string, err error) {\n\ts.mut.Lock()\n\tdefer s.mut.Unlock()\n\n\ts.failLocked(context, err)\n}", "func (recBuf *recBuf) clearFailing() {\n\trecBuf.mu.Lock()\n\tdefer recBuf.mu.Unlock()\n\n\trecBuf.failing = false\n\tif len(recBuf.batches) != recBuf.batchDrainIdx {\n\t\trecBuf.sink.maybeDrain()\n\t}\n}", "func (t *Task) Discard() {\n\t// Start a goroutine to listen to the task result channel and discard the result,\n\t// then exit.\n\tt.discardOnce.Do(func() {\n\t\tgo func() {\n\t\t\t<-t.resultChan\n\t\t\tt.completed(nil)\n\t\t}()\n\t})\n}", "func (suite *TaskFailRetryTestSuite) TestTaskFailRetryFailedPatch() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 3,\n\t\t},\n\t}\n\n\tsuite.cachedTask.EXPECT().\n\t\tID().\n\t\tReturn(uint32(0)).\n\t\tAnyTimes()\n\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedJob.EXPECT().\n\t\tID().Return(suite.jobID)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.taskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tPatchTasks(gomock.Any(), gomock.Any(), false).\n\t\tReturn(nil, nil, fmt.Errorf(\"patch error\"))\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.Error(err)\n}", "func (u *Updater) HandleNoResponse(requestID []byte) {\n\tidStr := encodeToString(requestID)\n\tu.RLock()\n\ta, found := u.waiting[idStr]\n\tu.RUnlock()\n\tif !found {\n\t\treturn\n\t}\n\tu.Lock()\n\tdelete(u.waiting, idStr)\n\tu.Unlock()\n\tu.network.RemoveNodeID(a.NodeID, true)\n\tu.queueIdx(a.idx)\n}", "func (hs *HealthStatusInfo) PublishFailed() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.PublishFailures++\n\tMQTTHealth.lastPublishErrorTime = time.Now()\n}", "func (s *Scheduler) taskFitNode(ctx context.Context, t *api.Task, nodeID string) *api.Task {\n\tnodeInfo, err := s.nodeSet.nodeInfo(nodeID)\n\tif err != nil {\n\t\t// node does not exist in set (it may have been deleted)\n\t\treturn nil\n\t}\n\tnewT := *t\n\ts.pipeline.SetTask(t)\n\tif !s.pipeline.Process(&nodeInfo) {\n\t\t// this node cannot accommodate this task\n\t\tnewT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())\n\t\tnewT.Status.Err = s.pipeline.Explain()\n\t\ts.allTasks[t.ID] = &newT\n\n\t\treturn &newT\n\t}\n\n\t// before doing all of the updating logic, get the volume attachments\n\t// for the task on this node. this should always succeed, because we\n\t// should already have filtered nodes based on volume availability, but\n\t// just in case we missed something and it doesn't, we have an error\n\t// case.\n\tattachments, err := s.volumes.chooseTaskVolumes(t, &nodeInfo)\n\tif err != nil {\n\t\tnewT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())\n\t\tnewT.Status.Err = err.Error()\n\t\ts.allTasks[t.ID] = &newT\n\n\t\treturn &newT\n\t}\n\n\tnewT.Volumes = attachments\n\n\tnewT.Status = api.TaskStatus{\n\t\tState: api.TaskStateAssigned,\n\t\tTimestamp: ptypes.MustTimestampProto(time.Now()),\n\t\tMessage: \"scheduler confirmed task can run on preassigned node\",\n\t}\n\ts.allTasks[t.ID] = &newT\n\n\tif nodeInfo.addTask(&newT) {\n\t\ts.nodeSet.updateNode(nodeInfo)\n\t}\n\treturn &newT\n}", "func (md *ManagementNode) SetTaskAndRunDeadTimeout(ctx context.Context,\n\tt *Task) {\n\tmd.scheduledTasksMtx.Lock()\n\n\tmd.scheduledTasks[t.task.Id] = t\n\n\tmd.scheduledTasksMtx.Unlock()\n\n\tt.StartDeadTimeout(ctx,\n\t\tfunc(ctx context.Context) {\n\t\t\tt.task.State = common.TaskStateDead\n\t\t\terr := md.SetToDb(ctx, t.task, EtcdTaskPrefix+t.task.Id)\n\t\t\tif err != nil {\n\t\t\t\tcommon.PrintDebugErr(err)\n\t\t\t}\n\n\t\t\tmd.DelTask(EtcdTaskPrefix + t.task.Id)\n\t\t})\n}", "func (suite *TaskFailRetryTestSuite) TestTaskFailRetryNoTaskRuntime() {\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(nil, fmt.Errorf(\"runtime error\"))\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.Error(err)\n}", "func recordingFaildWarning(packet *gosnmp.SnmpPacket, remote *net.UDPAddr) {\n\tmsg := new(warning.RecordingFailWarning)\n\tmsg.FromSnmpPackage(packet)\n\tseelog.Info(\"recv Warning:\", msg)\n\tdoWarning(msg)\n}", "func (n *Node) HandleNewEventLocked(ev *roothash.Event) {\n\t// In case a fault detector exists, notify it of events.\n\tif n.faultDetector != nil {\n\t\tn.faultDetector.notify(ev)\n\t}\n\n\tdis := ev.ExecutionDiscrepancyDetected\n\tif dis == nil {\n\t\t// Ignore other events.\n\t\treturn\n\t}\n\n\t// Check if the discrepancy occurred in our committee.\n\tepoch := n.commonNode.Group.GetEpochSnapshot()\n\texpectedID := epoch.GetExecutorCommitteeID()\n\tif !expectedID.Equal(&dis.CommitteeID) {\n\t\tn.logger.Debug(\"ignoring discrepancy event for a different committee\",\n\t\t\t\"expected_committee\", expectedID,\n\t\t\t\"committee\", dis.CommitteeID,\n\t\t)\n\t\treturn\n\t}\n\n\tn.logger.Warn(\"execution discrepancy detected\",\n\t\t\"committee_id\", dis.CommitteeID,\n\t)\n\n\tcrash.Here(crashPointDiscrepancyDetectedAfter)\n\n\tdiscrepancyDetectedCount.With(n.getMetricLabels()).Inc()\n\n\tif !n.commonNode.Group.GetEpochSnapshot().IsExecutorBackupWorker() {\n\t\treturn\n\t}\n\n\tvar state StateWaitingForEvent\n\tswitch s := n.state.(type) {\n\tcase StateWaitingForBatch:\n\t\t// Discrepancy detected event received before the batch. We need to\n\t\t// record the received event and keep waiting for the batch.\n\t\ts.pendingEvent = dis\n\t\tn.transitionLocked(s)\n\t\treturn\n\tcase StateWaitingForEvent:\n\t\tstate = s\n\tdefault:\n\t\tn.logger.Warn(\"ignoring received discrepancy event in incorrect state\",\n\t\t\t\"state\", s,\n\t\t)\n\t\treturn\n\t}\n\n\t// Backup worker, start processing a batch.\n\tn.logger.Info(\"backup worker activating and processing batch\")\n\tn.startProcessingBatchLocked(state.batch)\n}", "func (server *Server) NotifyTaskCompleted() {\n\tserver.totalCompleted++\n\tif server.totalCompleted >= server.totalSlaves {\n\t\tlog.Printf(\"All slaves completed their task\")\n\t\tserver.executor.generateSummary()\n\t}\n}", "func (ns *NetworkServer) processDownlinkTask(ctx context.Context) error {\n\tvar setErr bool\n\tvar addErr bool\n\terr := ns.downlinkTasks.Pop(ctx, func(ctx context.Context, devID ttnpb.EndDeviceIdentifiers, t time.Time) error {\n\t\tlogger := log.FromContext(ctx).WithFields(log.Fields(\n\t\t\t\"device_uid\", unique.ID(ctx, devID),\n\t\t\t\"started_at\", timeNow().UTC(),\n\t\t))\n\t\tctx = log.NewContext(ctx, logger)\n\t\tlogger.WithField(\"start_at\", t).Debug(\"Process downlink task\")\n\n\t\tvar queuedApplicationUplinks []*ttnpb.ApplicationUp\n\t\tvar queuedEvents []events.Event\n\t\tvar nextDownlinkAt time.Time\n\t\t_, ctx, err := ns.devices.SetByID(ctx, devID.ApplicationIdentifiers, devID.DeviceID,\n\t\t\t[]string{\n\t\t\t\t\"frequency_plan_id\",\n\t\t\t\t\"last_dev_status_received_at\",\n\t\t\t\t\"lorawan_phy_version\",\n\t\t\t\t\"mac_settings\",\n\t\t\t\t\"mac_state\",\n\t\t\t\t\"multicast\",\n\t\t\t\t\"pending_mac_state\",\n\t\t\t\t\"queued_application_downlinks\",\n\t\t\t\t\"recent_downlinks\",\n\t\t\t\t\"recent_uplinks\",\n\t\t\t\t\"session\",\n\t\t\t},\n\t\t\tfunc(ctx context.Context, dev *ttnpb.EndDevice) (*ttnpb.EndDevice, []string, error) {\n\t\t\t\tif dev == nil {\n\t\t\t\t\tlogger.Warn(\"Device not found\")\n\t\t\t\t\treturn nil, nil, nil\n\t\t\t\t}\n\n\t\t\t\tfp, phy, err := getDeviceBandVersion(dev, ns.FrequencyPlans)\n\t\t\t\tif err != nil {\n\t\t\t\t\tnextDownlinkAt = timeNow().Add(downlinkRetryInterval).UTC()\n\t\t\t\t\tlogger.WithField(\"retry_at\", nextDownlinkAt).WithError(err).Error(\"Failed to get frequency plan of the device, retry downlink slot\")\n\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t}\n\n\t\t\t\tif dev.PendingMACState != nil &&\n\t\t\t\t\tdev.PendingMACState.PendingJoinRequest == nil &&\n\t\t\t\t\tdev.PendingMACState.RxWindowsAvailable &&\n\t\t\t\t\tdev.PendingMACState.QueuedJoinAccept != nil {\n\n\t\t\t\t\tlogger = logger.WithField(\"downlink_type\", \"join-accept\")\n\t\t\t\t\tif len(dev.RecentUplinks) == 0 {\n\t\t\t\t\t\tlogger.Warn(\"No recent uplinks found, skip downlink slot\")\n\t\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t\t}\n\t\t\t\t\tup := lastUplink(dev.RecentUplinks...)\n\t\t\t\t\tswitch up.Payload.MHDR.MType {\n\t\t\t\t\tcase ttnpb.MType_JOIN_REQUEST, ttnpb.MType_REJOIN_REQUEST:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogger.Warn(\"Last uplink is neither join-request, nor rejoin-request, skip downlink slot\")\n\t\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t\t}\n\t\t\t\t\tctx := events.ContextWithCorrelationID(ctx, up.CorrelationIDs...)\n\n\t\t\t\t\trxDelay := ttnpb.RxDelay(phy.JoinAcceptDelay1 / time.Second)\n\n\t\t\t\t\trx1, rx2, paths := downlinkPathsForClassA(rxDelay, up)\n\t\t\t\t\tif len(paths) == 0 {\n\t\t\t\t\t\tlogger.Warn(\"No downlink path available, skip join-accept downlink slot\")\n\t\t\t\t\t\tdev.PendingMACState.RxWindowsAvailable = false\n\t\t\t\t\t\treturn dev, []string{\n\t\t\t\t\t\t\t\"pending_mac_state.rx_windows_available\",\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t}\n\t\t\t\t\tif !rx1 && !rx2 {\n\t\t\t\t\t\tlogger.Warn(\"Rx1 and Rx2 are expired, skip join-accept downlink slot\")\n\t\t\t\t\t\tdev.PendingMACState.RxWindowsAvailable = false\n\t\t\t\t\t\treturn dev, []string{\n\t\t\t\t\t\t\t\"pending_mac_state.rx_windows_available\",\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t}\n\n\t\t\t\t\treq, err := txRequestFromUplink(phy, dev.PendingMACState, rx1, rx2, rxDelay, up)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.WithError(err).Warn(\"Failed to generate Tx request from uplink, skip downlink slot\")\n\t\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t\t}\n\t\t\t\t\treq.Priority = ns.downlinkPriorities.JoinAccept\n\t\t\t\t\treq.FrequencyPlanID = dev.FrequencyPlanID\n\n\t\t\t\t\tdown, err := ns.scheduleDownlinkByPaths(\n\t\t\t\t\t\tlog.NewContext(ctx, loggerWithTxRequestFields(logger, req, rx1, rx2).WithField(\"rx1_delay\", req.Rx1Delay)),\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tdev.PendingMACState.QueuedJoinAccept.Payload,\n\t\t\t\t\t\tpaths...,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif schedErr, ok := err.(downlinkSchedulingError); ok {\n\t\t\t\t\t\t\tlogger = loggerWithDownlinkSchedulingErrorFields(logger, schedErr)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger = logger.WithError(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.Warn(\"All Gateway Servers failed to schedule downlink, skip downlink slot\")\n\t\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t\t}\n\n\t\t\t\t\tdev.PendingSession = &ttnpb.Session{\n\t\t\t\t\t\tDevAddr: dev.PendingMACState.QueuedJoinAccept.Request.DevAddr,\n\t\t\t\t\t\tSessionKeys: dev.PendingMACState.QueuedJoinAccept.Keys,\n\t\t\t\t\t}\n\t\t\t\t\tdev.PendingMACState.PendingJoinRequest = &dev.PendingMACState.QueuedJoinAccept.Request\n\t\t\t\t\tdev.PendingMACState.QueuedJoinAccept = nil\n\t\t\t\t\tdev.PendingMACState.RxWindowsAvailable = false\n\t\t\t\t\tdev.RecentDownlinks = appendRecentDownlink(dev.RecentDownlinks, down.Message, recentDownlinkCount)\n\t\t\t\t\treturn dev, []string{\n\t\t\t\t\t\t\"pending_mac_state.pending_join_request\",\n\t\t\t\t\t\t\"pending_mac_state.queued_join_accept\",\n\t\t\t\t\t\t\"pending_mac_state.rx_windows_available\",\n\t\t\t\t\t\t\"pending_session.dev_addr\",\n\t\t\t\t\t\t\"pending_session.keys\",\n\t\t\t\t\t\t\"recent_downlinks\",\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\n\t\t\t\tlogger = logger.WithField(\"downlink_type\", \"data\")\n\n\t\t\t\tif dev.MACState == nil {\n\t\t\t\t\tlogger.Warn(\"Unknown MAC state, skip downlink slot\")\n\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t}\n\n\t\t\t\tlogger = logger.WithField(\"device_class\", dev.MACState.DeviceClass)\n\t\t\t\tctx = log.NewContext(ctx, logger)\n\n\t\t\t\tif !dev.MACState.RxWindowsAvailable {\n\t\t\t\t\tlogger.Debug(\"Rx windows not available, skip class A downlink slot\")\n\t\t\t\t\tif dev.MACState.DeviceClass == ttnpb.CLASS_A {\n\t\t\t\t\t\treturn dev, nil, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar maxUpLength uint16 = math.MaxUint16\n\t\t\t\tif dev.MACState.LoRaWANVersion == ttnpb.MAC_V1_1 {\n\t\t\t\t\tmaxUpLength = maximumUplinkLength(fp, phy, dev.MACState.RecentUplinks...)\n\t\t\t\t}\n\n\t\t\t\tvar sets []string\n\t\t\t\tif dev.MACState.RxWindowsAvailable {\n\t\t\t\t\ta := ns.attemptClassADataDownlink(ctx, dev, phy, fp, maxUpLength)\n\t\t\t\t\tsets = append(sets, a.SetPaths...)\n\t\t\t\t\tqueuedEvents = append(queuedEvents, a.QueuedEvents...)\n\t\t\t\t\tqueuedApplicationUplinks = a.AppendApplicationUplinks(queuedApplicationUplinks...)\n\t\t\t\t\tif a.Scheduled {\n\t\t\t\t\t\tt, hasNext := nextDataDownlinkAt(ctx, dev, phy, ns.defaultMACSettings)\n\t\t\t\t\t\tif hasNext {\n\t\t\t\t\t\t\tearliestAt := a.DownAt.Add(dev.MACState.CurrentParameters.Rx1Delay.Duration())\n\t\t\t\t\t\t\tif t.Before(earliestAt) {\n\t\t\t\t\t\t\t\tnextDownlinkAt = earliestAt\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnextDownlinkAt = t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tswitch dev.MACState.DeviceClass {\n\t\t\t\tcase ttnpb.CLASS_A:\n\t\t\t\t\treturn dev, sets, nil\n\n\t\t\t\tcase ttnpb.CLASS_B:\n\t\t\t\t\t// TODO: Support Class B (https://github.com/TheThingsNetwork/lorawan-stack/issues/19).\n\t\t\t\t\tlogger.Warn(\"Class B downlinks are not supported, skip class B/C downlink slot\")\n\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t}\n\n\t\t\t\t// Class B/C data downlink\n\t\t\t\treq := &ttnpb.TxRequest{\n\t\t\t\t\tClass: dev.MACState.DeviceClass,\n\t\t\t\t\tRx2DataRateIndex: dev.MACState.CurrentParameters.Rx2DataRateIndex,\n\t\t\t\t\tRx2Frequency: dev.MACState.CurrentParameters.Rx2Frequency,\n\t\t\t\t\tFrequencyPlanID: dev.FrequencyPlanID,\n\t\t\t\t}\n\n\t\t\t\tgenDown, genState, err := ns.generateDownlink(ctx, dev, phy, dev.MACState.DeviceClass, timeNow().Add(nsScheduleWindow),\n\t\t\t\t\tphy.DataRates[req.Rx2DataRateIndex].DefaultMaxSize.PayloadSize(fp.DwellTime.GetDownlinks()),\n\t\t\t\t\tmaxUpLength,\n\t\t\t\t)\n\t\t\t\tif genState.NeedsDownlinkQueueUpdate {\n\t\t\t\t\tsets = []string{\n\t\t\t\t\t\t\"queued_application_downlinks\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tswitch {\n\t\t\t\t\tcase errors.Resemble(err, errNoDownlink):\n\t\t\t\t\t\tlogger.Debug(\"No class B/C downlink to send, skip class B/C downlink slot\")\n\n\t\t\t\t\tcase errors.Resemble(err, errConfirmedDownlinkTooSoon):\n\t\t\t\t\t\tnextDownlinkAt = dev.MACState.LastConfirmedDownlinkAt.Add(deviceClassCTimeout(dev, ns.defaultMACSettings))\n\t\t\t\t\t\tlogger.WithField(\"retry_at\", nextDownlinkAt).Info(\"Confirmed downlink scheduled too soon, retry\")\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogger.WithError(err).Warn(\"Failed to generate class B/C downlink, skip class B/C downlink slot\")\n\t\t\t\t\t}\n\t\t\t\t\tqueuedApplicationUplinks = genState.appendApplicationUplinks(queuedApplicationUplinks, false)\n\t\t\t\t\tif genState.ApplicationDownlink != nil && ttnpb.HasAnyField(sets, \"queued_application_downlinks\") {\n\t\t\t\t\t\tdev.QueuedApplicationDownlinks = append([]*ttnpb.ApplicationDownlink{genState.ApplicationDownlink}, dev.QueuedApplicationDownlinks...)\n\t\t\t\t\t}\n\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t}\n\n\t\t\t\tif genState.ApplicationDownlink != nil {\n\t\t\t\t\tctx = events.ContextWithCorrelationID(ctx, genState.ApplicationDownlink.CorrelationIDs...)\n\t\t\t\t}\n\t\t\t\treq.Priority = genDown.Priority\n\n\t\t\t\tvar paths []downlinkPath\n\t\t\t\tif fixedPaths := genState.ApplicationDownlink.GetClassBC().GetGateways(); len(fixedPaths) > 0 {\n\t\t\t\t\tpaths = make([]downlinkPath, 0, len(fixedPaths))\n\t\t\t\t\tfor i := range fixedPaths {\n\t\t\t\t\t\tpaths = append(paths, downlinkPath{\n\t\t\t\t\t\t\tGatewayIdentifiers: fixedPaths[i].GatewayIdentifiers,\n\t\t\t\t\t\t\tDownlinkPath: &ttnpb.DownlinkPath{\n\t\t\t\t\t\t\t\tPath: &ttnpb.DownlinkPath_Fixed{\n\t\t\t\t\t\t\t\t\tFixed: &fixedPaths[i],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpaths = downlinkPathsFromRecentUplinks(dev.MACState.RecentUplinks...)\n\t\t\t\t\tif len(paths) == 0 {\n\t\t\t\t\t\tlogger.Warn(\"No downlink path available, skip class B/C downlink slot\")\n\t\t\t\t\t\tqueuedApplicationUplinks = genState.appendApplicationUplinks(queuedApplicationUplinks, false)\n\t\t\t\t\t\tif genState.ApplicationDownlink != nil && ttnpb.HasAnyField(sets, \"queued_application_downlinks\") {\n\t\t\t\t\t\t\tdev.QueuedApplicationDownlinks = append([]*ttnpb.ApplicationDownlink{genState.ApplicationDownlink}, dev.QueuedApplicationDownlinks...)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif absTime := genState.ApplicationDownlink.GetClassBC().GetAbsoluteTime(); absTime != nil {\n\t\t\t\t\tif absTime.After(timeNow().Add(gsScheduleWindow + nsScheduleWindow)) {\n\t\t\t\t\t\tnextDownlinkAt = absTime.Add(-gsScheduleWindow)\n\t\t\t\t\t\tlogger.WithField(\"retry_at\", nextDownlinkAt).Info(\"Downlink scheduled too soon, retry attempt\")\n\t\t\t\t\t\tqueuedApplicationUplinks = genState.appendApplicationUplinks(queuedApplicationUplinks, false)\n\t\t\t\t\t\tif genState.ApplicationDownlink != nil && ttnpb.HasAnyField(sets, \"queued_application_downlinks\") {\n\t\t\t\t\t\t\tdev.QueuedApplicationDownlinks = append([]*ttnpb.ApplicationDownlink{genState.ApplicationDownlink}, dev.QueuedApplicationDownlinks...)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t\t}\n\t\t\t\t\treq.AbsoluteTime = absTime\n\t\t\t\t}\n\n\t\t\t\tdown, err := ns.scheduleDownlinkByPaths(\n\t\t\t\t\tlog.NewContext(ctx, loggerWithTxRequestFields(logger, req, false, true)),\n\t\t\t\t\treq,\n\t\t\t\t\tgenDown.Payload,\n\t\t\t\t\tpaths...,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tnextDownlinkAt = timeNow().Add(downlinkRetryInterval).UTC()\n\t\t\t\t\tschedErr, ok := err.(downlinkSchedulingError)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tlogger = loggerWithDownlinkSchedulingErrorFields(logger, schedErr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger = logger.WithError(err)\n\t\t\t\t\t}\n\t\t\t\t\tqueuedApplicationUplinks = genState.appendApplicationUplinks(queuedApplicationUplinks, false)\n\t\t\t\t\tif ok && genState.ApplicationDownlink != nil {\n\t\t\t\t\t\tpathErrs, ok := schedErr.pathErrors()\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tif genState.ApplicationDownlink.GetClassBC().GetAbsoluteTime() != nil &&\n\t\t\t\t\t\t\t\tallErrors(nonRetryableAbsoluteTimeGatewayError, pathErrs...) {\n\t\t\t\t\t\t\t\tlogger.WithField(\"retry_at\", nextDownlinkAt).Warn(\"Absolute time invalid, fail downlink and retry attempt\")\n\t\t\t\t\t\t\t\tqueuedApplicationUplinks = append(queuedApplicationUplinks, &ttnpb.ApplicationUp{\n\t\t\t\t\t\t\t\t\tEndDeviceIdentifiers: dev.EndDeviceIdentifiers,\n\t\t\t\t\t\t\t\t\tCorrelationIDs: events.CorrelationIDsFromContext(ctx),\n\t\t\t\t\t\t\t\t\tUp: &ttnpb.ApplicationUp_DownlinkFailed{\n\t\t\t\t\t\t\t\t\t\tDownlinkFailed: &ttnpb.ApplicationDownlinkFailed{\n\t\t\t\t\t\t\t\t\t\t\tApplicationDownlink: *genState.ApplicationDownlink,\n\t\t\t\t\t\t\t\t\t\t\tError: *ttnpb.ErrorDetailsToProto(errInvalidAbsoluteTime),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tif !genState.NeedsDownlinkQueueUpdate {\n\t\t\t\t\t\t\t\t\tsets = append(sets, \"queued_application_downlinks\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif len(genState.ApplicationDownlink.GetClassBC().GetGateways()) > 0 &&\n\t\t\t\t\t\t\t\tallErrors(nonRetryableFixedPathGatewayError, pathErrs...) {\n\t\t\t\t\t\t\t\tlogger.WithField(\"retry_at\", nextDownlinkAt).Warn(\"Fixed paths invalid, fail application downlink and retry attempt\")\n\t\t\t\t\t\t\t\tqueuedApplicationUplinks = append(queuedApplicationUplinks, &ttnpb.ApplicationUp{\n\t\t\t\t\t\t\t\t\tEndDeviceIdentifiers: dev.EndDeviceIdentifiers,\n\t\t\t\t\t\t\t\t\tCorrelationIDs: events.CorrelationIDsFromContext(ctx),\n\t\t\t\t\t\t\t\t\tUp: &ttnpb.ApplicationUp_DownlinkFailed{\n\t\t\t\t\t\t\t\t\t\tDownlinkFailed: &ttnpb.ApplicationDownlinkFailed{\n\t\t\t\t\t\t\t\t\t\t\tApplicationDownlink: *genState.ApplicationDownlink,\n\t\t\t\t\t\t\t\t\t\t\tError: *ttnpb.ErrorDetailsToProto(errInvalidFixedPaths),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tif !genState.NeedsDownlinkQueueUpdate {\n\t\t\t\t\t\t\t\t\tsets = append(sets, \"queued_application_downlinks\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn dev, sets, nil\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\tlogger.Warn(\"All Gateway Servers failed to schedule downlink, skip class B/C downlink slot\")\n\t\t\t\t\tif genState.NeedsDownlinkQueueUpdate {\n\t\t\t\t\t\tdev.QueuedApplicationDownlinks = append([]*ttnpb.ApplicationDownlink{genState.ApplicationDownlink}, dev.QueuedApplicationDownlinks...)\n\t\t\t\t\t}\n\t\t\t\t\treturn dev, sets, nil\n\t\t\t\t}\n\n\t\t\t\trecordDataDownlink(dev, genDown, genState, down, ns.defaultMACSettings)\n\t\t\t\tqueuedEvents = append(queuedEvents, genState.Events...)\n\t\t\t\tqueuedApplicationUplinks = genState.appendApplicationUplinks(queuedApplicationUplinks, true)\n\t\t\t\tif genState.ApplicationDownlink != nil {\n\t\t\t\t\tsets = append(sets, \"queued_application_downlinks\")\n\t\t\t\t}\n\t\t\t\tt, hasNext := nextDataDownlinkAt(ctx, dev, phy, ns.defaultMACSettings)\n\t\t\t\tif hasNext {\n\t\t\t\t\tearliestAt := down.TransmitAt.Add(dev.MACState.CurrentParameters.Rx1Delay.Duration())\n\t\t\t\t\tif t.Before(earliestAt) {\n\t\t\t\t\t\tnextDownlinkAt = earliestAt\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnextDownlinkAt = t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn dev, append(sets,\n\t\t\t\t\t\"mac_state.last_confirmed_downlink_at\",\n\t\t\t\t\t\"mac_state.pending_application_downlink\",\n\t\t\t\t\t\"mac_state.pending_requests\",\n\t\t\t\t\t\"mac_state.queued_responses\",\n\t\t\t\t\t\"mac_state.recent_downlinks\",\n\t\t\t\t\t\"mac_state.rx_windows_available\",\n\t\t\t\t\t\"recent_downlinks\",\n\t\t\t\t\t\"session\",\n\t\t\t\t), nil\n\t\t\t},\n\t\t)\n\t\tif len(queuedApplicationUplinks) > 0 {\n\t\t\tif err := ns.applicationUplinks.Add(ctx, queuedApplicationUplinks...); err != nil {\n\t\t\t\tlogger.WithError(err).Warn(\"Failed to queue application uplinks for sending to Application Server\")\n\t\t\t}\n\t\t}\n\t\tif len(queuedEvents) > 0 {\n\t\t\tfor _, ev := range queuedEvents {\n\t\t\t\tevents.Publish(ev)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tsetErr = true\n\t\t\tlogger.WithError(err).Error(\"Failed to update device in registry\")\n\t\t\treturn err\n\t\t}\n\t\tif !nextDownlinkAt.IsZero() {\n\t\t\tnextDownlinkAt = nextDownlinkAt.Add(-nsScheduleWindow)\n\t\t\tlogger.WithField(\"start_at\", nextDownlinkAt).Debug(\"Add downlink task after downlink attempt\")\n\t\t\tif err := ns.downlinkTasks.Add(ctx, devID, nextDownlinkAt, true); err != nil {\n\t\t\t\taddErr = true\n\t\t\t\tlogger.WithError(err).Error(\"Failed to add downlink task after downlink attempt\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil && !setErr && !addErr {\n\t\tlog.FromContext(ctx).WithError(err).Error(\"Failed to pop device from downlink schedule\")\n\t}\n\treturn err\n}", "func unregisteredNodeHealth(t *testing.T, proxyURL string, si *meta.Snode) {\n\terr := api.Health(tools.BaseAPIParams(si.PubNet.URL))\n\ttassert.CheckError(t, err)\n\n\tsmapOrig := tools.GetClusterMap(t, proxyURL)\n\targs := &apc.ActValRmNode{DaemonID: si.ID(), SkipRebalance: true}\n\tbaseParams := tools.BaseAPIParams(proxyURL)\n\t_, err = api.StartMaintenance(baseParams, args)\n\ttassert.CheckFatal(t, err)\n\ttargetCount := smapOrig.CountActiveTs()\n\tproxyCount := smapOrig.CountActivePs()\n\tif si.IsProxy() {\n\t\tproxyCount--\n\t} else {\n\t\ttargetCount--\n\t}\n\t_, err = tools.WaitForClusterState(proxyURL, \"decommission node\", smapOrig.Version, proxyCount, targetCount)\n\ttassert.CheckFatal(t, err)\n\tdefer func() {\n\t\tval := &apc.ActValRmNode{DaemonID: si.ID()}\n\t\trebID, err := api.StopMaintenance(baseParams, val)\n\t\ttassert.CheckFatal(t, err)\n\t\t_, err = tools.WaitForClusterState(proxyURL, \"join node\", smapOrig.Version, smapOrig.CountActivePs(),\n\t\t\tsmapOrig.CountActiveTs())\n\t\ttassert.CheckFatal(t, err)\n\t\ttools.WaitForRebalanceByID(t, baseParams, rebID)\n\t}()\n\n\terr = api.Health(tools.BaseAPIParams(si.PubNet.URL))\n\ttassert.CheckError(t, err)\n}", "func (sd *ScanDiapasons) NotifyDpnsTask(ctx context.Context) ([]byte, error) {\n\trequest, err := http.NewRequest(\"POST\", sd.client.Server+\"/api/v1.0/ScanDiapasons.NotifyDpnsTask\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw, err := sd.client.Do(ctx, request, nil)\n\treturn raw, err\n}", "func (s *Session) RetryTask(t util.Task) error {\n\ttask := util.Task{\n\t\tName: t.Name,\n\t\tOriginalTaskID: t.OriginalTaskID,\n\t\tPayload: t.Payload,\n\t\tPriority: t.Priority,\n\t\tStatus: util.StatusRetry,\n\t}\n\n\t// updating original task id counter\n\ts.taskRepo.UpdateRetryCount(t.OriginalTaskID, -1)\n\tif err := s.SendTask(task); err != nil {\n\t\ts.lgr.Error(\"failed to retry\", err, util.Object{Key: \"TaskID\", Val: task.TaskID}, util.Object{Key: \"OriginalTaskID\", Val: task.OriginalTaskID})\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *statusUpdate) persistHealthyField(\n\tstate pb_task.TaskState,\n\treason string,\n\thealthy bool,\n\tnewRuntime *pb_task.RuntimeInfo) {\n\n\tswitch {\n\tcase util.IsPelotonStateTerminal(state):\n\t\t// Set healthy to INVALID for all terminal state\n\t\tnewRuntime.Healthy = pb_task.HealthState_INVALID\n\tcase state == pb_task.TaskState_RUNNING:\n\t\t// Only record the health check result when\n\t\t// the reason for the event is TASK_HEALTH_CHECK_STATUS_UPDATED\n\t\tif reason == mesos.TaskStatus_REASON_TASK_HEALTH_CHECK_STATUS_UPDATED.String() {\n\t\t\tnewRuntime.Reason = reason\n\t\t\tif healthy {\n\t\t\t\tnewRuntime.Healthy = pb_task.HealthState_HEALTHY\n\t\t\t\tp.metrics.TasksHealthyTotal.Inc(1)\n\t\t\t} else {\n\t\t\t\tnewRuntime.Healthy = pb_task.HealthState_UNHEALTHY\n\t\t\t\tp.metrics.TasksUnHealthyTotal.Inc(1)\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *AutoRollNotifier) SendNewFailure(ctx context.Context, id, url string) {\n\ta.send(ctx, &tmplVars{\n\t\tIssueID: id,\n\t\tIssueURL: url,\n\t}, subjectTmplNewFailure, bodyTmplNewFailure, notifier.SEVERITY_WARNING, MSG_TYPE_NEW_FAILURE, nil)\n}", "func (status *DownloaderStatus) HandleDownloadFail(errStr string) {\n\tstatus.SetErrorInfo(errStr)\n\tstatus.ClearPendingStatus()\n}", "func (m *Master) AssignTask(args *Args, reply *Reply) error {\n\treply.Valid = false\n\treply.Done = false\n\n\tm.Mutex.Lock()\n\tdefer m.Mutex.Unlock()\n\tif m.Phase == Reduce && len(m.Undone) == 0 && len(m.Doing) == 0 {\n\t\treply.Done = true\n//\t\tlog.Printf(\"all task finished\")\n\t\treturn nil\n\t}\n\n\tif len(m.Undone) == 0 {\n//\t\tlog.Printf(\"no task to assign undone:%d\", len(m.Undone))\n\t\treturn nil\n\t}\n\n\treply.Valid = true\n\treply.Mapnr = m.Mapnr\n\treply.Reducenr = m.Reducenr\n\n\tvar idx int\n\tvar task Task\n\tfor idx, task = range m.Undone {\n\t\ttask.Starttime = time.Now().Unix()\n\t\treply.Task = task\n\t\tbreak\n\t}\n\n\tdelete(m.Undone, idx)\n\tm.Doing[idx] = task\n\n//\tlog.Printf(\"AssignTask undone %d doing %d type %d idx %d inputfile %s\",\n//\t\tlen(m.Undone), len(m.Doing), task.Type, task.Idx, task.Inputfile)\n\n\treturn nil\n}", "func (q *Q) Fail() {\n\tif q.Status != PROGRESS {\n\t\treturn\n\t}\n\tq.Status = FAILURE\n}" ]
[ "0.65679485", "0.65535086", "0.62841725", "0.6088731", "0.59463507", "0.58184403", "0.5762325", "0.5706654", "0.56167144", "0.55078316", "0.5208127", "0.51102793", "0.51076466", "0.50827014", "0.5040597", "0.5035461", "0.50189453", "0.5009758", "0.4995262", "0.49910837", "0.49465847", "0.49212784", "0.49165308", "0.4912476", "0.49053463", "0.48390847", "0.48326054", "0.48322666", "0.4757295", "0.47468984", "0.47416425", "0.47289994", "0.47209623", "0.46940127", "0.46872061", "0.46766928", "0.46647525", "0.46627682", "0.4650723", "0.4644357", "0.46224913", "0.4605231", "0.45823485", "0.45810103", "0.4553539", "0.45517504", "0.45182434", "0.45065698", "0.4498489", "0.44965106", "0.4495556", "0.44931522", "0.44845814", "0.44819763", "0.4479778", "0.44693688", "0.44576508", "0.44411576", "0.44267017", "0.44198468", "0.44177872", "0.44165516", "0.44163075", "0.4398597", "0.4398147", "0.43981382", "0.439587", "0.43937442", "0.43918222", "0.43873173", "0.43809626", "0.43778297", "0.43778297", "0.43719497", "0.4365552", "0.43580502", "0.43561015", "0.43550646", "0.43534938", "0.4346352", "0.43433446", "0.43409494", "0.43373486", "0.43330413", "0.43284175", "0.4326437", "0.43069652", "0.43030083", "0.42977923", "0.42972353", "0.42961177", "0.4295234", "0.42912793", "0.42881837", "0.42821157", "0.4274575", "0.4253698", "0.42512685", "0.4249835" ]
0.7423561
1
deletes the pod and task associated with the task identified by tid and sends a task status update to mesos. also attempts to reset the suicide watch. Assumes that the caller is locking around pod and task state.
func (k *KubernetesExecutor) removePodTask(driver bindings.ExecutorDriver, tid, reason string, state mesos.TaskState) { task, ok := k.tasks[tid] if !ok { log.V(1).Infof("Failed to remove task, unknown task %v\n", tid) return } delete(k.tasks, tid) k.resetSuicideWatch(driver) pid := task.podName pod, found := k.pods[pid] if !found { log.Warningf("Cannot remove unknown pod %v for task %v", pid, tid) } else { log.V(2).Infof("deleting pod %v for task %v", pid, tid) delete(k.pods, pid) // tell the kubelet to remove the pod update := kubelet.PodUpdate{ Op: kubelet.REMOVE, Pods: []*api.Pod{pod}, } k.updateChan <- update } // TODO(jdef): ensure that the update propagates, perhaps return a signal chan? k.sendStatus(driver, newStatus(mutil.NewTaskID(tid), state, reason)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesExecutor) removePodTask(driver bindings.ExecutorDriver, tid, reason string, state mesos.TaskState) {\n\ttask, ok := k.tasks[tid]\n\tif !ok {\n\t\tlog.V(1).Infof(\"Failed to remove task, unknown task %v\\n\", tid)\n\t\treturn\n\t}\n\tdelete(k.tasks, tid)\n\n\tpid := task.podName\n\tif _, found := k.pods[pid]; !found {\n\t\tlog.Warningf(\"Cannot remove unknown pod %v for task %v\", pid, tid)\n\t} else {\n\t\tlog.V(2).Infof(\"deleting pod %v for task %v\", pid, tid)\n\t\tdelete(k.pods, pid)\n\n\t\t// Send the pod updates to the channel.\n\t\tupdate := kubelet.PodUpdate{Op: kubelet.SET}\n\t\tfor _, p := range k.pods {\n\t\t\tupdate.Pods = append(update.Pods, *p)\n\t\t}\n\t\tk.updateChan <- update\n\t}\n\t// TODO(jdef): ensure that the update propagates, perhaps return a signal chan?\n\tk.sendStatus(driver, newStatus(mutil.NewTaskID(tid), state, reason))\n}", "func CleanTask() {\n\tfor taskID, t := range kv.DefaultClient.GetStorage().Tasks {\n\t\tflag := true\n\t\tfor nid := range kv.DefaultClient.GetStorage().Nodes {\n\t\t\tif t.NodeID == nid {\n\t\t\t\tflag = false\n\t\t\t}\n\t\t}\n\t\tif flag {\n\t\t\tif t.Timer {\n\t\t\t\tlog.Info(\"clean timer:\", taskID)\n\t\t\t\tormTimer := new(orm.Timer)\n\t\t\t\tormTimer.ID = taskID\n\t\t\t\tormTimer.Status = false\n\t\t\t\terr := orm.UpdateTimerStatus(ormTimer)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Info(\"clean task:\", taskID)\n\t\t\t\tormTask := new(orm.Task)\n\t\t\t\tormTask.ID = taskID\n\t\t\t\tormTask.Status = \"error\"\n\t\t\t\terr := orm.UpdateTask(ormTask)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkv.DefaultClient.DeleteTask(taskID)\n\t\t}\n\t}\n}", "func undoTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": false}}\n\t_, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Task defined incomplete: \", id)\n}", "func resetTask(ctx context.Context, settings *evergreen.Settings, taskId, username string, failedOnly bool) error {\n\tt, err := task.FindOneId(taskId)\n\tif err != nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tMessage: errors.Wrapf(err, \"finding task '%s'\", t).Error(),\n\t\t}\n\t}\n\tif t == nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"task '%s' not found\", taskId),\n\t\t}\n\t}\n\treturn errors.Wrapf(serviceModel.ResetTaskOrDisplayTask(ctx, settings, t, username, evergreen.RESTV2Package, failedOnly, nil), \"resetting task '%s'\", taskId)\n}", "func (k *KubernetesExecutor) killPodForTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_KILLED)\n}", "func undoTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": false}}\n\tresult, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"modified count: \", result.ModifiedCount)\n}", "func undoTask(task string) {\n\tlog.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": false}}\n\tresult, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"modified count: \", result.ModifiedCount)\n}", "func (ts *taskState) watcher(ctx context.Context) {\n\ttask := ctx.Value(\"task\").(storage.Task)\n\tchId := task.Canceled()\n\tprotCtl := ctx.Value(\"protocol.ctl\").(controller.Controller)\n\n\tts.mu.Lock()\n\n\tid, ok := ts.ids[chId]\n\n\tts.mu.Unlock()\n\n\tif !ok {\n\t\treturn\n\t}\n\n\tdefer ts.remove(task)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn\n\tcase <-protCtl.Finished():\n\t\treturn\n\tcase <-task.Canceled():\n\t\tprotCtl.MessageSend(&mes.SC_TaskCancel_ms{\n\t\t\tStateId: id,\n\t\t\tReason: \"state changed\",\n\t\t})\n\t}\n}", "func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST)\n}", "func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) {\n\tk.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST)\n}", "func (e *bcsExecutor) updateTaskStatus(taskId string, status types.TaskStatus, msg string) {\n\tvar state mesos.TaskState\n\n\tswitch status {\n\tcase types.TaskStatusStarting:\n\t\tstate = mesos.TaskState_TASK_STARTING\n\n\tcase types.TaskStatusRunning:\n\t\tstate = mesos.TaskState_TASK_RUNNING\n\n\tcase types.TaskStatusKilling:\n\t\tstate = mesos.TaskState_TASK_KILLING\n\n\tcase types.TaskStatusFinish:\n\t\tstate = mesos.TaskState_TASK_FINISHED\n\n\tcase types.TaskStatusFailed:\n\t\tstate = mesos.TaskState_TASK_FAILED\n\n\tcase types.TaskStatusError:\n\t\tstate = mesos.TaskState_TASK_ERROR\n\n\tdefault:\n\t\tblog.Errorf(\"task %s status %s is invalid\", taskId, string(status))\n\t\treturn\n\t}\n\n\tupdate := &mesos.TaskStatus{\n\t\tTaskId: &mesos.TaskID{Value: proto.String(taskId)},\n\t\tState: state.Enum(),\n\t\tMessage: proto.String(msg),\n\t\tSource: mesos.TaskStatus_SOURCE_EXECUTOR.Enum(),\n\t}\n\n\tID := uuid.NewUUID()\n\tnow := float64(time.Now().Unix())\n\tupdate.Timestamp = proto.Float64(now)\n\tupdate.Uuid = ID\n\n\tFunc, ok := e.callbackFuncs[types.CallbackFuncUpdateTask]\n\tif !ok {\n\t\tblog.Errorf(\"CallbackFuncUpdateTask not found\")\n\t\treturn\n\t}\n\n\tblog.Infof(\"update task %s status %s uuid %s msg %s\", taskId, state.String(), ID.String(), msg)\n\n\te.updatesLocks.Lock()\n\te.ackUpdates[taskId] = update\n\te.updatesLocks.Unlock()\n\n\tupdateFunc := Func.(types.UpdateTaskFunc)\n\terr := updateFunc(update)\n\tif err != nil {\n\t\tblog.Errorf(\"update task %s status %s msg %s error %s\", taskId, state.String(), msg, err.Error())\n\t}\n\treturn\n}", "func (_m *MutableNodeStatus) ClearTaskStatus() {\n\t_m.Called()\n}", "func (i *DeleteOrUpdateInvTask) StatusUpdate(_ *taskrunner.TaskContext, _ object.ObjMetadata) {}", "func cleanupTask(ctx context.Context, t *testing.T, c cocoa.ECSClient, runOut *ecs.RunTaskOutput) {\n\tif runOut != nil && len(runOut.Tasks) > 0 && runOut.Tasks[0].TaskArn != nil {\n\t\tout, err := c.StopTask(ctx, &ecs.StopTaskInput{\n\t\t\tCluster: aws.String(testutil.ECSClusterName()),\n\t\t\tTask: aws.String(*runOut.Tasks[0].TaskArn),\n\t\t})\n\t\trequire.NoError(t, err)\n\t\trequire.NotZero(t, out)\n\t}\n}", "func UpdateOneTimeTaskStatus(otid int64, status int) error {\n\tvar dummy string\n\tif err := db.QueryRow(\"UPDATE onetime_tasks SET status=$1 WHERE id=$2 \"+\n\t\t\"RETURNING id\", status, otid).Scan(&dummy); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *PodTask) ClearTaskInfo() {\n\tt.OfferIds = nil\n\tt.TaskInfo.TaskId = nil\n\tt.TaskInfo.SlaveId = nil\n\tt.TaskInfo.Resources = nil\n\tt.TaskInfo.Data = nil\n}", "func UpdateTaskStatus(tid int64, new_status int64) {\n\tvar dummy string\n\n\tif new_status == Running {\n\t\tdb.QueryRow(\"UPDATE tasks SET status=$1, start_time=now() WHERE id=$2\",\n\t\t\tnew_status, tid).Scan(&dummy)\n\t} else if new_status == Canceled {\n\t\tdb.QueryRow(\"UPDATE tasks SET status=$1, end_time=now() WHERE id=$2\",\n\t\t\tnew_status, tid).Scan(&dummy)\n\t} else {\n\t\tdb.QueryRow(\"UPDATE tasks SET status=$1 WHERE id=$2\", new_status, tid).\n\t\t\tScan(&dummy)\n\t}\n}", "func (s *eremeticScheduler) StatusUpdate(driver sched.SchedulerDriver, status *mesos.TaskStatus) {\n\tid := status.TaskId.GetValue()\n\n\tlog.Debugf(\"Received task status [%s] for task [%s]\", status.State.String(), id)\n\n\ttask, err := database.ReadTask(id)\n\tif err != nil {\n\t\tlog.Debugf(\"Error reading task from database: %s\", err)\n\t}\n\n\tif task.ID == \"\" {\n\t\ttask = types.EremeticTask{\n\t\t\tID: id,\n\t\t\tSlaveId: status.SlaveId.GetValue(),\n\t\t}\n\t}\n\n\tif !task.IsRunning() && *status.State == mesos.TaskState_TASK_RUNNING {\n\t\tTasksRunning.Inc()\n\t}\n\n\tif types.IsTerminal(status.State) {\n\t\tTasksTerminated.With(prometheus.Labels{\"status\": status.State.String()}).Inc()\n\t\tif task.WasRunning() {\n\t\t\tTasksRunning.Dec()\n\t\t}\n\t}\n\n\ttask.UpdateStatus(types.Status{\n\t\tStatus: status.State.String(),\n\t\tTime: time.Now().Unix(),\n\t})\n\n\tif *status.State == mesos.TaskState_TASK_FAILED && !task.WasRunning() {\n\t\tif task.Retry >= maxRetries {\n\t\t\tlog.Warnf(\"giving up on %s after %d retry attempts\", id, task.Retry)\n\t\t} else {\n\t\t\tlog.Infof(\"task %s was never running. re-scheduling\", id)\n\t\t\ttask.UpdateStatus(types.Status{\n\t\t\t\tStatus: mesos.TaskState_TASK_STAGING.String(),\n\t\t\t\tTime: time.Now().Unix(),\n\t\t\t})\n\t\t\ttask.Retry++\n\t\t\tgo func() {\n\t\t\t\tQueueSize.Inc()\n\t\t\t\ts.tasks <- id\n\t\t\t}()\n\t\t}\n\t}\n\n\tif types.IsTerminal(status.State) {\n\t\thandler.NotifyCallback(&task)\n\t}\n\n\tdatabase.PutTask(&task)\n}", "func deleteTask(msg BackendPayload) {\n\tincomingTaskID := msg.ID // attempt to retreive the id of the task in the case its an update POST\n\t// _, exists := TodoList[incomingTaskID]\n\t// if exists { // only attempt to delete if it exists\n\t// \tdelete(TodoList, incomingTaskID)\n\t// }\n\tTodoList.Delete(incomingTaskID)\n\treturn\n}", "func taskComplete(task string){\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": true}}\n\t_, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(\"Error update task\", err)\n\t}\n\n\tfmt.Println(\"Task defined complete: \", id)\n}", "func (p k8sPodResources) Kill(ctx *actor.System, _ logger.Context) {\n\tctx.Tell(p.podsActor, KillTaskPod{\n\t\tPodID: p.containerID,\n\t})\n}", "func (w *WaitTask) StatusUpdate(taskContext *TaskContext, id object.ObjMetadata) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\tif klog.V(5).Enabled() {\n\t\tstatus := taskContext.ResourceCache().Get(id).Status\n\t\tklog.Infof(\"status update (object: %q, status: %q)\", id, status)\n\t}\n\n\tswitch {\n\tcase w.pending.Contains(id):\n\t\tswitch {\n\t\tcase w.changedUID(taskContext, id):\n\t\t\t// replaced\n\t\t\tw.handleChangedUID(taskContext, id)\n\t\t\tw.pending = w.pending.Remove(id)\n\t\tcase w.reconciledByID(taskContext, id):\n\t\t\t// reconciled - remove from pending & send event\n\t\t\terr := taskContext.InventoryManager().SetSuccessfulReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as successful reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.pending = w.pending.Remove(id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSuccessful)\n\t\tcase w.failedByID(taskContext, id):\n\t\t\t// failed - remove from pending & send event\n\t\t\terr := taskContext.InventoryManager().SetFailedReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as failed reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.pending = w.pending.Remove(id)\n\t\t\tw.failed = append(w.failed, id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileFailed)\n\t\t\t// default - still pending\n\t\t}\n\tcase !w.Ids.Contains(id):\n\t\t// not in wait group - ignore\n\t\treturn\n\tcase w.skipped(taskContext, id):\n\t\t// skipped - ignore\n\t\treturn\n\tcase w.failed.Contains(id):\n\t\t// If a failed resource becomes current before other\n\t\t// resources have completed/timed out, we consider it\n\t\t// current.\n\t\tif w.reconciledByID(taskContext, id) {\n\t\t\t// reconciled - remove from pending & send event\n\t\t\terr := taskContext.InventoryManager().SetSuccessfulReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as successful reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.failed = w.failed.Remove(id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSuccessful)\n\t\t} else if !w.failedByID(taskContext, id) {\n\t\t\t// If a resource is no longer reported as Failed and is not Reconciled,\n\t\t\t// they should just go back to InProgress.\n\t\t\terr := taskContext.InventoryManager().SetPendingReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as pending reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.failed = w.failed.Remove(id)\n\t\t\tw.pending = append(w.pending, id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcilePending)\n\t\t}\n\t\t// else - still failed\n\tdefault:\n\t\t// reconciled - check if unreconciled\n\t\tif !w.reconciledByID(taskContext, id) {\n\t\t\t// unreconciled - add to pending & send event\n\t\t\terr := taskContext.InventoryManager().SetPendingReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as pending reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.pending = append(w.pending, id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcilePending)\n\t\t}\n\t\t// else - still reconciled\n\t}\n\n\tklog.V(3).Infof(\"wait task progress: %d/%d\", len(w.Ids)-len(w.pending), len(w.Ids))\n\n\t// If we no longer have any pending resources, the WaitTask\n\t// can be completed.\n\tif len(w.pending) == 0 {\n\t\t// all reconciled, so exit\n\t\tklog.V(3).Infof(\"all objects reconciled or skipped (name: %q)\", w.TaskName)\n\t\tw.cancelFunc()\n\t}\n}", "func taskComplete(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": true}}\n\tresult, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"modified count: \", result.ModifiedCount)\n}", "func (s *Server) updateTaskStatus(msg message.Message, status models.State, db *database.DataStore) error {\n\tselector := bson.M{\"$and\": []bson.M{\n\t\tbson.M{\"ulid\": msg.ULID},\n\t\tbson.M{\"tasks\": bson.M{\"$elemMatch\": bson.M{\"task_id\": msg.TaskID}}}}}\n\tupdate := bson.M{\"$set\": bson.M{\"tasks.$.status\": status}}\n\tif status == models.Failed {\n\t\tlog.Errorf(\"[%s] %s\", msg.ULID, errors.Errors[msg.ErrorID])\n\t\ts.saveErr(msg.ULID, msg.TaskID, msg.ErrorID, db)\n\t}\n\treturn db.C(models.Schedules).Update(selector, update)\n}", "func taskComplete(task string) {\n\tlog.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\tupdate := bson.M{\"$set\": bson.M{\"status\": true}}\n\tresult, err := collection.UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"modified count: \", result.ModifiedCount)\n}", "func (p *AuroraAdminClient) ForceTaskState(ctx context.Context, taskId string, status ScheduleStatus) (r *Response, err error) {\n var _args319 AuroraAdminForceTaskStateArgs\n _args319.TaskId = taskId\n _args319.Status = status\n var _result320 AuroraAdminForceTaskStateResult\n if err = p.Client_().Call(ctx, \"forceTaskState\", &_args319, &_result320); err != nil {\n return\n }\n return _result320.GetSuccess(), nil\n}", "func (m *Master) UpdateMapTaskStatus(args *UpdateStatusRequest, reply *UpdateStatusReply) error {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Println(\"work failed:\", err)\n\t\t\treply.Err = fmt.Sprintf(\"%s\", err)\n\t\t}\n\t}()\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif args.Status == SUCCESS {\n\t\tfor _, record := range m.tasks[args.TaskID] {\n\t\t\trecord.status = SUCCESS\n\t\t\tm.successCounter++\n\t\t}\n\n\t\tif m.successCounter >= len(m.files) {\n\t\t\tm.phase = TaskReduceType\n\t\t\tlog.Println(\"All Map task have done , let we entry reduce phase!\")\n\t\t}\n\t} else if args.Status == FAILED {\n\t\t//TODO add to failed list\n\t} else {\n\t\treturn &argError{args.Status, \"map task just return success or failed\"}\n\t}\n\treturn nil\n}", "func genericPodDelete(label, namespace string, clientset *kubernetes.Clientset) error {\n\n\tvar name string\n\t//Getting all pods in litmus Namespace\n\tpods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn errors.Errorf(\"failed to get pods in %v namespace, err: %v\", err)\n\t}\n\n\tklog.Infof(\"[Info]: Selecting pod with label %v for reboot\", label)\n\tfor i := range pods.Items {\n\t\tif pods.Items[i].Labels[\"component\"] == label {\n\t\t\tname = pods.Items[i].Name\n\t\t}\n\t}\n\tklog.Infof(\"[Info]: Deleting the Pod : %v\", name)\n\terr = clientset.CoreV1().Pods(\"litmus\").Delete(context.TODO(), name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn errors.Errorf(\"failed to delete %v pod, err: %v\", name, err)\n\t}\n\tklog.Infof(\"[Info]: %v pod deleted successfully \\n\", name)\n\treturn nil\n}", "func Run(task structs.Task, threadChannel chan<- structs.ThreadMsg) {\n\ttMsg := structs.ThreadMsg{}\n\ttMsg.Error = false\n\ttMsg.TaskItem = task\n\n\tparams := strings.TrimSpace(task.Params)\n\terr := os.Unsetenv(params)\n\n\tif err != nil {\n\t\ttMsg.Error = true\n\t\ttMsg.TaskResult = []byte(err.Error())\n\t\tthreadChannel <- tMsg\n\t\treturn\n\t}\n\n\ttMsg.TaskResult = []byte(fmt.Sprintf(\"Successfully cleared %s\", params))\n\tthreadChannel <- tMsg\n}", "func (t *task) deleteTask() {\n\t// There is no state to clean up as of now.\n\t// If the goal state was set to DELETED, then let the\n\t// listeners know that the task has been deleted.\n\n\tvar runtimeCopy *pbtask.RuntimeInfo\n\tvar labelsCopy []*peloton.Label\n\n\t// notify listeners after dropping the lock\n\tdefer func() {\n\t\tif runtimeCopy != nil {\n\t\t\tt.jobFactory.notifyTaskRuntimeChanged(\n\t\t\t\tt.jobID,\n\t\t\t\tt.id,\n\t\t\t\tt.jobType,\n\t\t\t\truntimeCopy,\n\t\t\t\tlabelsCopy,\n\t\t\t)\n\t\t}\n\t}()\n\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\tif t.runtime == nil {\n\t\treturn\n\t}\n\n\tif t.runtime.GetGoalState() != pbtask.TaskState_DELETED {\n\t\treturn\n\t}\n\n\truntimeCopy = proto.Clone(t.runtime).(*pbtask.RuntimeInfo)\n\truntimeCopy.State = pbtask.TaskState_DELETED\n\tlabelsCopy = t.copyLabelsInCache()\n}", "func (task *QueueTask) Reset(conf *TaskConfig) error {\n\tif conf.Interval <= 0 {\n\t\terrmsg := \"interval is wrong format => must bigger then zero\"\n\t\ttask.taskService.Logger().Debug(fmt.Sprint(\"TaskInfo:Reset \", task, conf, \"error\", errmsg))\n\t\treturn errors.New(errmsg)\n\t}\n\n\t//restart task\n\ttask.Stop()\n\ttask.IsRun = conf.IsRun\n\tif conf.TaskData != nil {\n\t\ttask.TaskData = conf.TaskData\n\t}\n\tif conf.Handler != nil {\n\t\ttask.handler = conf.Handler\n\t}\n\ttask.Interval = conf.Interval\n\ttask.Start()\n\ttask.taskService.Logger().Debug(fmt.Sprint(\"TaskInfo:Reset \", task, conf, \"success\"))\n\treturn nil\n}", "func (p *AuroraAdminClient) ForceTaskState(ctx context.Context, taskId string, status ScheduleStatus) (r *Response, err error) {\n var _args369 AuroraAdminForceTaskStateArgs\n _args369.TaskId = taskId\n _args369.Status = status\n var _result370 AuroraAdminForceTaskStateResult\n var meta thrift.ResponseMeta\n meta, err = p.Client_().Call(ctx, \"forceTaskState\", &_args369, &_result370)\n p.SetLastResponseMeta_(meta)\n if err != nil {\n return\n }\n return _result370.GetSuccess(), nil\n}", "func (t *Task) updateStatus() {\n\tb, err := json.Marshal(&map[string]interface{}{\n\t\t\"type\": \"update\",\n\t\t\"start\": t.Desc.Start,\n\t\t\"end\": t.Desc.End,\n\t\t\"status\": t.Desc.Status,\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\torm.UpdateTask(&t.Desc)\n\tsockets.Message(t.Desc.ID, b)\n}", "func updateTaskState(task *api.Task) api.TaskStatus {\n\t//The task is the minimum status of all its essential containers unless the\n\t//status is terminal in which case it's that status\n\tlog.Debug(\"Updating task\", \"task\", task)\n\n\t// minContainerStatus is the minimum status of all essential containers\n\tminContainerStatus := api.ContainerDead + 1\n\t// minContainerStatus is the minimum status of all containers to be used in\n\t// the edge case of no essential containers\n\tabsoluteMinContainerStatus := minContainerStatus\n\tfor _, cont := range task.Containers {\n\t\tlog.Debug(\"On container\", \"cont\", cont)\n\t\tif cont.KnownStatus < absoluteMinContainerStatus {\n\t\t\tabsoluteMinContainerStatus = cont.KnownStatus\n\t\t}\n\t\tif !cont.Essential {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Terminal states\n\t\tif cont.KnownStatus == api.ContainerStopped {\n\t\t\tif task.KnownStatus < api.TaskStopped {\n\t\t\t\ttask.KnownStatus = api.TaskStopped\n\t\t\t\treturn task.KnownStatus\n\t\t\t}\n\t\t} else if cont.KnownStatus == api.ContainerDead {\n\t\t\tif task.KnownStatus < api.TaskDead {\n\t\t\t\ttask.KnownStatus = api.TaskDead\n\t\t\t\treturn task.KnownStatus\n\t\t\t}\n\t\t}\n\t\t// Non-terminal\n\t\tif cont.KnownStatus < minContainerStatus {\n\t\t\tminContainerStatus = cont.KnownStatus\n\t\t}\n\t}\n\n\tif minContainerStatus == api.ContainerDead+1 {\n\t\tlog.Warn(\"Task with no essential containers; all properly formed tasks should have at least one essential container\", \"task\", task)\n\n\t\t// If there's no essential containers, let's just assume the container\n\t\t// with the earliest status is essential and proceed.\n\t\tminContainerStatus = absoluteMinContainerStatus\n\t}\n\n\tlog.Info(\"MinContainerStatus is \" + minContainerStatus.String())\n\n\tif minContainerStatus == api.ContainerCreated {\n\t\tif task.KnownStatus < api.TaskCreated {\n\t\t\ttask.KnownStatus = api.TaskCreated\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerRunning {\n\t\tif task.KnownStatus < api.TaskRunning {\n\t\t\ttask.KnownStatus = api.TaskRunning\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerStopped {\n\t\tif task.KnownStatus < api.TaskStopped {\n\t\t\ttask.KnownStatus = api.TaskStopped\n\t\t\treturn task.KnownStatus\n\t\t}\n\t} else if minContainerStatus == api.ContainerDead {\n\t\tif task.KnownStatus < api.TaskDead {\n\t\t\ttask.KnownStatus = api.TaskDead\n\t\t\treturn task.KnownStatus\n\t\t}\n\t}\n\treturn api.TaskStatusNone\n}", "func UpdateRemoveNodeDBInfoTask(taskID string, stepName string) error {\n\tstart := time.Now()\n\n\t// get task form database\n\ttask, err := cloudprovider.GetStorageModel().GetTask(context.Background(), taskID)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s get detail task information from storage failed: %s, task retry\", taskID, taskID, err.Error())\n\t\treturn err\n\t}\n\n\t// task state check\n\tstate := &cloudprovider.TaskState{\n\t\tTask: task,\n\t\tJobResult: cloudprovider.NewJobSyncResult(task),\n\t}\n\t// check task already terminated\n\tif state.IsTerminated() {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s is terminated, step %s skip\", taskID, taskID, stepName)\n\t\treturn fmt.Errorf(\"task %s terminated\", taskID)\n\t}\n\t// workflow switch current step to stepName when previous task exec successful\n\tstep, err := state.IsReadyToStep(stepName)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s not turn ro run step %s, err %s\", taskID, taskID, stepName, err.Error())\n\t\treturn err\n\t}\n\t// previous step successful when retry task\n\tif step == nil {\n\t\tblog.Infof(\"UpdateRemoveNodeDBInfoTask[%s]: current step[%s] successful and skip\", taskID, stepName)\n\t\treturn nil\n\t}\n\n\tblog.Infof(\"UpdateRemoveNodeDBInfoTask[%s] task %s run current step %s, system: %s, old state: %s, params %v\",\n\t\ttaskID, taskID, stepName, step.System, step.Status, step.Params)\n\n\t// extract valid info\n\tsuccess := strings.Split(step.Params[\"NodeIPs\"], \",\")\n\tif len(success) > 0 {\n\t\tfor i := range success {\n\t\t\terr = cloudprovider.GetStorageModel().DeleteNodeByIP(context.Background(), success[i])\n\t\t\tif err != nil {\n\t\t\t\tblog.Errorf(\"UpdateRemoveNodeDBInfoTask[%s] task %s DeleteNodeByIP failed: %v\", taskID, taskID, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// update step\n\tif err := state.UpdateStepSucc(start, stepName); err != nil {\n\t\tblog.Errorf(\"UpdateNodeDBInfoTask[%s] task %s %s update to storage fatal\", taskID, taskID, stepName)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func updateTask(w http.ResponseWriter, r *http.Request){\n\t//definimos variable de vars que devuelve las variables de ruta\n\tvars := mux.Vars(r)\n\t//convertimos la variable del id a ints\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\n\n\t//Creamos una variable donde almacenaremos la nueva tarea \n\tvar updatedTask task\n\n\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Invalid ID\")\n\t}\n\n\t//Creamos una funcion que lee todo el body del request\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w,\"Please enter Valid Data\")\n\t}\n\n\t//Desarma el Json y lo hace una struct\n\tjson.Unmarshal(reqBody, &updatedTask)\n\n\t\n\t//Se busca entre todas las tasks una task con el ID solicitado\n\tfor i, task := range tasks {\n\t\tif task.ID == taskID {\n\t\t\t//Se elimina la task a la lista, guardando todas las que estan hasta su indice, y la que le sigue en adelante.\n\t\t\ttasks = append(tasks[:i], tasks[i + 1:]...)\n\n\t\t\t//El id se mantiene\n\t\t\tupdatedTask.ID = taskID\n\t\t\t//Se agrega nueva task\n\t\t\ttasks = append(tasks, updatedTask)\n\n\t\t\t//Aviso de que la task se cambio con exito\n\t\t\tfmt.Fprintf(w, \"The task with ID %v has been succesfully updated\", taskID)\n\t\t}\n\t}\n}", "func (tc *DBTaskConnector) ResetTask(taskId, username string, proj *serviceModel.Project) error {\n\treturn errors.Wrap(serviceModel.TryResetTask(taskId, username, evergreen.RESTV2Package, proj, nil),\n\t\t\"Reset task error\")\n}", "func (e *Endpoints) TaskClean(interval time.Duration) {\n\tl := loop.New(loop.WithInterval(interval))\n\tl.Do(func() (bool, error) {\n\t\ttimeUnix := time.Now().Unix()\n\t\tfmt.Println(timeUnix)\n\n\t\tstartTimestamp := timeUnix - TaskCleanDurationTimestamp\n\n\t\tstartTime := time.Unix(startTimestamp, 0).Format(\"2006-01-02 15:04:05\")\n\n\t\t// clean job resource\n\t\tjobs := e.dbclient.ListExpiredJobs(startTime)\n\n\t\tfor _, job := range jobs {\n\t\t\terr := e.dbclient.DeleteJob(strconv.FormatUint(job.OrgID, 10), job.TaskID)\n\t\t\tif err != nil {\n\t\t\t\terr = e.dbclient.DeleteJob(strconv.FormatUint(job.OrgID, 10), job.TaskID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.Errorf(\"failed to delete job, job: %+v, (%+v)\", job, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogrus.Debugf(\"[clean] expired job: %+v\", job)\n\t\t}\n\n\t\t// clean deployment resource\n\t\tdeployments := e.dbclient.ListExpiredDeployments(startTime)\n\n\t\tfor _, deployment := range deployments {\n\t\t\terr := e.dbclient.DeleteDeployment(strconv.FormatUint(deployment.OrgID, 10), deployment.TaskID)\n\t\t\tif err != nil {\n\t\t\t\terr = e.dbclient.DeleteDeployment(strconv.FormatUint(deployment.OrgID, 10), deployment.TaskID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.Errorf(\"failed to delete deployment, deployment: %+v, (%+v)\", deployment, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogrus.Debugf(\"[clean] expired deployment: %+v\", deployment)\n\t\t}\n\n\t\treturn false, nil\n\t})\n}", "func (context Context) UpdateTaskStatus(id string, status string, statusMessage string) (err error) {\n\t_, err = context.UpdateTask(id, F{\"status\": status, \"status-message\": statusMessage})\n\treturn\n}", "func deleteTasks() {\n\tcounter := 0\n\n\t// Create AWS session\n\ts, err := session.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't create AWS Session.\")\n\t}\n\n\t// Create the AWS Service\n\tsvc := databasemigrationservice.New(s, &aws.Config{Region: &region})\n\n\t// Read the defaults file\n\treadTasks, err := ioutil.ReadFile(tasksFile)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't read file \"+tasksFile, err)\n\t}\n\n\t// Create tasks and unmarshal the JSON\n\ttasks := new([]ReplicationTask)\n\tremainingTasks := new([]ReplicationTask) // Tasks that will be saved (if they couldn't be removed for example)\n\terr = json.Unmarshal(readTasks, tasks)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't JSON unmarshal file \"+tasksFile, err)\n\t}\n\n\t// Start all the tasks stored in tasks\n\tfor _, task := range *tasks {\n\t\tparams := &databasemigrationservice.DeleteReplicationTaskInput{\n\t\t\tReplicationTaskArn: aws.String(task.ReplicationTaskArn),\n\t\t}\n\n\t\t_, err := svc.DeleteReplicationTask(params)\n\t\tif err != nil {\n\t\t\t// If the task doesn't exists we shouldn't keep it in the tasks.json file - just continue\n\t\t\tif strings.Contains(err.Error(), notFound) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If the task errored and not because it doesn't exists, keep it in the tasks.json file\n\t\t\t*remainingTasks = append(*remainingTasks, task)\n\n\t\t\t// Go through the different statuses that might have made the action failed\n\t\t\tswitch {\n\t\t\tcase strings.Contains(err.Error(), isRunning):\n\t\t\t\tfmt.Println(\"Please stop task\", task.ReplicationTaskIdentifier, stopBeforeDeleting)\n\t\t\t\tcontinue\n\t\t\tcase strings.Contains(err.Error(), \"is currently being stopped\"):\n\t\t\t\tfmt.Println(\"Please wait until task\", task.ReplicationTaskIdentifier, waitForStop)\n\t\t\t\tcontinue\n\t\t\tcase strings.Contains(err.Error(), \"is already being deleted\"):\n\t\t\t\tfmt.Println(\"Task\", task.ReplicationTaskIdentifier, beingDeleted)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfmt.Println(\"Couldn't delete Replication Task\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcounter++\n\t\tfmt.Println(\"Task deleted: \" + task.ReplicationTaskIdentifier)\n\t}\n\n\t// If we have no tasks left, delete the whole file\n\tswitch {\n\tcase len(*remainingTasks) == 0:\n\t\terr := os.Remove(tasksFile)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Couldn't remove tasks files\", err)\n\t\t}\n\n\tdefault:\n\t\t// Write remaining tasks to tasks-file\n\t\twriteTaskFile(remainingTasks)\n\t}\n\n\tfmt.Println(\"\\nDONE! Deleted\", counter, \"tasks.\")\n}", "func (e *Endpoints) SyncTaskStatus(interval time.Duration) {\n\tl := loop.New(loop.WithInterval(interval))\n\tl.Do(func() (bool, error) {\n\t\t// deal job resource\n\t\tjobs := e.dbclient.ListRunningJobs()\n\n\t\tfor _, job := range jobs {\n\t\t\t// 根据pipelineID获取task列表信息\n\t\t\tpipelineInfo, err := e.PipelineSvc.PipelineDetail(apis.WithInternalClientContext(context.Background(), discover.CMP()), &pipelinepb.PipelineDetailRequest{\n\t\t\t\tPipelineID: job.PipelineID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"failed to get pipeline info by pipelineID, pipelineID:%d, (%+v)\", job.PipelineID, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, stage := range pipelineInfo.Data.PipelineStages {\n\t\t\t\tfor _, task := range stage.PipelineTasks {\n\t\t\t\t\tif task.ID == job.TaskID {\n\t\t\t\t\t\tif string(task.Status) != job.Status {\n\t\t\t\t\t\t\tjob.Status = string(task.Status)\n\n\t\t\t\t\t\t\t// 更新数据库状态\n\t\t\t\t\t\t\te.dbclient.UpdateJobStatus(&job)\n\t\t\t\t\t\t\tlogrus.Debugf(\"update job status, jobID:%d, status:%s\", job.ID, job.Status)\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}\n\n\t\t// deal deployment resource\n\t\tdeployments := e.dbclient.ListRunningDeployments()\n\n\t\tfor _, deployment := range deployments {\n\t\t\t// 根据pipelineID获取task列表信息\n\t\t\tpipelineInfo, err := e.PipelineSvc.PipelineDetail(apis.WithInternalClientContext(context.Background(), discover.CMP()), &pipelinepb.PipelineDetailRequest{\n\t\t\t\tPipelineID: deployment.PipelineID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"failed to get pipeline info by pipelineID, pipelineID:%d, (%+v)\", deployment.PipelineID, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, stage := range pipelineInfo.Data.PipelineStages {\n\t\t\t\tfor _, task := range stage.PipelineTasks {\n\t\t\t\t\tif task.ID == deployment.TaskID {\n\t\t\t\t\t\tif string(task.Status) != deployment.Status {\n\t\t\t\t\t\t\tdeployment.Status = string(task.Status)\n\n\t\t\t\t\t\t\t// 更新数据库状态\n\t\t\t\t\t\t\te.dbclient.UpdateDeploymentStatus(&deployment)\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}\n\n\t\treturn false, nil\n\t})\n}", "func (c *Controller) handleTektonTaskRun(obj interface{}) {\n\tvar object metav1.Object\n\tvar ok bool\n\tif object, ok = obj.(metav1.Object); !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error decoding object, invalid type\"))\n\t\t\treturn\n\t\t}\n\t\tobject, ok = tombstone.Obj.(metav1.Object)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error decoding object tombstone, invalid type\"))\n\t\t\treturn\n\t\t}\n\t\tklog.V(3).Infof(\"Recovered deleted object '%s' from tombstone\", object.GetName())\n\t}\n\tklog.V(4).Infof(\"Processing object: %s\", object.GetSelfLink())\n\tannotations := object.GetAnnotations()\n\trunKey := annotations[annotationPipelineRunKey]\n\tif runKey != \"\" {\n\t\tklog.V(4).Infof(\"Add to workqueue '%s'\", runKey)\n\t\tc.workqueue.Add(runKey)\n\t}\n}", "func (s *Scheduler) tick(ctx context.Context) {\n\ttype commonSpecKey struct {\n\t\tserviceID string\n\t\tspecVersion api.Version\n\t}\n\ttasksByCommonSpec := make(map[commonSpecKey]map[string]*api.Task)\n\tvar oneOffTasks []*api.Task\n\tschedulingDecisions := make(map[string]schedulingDecision, len(s.unassignedTasks))\n\n\tfor taskID, t := range s.unassignedTasks {\n\t\tif t == nil || t.NodeID != \"\" {\n\t\t\t// task deleted or already assigned\n\t\t\tdelete(s.unassignedTasks, taskID)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Group tasks with common specs\n\t\tif t.SpecVersion != nil {\n\t\t\ttaskGroupKey := commonSpecKey{\n\t\t\t\tserviceID: t.ServiceID,\n\t\t\t\tspecVersion: *t.SpecVersion,\n\t\t\t}\n\n\t\t\tif tasksByCommonSpec[taskGroupKey] == nil {\n\t\t\t\ttasksByCommonSpec[taskGroupKey] = make(map[string]*api.Task)\n\t\t\t}\n\t\t\ttasksByCommonSpec[taskGroupKey][taskID] = t\n\t\t} else {\n\t\t\t// This task doesn't have a spec version. We have to\n\t\t\t// schedule it as a one-off.\n\t\t\toneOffTasks = append(oneOffTasks, t)\n\t\t}\n\t\tdelete(s.unassignedTasks, taskID)\n\t}\n\n\tfor _, taskGroup := range tasksByCommonSpec {\n\t\ts.scheduleTaskGroup(ctx, taskGroup, schedulingDecisions)\n\t}\n\tfor _, t := range oneOffTasks {\n\t\ts.scheduleTaskGroup(ctx, map[string]*api.Task{t.ID: t}, schedulingDecisions)\n\t}\n\n\t_, failed := s.applySchedulingDecisions(ctx, schedulingDecisions)\n\tfor _, decision := range failed {\n\t\ts.allTasks[decision.old.ID] = decision.old\n\n\t\tnodeInfo, err := s.nodeSet.nodeInfo(decision.new.NodeID)\n\t\tif err == nil && nodeInfo.removeTask(decision.new) {\n\t\t\ts.nodeSet.updateNode(nodeInfo)\n\t\t}\n\n\t\t// release the volumes we tried to use\n\t\tfor _, va := range decision.new.Volumes {\n\t\t\ts.volumes.releaseVolume(va.ID, decision.new.ID)\n\t\t}\n\n\t\t// enqueue task for next scheduling attempt\n\t\ts.enqueue(decision.old)\n\t}\n}", "func (ctl *StatusController) fillTask(ctx context.Context, task Task) (TaskStatus, error) {\n\tvar err error\n\ts := TaskStatus{\n\t\tInfo: task.Info,\n\t}\n\n\tif s.paused, err = task.IsPaused(ctx); err != nil {\n\t\treturn s, errors.Annotatef(err, \"failed to get pause status of task %s\", s.Info.Name)\n\t}\n\n\tif s.Checkpoints, err = task.NextBackupTSList(ctx); err != nil {\n\t\treturn s, errors.Annotatef(err, \"failed to get progress of task %s\", s.Info.Name)\n\t}\n\n\tif s.globalCheckpoint, err = task.GetStorageCheckpoint(ctx); err != nil {\n\t\treturn s, errors.Annotatef(err, \"failed to get storage checkpoint of task %s\", s.Info.Name)\n\t}\n\n\ts.LastErrors, err = task.LastError(ctx)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\ts.QPS, err = MaybeQPS(ctx, ctl.mgr)\n\tif err != nil {\n\t\treturn s, errors.Annotatef(err, \"failed to get QPS of task %s\", s.Info.Name)\n\t}\n\treturn s, nil\n}", "func (m *Master) SignalTaskStatus(args *model.TaskStatus, reply *bool) error {\n\tif !args.Success {\n\t\treturn nil\n\t}\n\n\tif m.phase == model.Map {\n\t\tlog.Infof(\"map phase for %s completed\", args.File)\n\t\tm.mutex.Lock()\n\t\tdefer m.mutex.Unlock()\n\t\tf := path.Base(args.File)\n\t\tif t, ok := m.mapTasks[f]; ok {\n\t\t\tif t.Status == inprogress {\n\t\t\t\tt.Status = completed\n\t\t\t\tt.Files = append(t.Files, args.OutFiles...)\n\t\t\t\tm.mapTasks[f] = t\n\t\t\t}\n\n\t\t\t// Build up reduce tasks.\n\t\t\tfor i, v := range args.OutFiles {\n\t\t\t\tkey := toString(i + 1)\n\t\t\t\tt := m.reduceTasks[key]\n\t\t\t\tt.Files = append(t.Files, v)\n\t\t\t\tm.reduceTasks[key] = t\n\t\t\t}\n\t\t}\n\t} else if m.phase == model.Reduce {\n\t\tlog.Infof(\"reduce phase %s completed\", args.File)\n\t\ti, _ := strconv.ParseInt(args.File, 10, 32)\n\t\tkey := toString(i + 1)\n\t\tm.mutex.Lock()\n\t\tdefer m.mutex.Unlock()\n\t\tif t, ok := m.reduceTasks[key]; ok {\n\t\t\tif t.Status == inprogress {\n\t\t\t\tt.Status = completed\n\t\t\t\tm.reduceTasks[key] = t\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *stat) DoneTask(t task.Task) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif _, found := s.inProgress[key(t)]; !found {\n\t\treturn\n\t}\n\tdelete(s.inProgress, key(t))\n\n\tjobid := getJobID(&t)\n\n\tstart, _ := time.Parse(time.RFC3339, t.Started)\n\tend, _ := time.Parse(time.RFC3339, t.Ended)\n\td := end.Sub(start)\n\tjobRuntimeMetric.WithLabelValues(t.Type, jobid).Observe(d.Seconds())\n\n\tif t.Result == task.ErrResult {\n\t\ts.error.Add(d)\n\t\tjobFailureMetric.WithLabelValues(t.Type, jobid).Inc()\n\t} else if t.Result == task.CompleteResult {\n\t\ts.success.Add(d)\n\t\tjobSuccessMetric.WithLabelValues(t.Type, jobid).Inc()\n\t}\n}", "func ResetTasks() {\n\tconn := getConnection(\"mflow\")\n\tdb, err := sql.Open(\"godror\", conn.User+\"/\"+conn.Password+\"@\"+conn.ConnectionString)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer db.Close()\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tconst command string = `delete mflow.tasks where id_master = :id_master and status = :status`\n\t_, err = tx.Exec(command, sql.Named(\"id_master\", global.IDMaster), sql.Named(\"status\", runningStatus))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (k *KubernetesScheduler) DeletePod(podId string) error {\n\tlog.V(2).Infof(\"Delete pod '%s'\\n\", podId)\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// TODO(jdef): set pod.DesiredState.Host=\"\"\n\t// The k8s DeletePod() implementation does this, and the k8s REST implementation\n\t// uses this state to determine what level of pod detail should be returned to the\n\t// end user. Need to think more about the impact of setting this to \"\" before doing\n\t// the same.\n\n\t// prevent the scheduler from attempting to pop this; it's also possible that\n\t// it's concurrently being scheduled (somewhere between pod scheduling and\n\t// binding)\n\tk.podQueue.Delete(podId)\n\n\ttaskId, exists := k.podToTask[podId]\n\tif !exists {\n\t\treturn fmt.Errorf(\"Could not resolve pod '%s' to task id\", podId)\n\t}\n\n\t// determine if the task has already been launched to mesos, if not then\n\t// cleanup is easier (podToTask,pendingTasks) since there's no state to sync\n\n\tif task, exists := k.runningTasks[taskId]; exists {\n\t\ttaskId := &mesos.TaskID{Value: proto.String(task.ID)}\n\t\treturn k.Driver.KillTask(taskId)\n\t}\n\n\tif task, exists := k.pendingTasks[taskId]; exists {\n\t\tif !task.Launched {\n\t\t\tdelete(k.podToTask, podId)\n\t\t\tdelete(k.pendingTasks, taskId)\n\t\t\treturn nil\n\t\t}\n\t\ttaskId := &mesos.TaskID{Value: proto.String(task.ID)}\n\t\treturn k.Driver.KillTask(taskId)\n\t}\n\n\treturn fmt.Errorf(\"Cannot kill pod '%s': pod not found\", podId)\n}", "func (s *Service) UpdateTaskStatus(c context.Context, date string, typ int, status int) (err error) {\n\t_, err = s.dao.UpdateTaskStatus(c, date, typ, status)\n\treturn\n}", "func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode task state from handle: %v\", err)\n\t}\n\td.logger.Debug(\"Checking for recoverable task\", \"task\", handle.Config.Name, \"taskid\", handle.Config.ID, \"container\", taskState.ContainerID)\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, taskState.ContainerID)\n\tif err != nil {\n\t\td.logger.Warn(\"Recovery lookup failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: taskState.ContainerID,\n\t\tdriver: d,\n\t\ttaskConfig: taskState.TaskConfig,\n\t\tprocState: drivers.TaskStateUnknown,\n\t\tstartedAt: taskState.StartedAt,\n\t\texitResult: &drivers.ExitResult{},\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tif inspectData.State.Running {\n\t\td.logger.Info(\"Recovered a still running container\", \"container\", inspectData.State.Pid)\n\t\th.procState = drivers.TaskStateRunning\n\t} else if inspectData.State.Status == \"exited\" {\n\t\t// are we allowed to restart a stopped container?\n\t\tif d.config.RecoverStopped {\n\t\t\td.logger.Debug(\"Found a stopped container, try to start it\", \"container\", inspectData.State.Pid)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery restart failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\t\t} else {\n\t\t\t\td.logger.Info(\"Restarted a container during recovery\", \"container\", inspectData.ID)\n\t\t\t\th.procState = drivers.TaskStateRunning\n\t\t\t}\n\t\t} else {\n\t\t\t// no, let's cleanup here to prepare for a StartTask()\n\t\t\td.logger.Debug(\"Found a stopped container, removing it\", \"container\", inspectData.ID)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery cleanup failed\", \"task\", handle.Config.ID, \"container\", inspectData.ID)\n\t\t\t}\n\t\t\th.procState = drivers.TaskStateExited\n\t\t}\n\t} else {\n\t\td.logger.Warn(\"Recovery restart failed, unknown container state\", \"state\", inspectData.State.Status, \"container\", taskState.ContainerID)\n\t\th.procState = drivers.TaskStateUnknown\n\t}\n\n\td.tasks.Set(taskState.TaskConfig.ID, h)\n\n\tgo h.runContainerMonitor()\n\td.logger.Debug(\"Recovered container handle\", \"container\", taskState.ContainerID)\n\n\treturn nil\n}", "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.killPodForTask(driver, taskId.GetValue(), messages.TaskKilled)\n}", "func updateTasks(c context.Context) {\n\tnow := clock.Now(c)\n\tq := datastore.NewQuery(\"TaskCount\").Order(\"computed\")\n\tif err := datastore.Run(c, q, func(tc *TaskCount) {\n\t\tif now.Sub(tc.Computed) > 5*time.Minute {\n\t\t\tlogging.Debugf(c, \"deleting outdated count %q\", tc.Queue)\n\t\t\tif err := datastore.Delete(c, tc); err != nil {\n\t\t\t\tlogging.Errorf(c, \"%s\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttasksExecuting.Set(c, int64(tc.Executing), tc.Queue)\n\t\ttasksPending.Set(c, int64(tc.Total-tc.Executing), tc.Queue)\n\t\ttasksTotal.Set(c, int64(tc.Total), tc.Queue)\n\t}); err != nil {\n\t\terrors.Log(c, errors.Annotate(err, \"failed to fetch counts\").Err())\n\t}\n}", "func (d *Driver) DestroyTask(taskID string, force bool) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\tif handle.isRunning() && !force {\n\t\treturn fmt.Errorf(\"cannot destroy running task\")\n\t}\n\n\tif handle.isRunning() {\n\t\td.logger.Debug(\"Have to destroyTask but container is still running\", \"containerID\", handle.containerID)\n\t\t// we can not do anything, so catching the error is useless\n\t\terr := d.podman.ContainerStop(d.ctx, handle.containerID, 60)\n\t\tif err != nil {\n\t\t\td.logger.Warn(\"failed to stop/kill container during destroy\", \"error\", err)\n\t\t}\n\t\t// wait a while for stats emitter to collect exit code etc.\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tif !handle.isRunning() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 250)\n\t\t}\n\t\tif handle.isRunning() {\n\t\t\td.logger.Warn(\"stats emitter did not exit while stop/kill container during destroy\", \"error\", err)\n\t\t}\n\t}\n\n\tif handle.removeContainerOnExit {\n\t\terr := d.podman.ContainerDelete(d.ctx, handle.containerID, true, true)\n\t\tif err != nil {\n\t\t\td.logger.Warn(\"Could not remove container\", \"container\", handle.containerID, \"error\", err)\n\t\t}\n\t}\n\n\td.tasks.Delete(taskID)\n\treturn nil\n}", "func (t *TaskService) Delete(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\temptyUUID gocql.UUID\n\t\ttaskIDStr = mux.Vars(r)[\"taskID\"]\n\t\tpartnerID = mux.Vars(r)[\"partnerID\"]\n\t\tctx = r.Context()\n\t\tcurrentUser = t.userService.GetUser(r, t.httpClient)\n\t)\n\n\ttaskID, err := gocql.ParseUUID(taskIDStr)\n\tif err != nil || taskID == emptyUUID {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorTaskIDHasBadFormat, \"TaskService.Delete: task ID(UUID=%s) has bad format or empty. err=%v\", taskIDStr, err)\n\t\tcommon.SendBadRequest(w, r, errorcode.ErrorTaskIDHasBadFormat)\n\t\treturn\n\t}\n\n\tinternalTasks, err := t.taskPersistence.GetByIDs(ctx, nil, partnerID, false, taskID)\n\tif err != nil {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorCantGetTaskByTaskID, \"TaskService.Delete: can't get internal tasks by task ID %v. err=%v\", taskID, err)\n\t\tcommon.SendInternalServerError(w, r, errorcode.ErrorCantGetTaskByTaskID)\n\t\treturn\n\t}\n\n\tif len(internalTasks) == 0 {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorTaskIsNotFoundByTaskID, \"TaskService.Delete: task with ID %v not found.\", taskID)\n\t\tcommon.SendBadRequest(w, r, errorcode.ErrorTaskIsNotFoundByTaskID)\n\t\treturn\n\t}\n\n\tcommonTaskData := internalTasks[0]\n\tif currentUser.HasNOCAccess() != commonTaskData.IsRequireNOCAccess {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorAccessDenied, \"TaskService.Delete: current user %s is not authorized to delete task with ID %v for partnerID %v\", currentUser.UID(), commonTaskData.ID, commonTaskData.PartnerID)\n\t\tcommon.SendForbidden(w, r, errorcode.ErrorAccessDenied)\n\t\treturn\n\t}\n\n\tdto, err := t.getDataToDelete(ctx, taskID, r, w, partnerID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdto.tasks = internalTasks\n\tif err = t.executeDeleting(dto); err != nil {\n\t\tlogger.Log.ErrfCtx(r.Context(), errorcode.ErrorCantDeleteTask, \"TaskService.Delete: can't process deleting of the task. err=%v\", err)\n\t\tcommon.SendInternalServerError(w, r, errorcode.ErrorCantDeleteTask)\n\t\treturn\n\t}\n\n\tif !currentUser.HasNOCAccess() {\n\t\t// update counters for tasks in separate goroutine\n\t\tgo func(ctx context.Context, iTasks []models.Task) {\n\t\t\tcounters := getCountersForInternalTasks(iTasks)\n\t\t\tif len(counters) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr := t.taskCounterRepo.DecreaseCounter(commonTaskData.PartnerID, counters, false)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.ErrfCtx(ctx, errorcode.ErrorCantProcessData, \"Delete: error while trying to increase counter: \", err)\n\t\t\t}\n\t\t}(ctx, internalTasks)\n\t}\n\n\tlogger.Log.InfofCtx(r.Context(), \"TaskService.Delete: successfully deleted task with ID = %v\", taskID)\n\tcommon.SendNoContent(w)\n}", "func deleteOneTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\td, err := collection.DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Deleted Document\", d.DeletedCount)\n}", "func (p *statusUpdate) logTaskMetrics(event *statusupdate.Event) {\n\tif event.V0() == nil {\n\t\treturn\n\t}\n\t// Update task state counter for non-reconcilication update.\n\treason := event.MesosTaskStatus().GetReason()\n\tif reason != mesos.TaskStatus_REASON_RECONCILIATION {\n\t\tswitch event.State() {\n\t\tcase pb_task.TaskState_RUNNING:\n\t\t\tp.metrics.TasksRunningTotal.Inc(1)\n\t\tcase pb_task.TaskState_SUCCEEDED:\n\t\t\tp.metrics.TasksSucceededTotal.Inc(1)\n\t\tcase pb_task.TaskState_FAILED:\n\t\t\tp.metrics.TasksFailedTotal.Inc(1)\n\t\t\tp.metrics.TasksFailedReason[int32(reason)].Inc(1)\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"task_id\": event.TaskID(),\n\t\t\t\t\"failed_reason\": mesos.TaskStatus_Reason_name[int32(reason)],\n\t\t\t}).Debug(\"received failed task\")\n\t\tcase pb_task.TaskState_KILLED:\n\t\t\tp.metrics.TasksKilledTotal.Inc(1)\n\t\tcase pb_task.TaskState_LOST:\n\t\t\tp.metrics.TasksLostTotal.Inc(1)\n\t\tcase pb_task.TaskState_LAUNCHED:\n\t\t\tp.metrics.TasksLaunchedTotal.Inc(1)\n\t\tcase pb_task.TaskState_STARTING:\n\t\t\tp.metrics.TasksStartingTotal.Inc(1)\n\t\t}\n\t} else {\n\t\tp.metrics.TasksReconciledTotal.Inc(1)\n\t}\n}", "func (s *sched) unlock(t Task) {\n\ts.cache.Del(prefixLock + t.GetID())\n}", "func updateTask(msg BackendPayload) {\n\tincomingTaskID := msg.ID // attempt to retreive the id of the task in the case its an update POST\n\t// TodoList[incomingTaskID] = Task{incomingTaskID, msg.TaskName} // update task with id provided\n\tTodoList.Store(incomingTaskID, Task{incomingTaskID, msg.TaskName})\n\treturn\n}", "func UpdateTask(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprint(w, \"UpdateTask\\n\")\n}", "func deleteOneTask(task string) {\n\tlog.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\td, err := collection.DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"Deleted Document\", d.DeletedCount)\n}", "func (t *TaskBox[T, U, C, CT, TF]) SetStatus(s int32) {\n\tt.status.Store(s)\n}", "func (t *TaskController[T, U, C, CT, TF]) Wait() {\n\tt.wg.Wait()\n\tclose(t.resultCh)\n\tt.pool.DeleteTask(t.taskID)\n}", "func (w *worker) assignUnqueuedTask(bq *InMemoryBuildQueue, t *task) {\n\tif w.currentTask != nil {\n\t\tpanic(\"Worker is already associated with a task\")\n\t}\n\tif t.currentWorker != nil {\n\t\tpanic(\"Task is already associated with a worker\")\n\t}\n\n\tt.registerQueuedStageFinished(bq)\n\tw.currentTask = t\n\tt.currentWorker = w\n\tt.retryCount = 0\n\tfor i := range t.operations {\n\t\ti.incrementExecutingWorkersCount()\n\t}\n\tw.clearLastInvocations()\n}", "func deleteOneTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\td, err := collection.DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Documento eliminado\", d.DeletedCount)\n}", "func (j *TrainingJob) updateTPRStatus() error {\n\t// If the status hasn't changed then there's no reason to update the TPR.\n\tif reflect.DeepEqual(j.job.Status, j.status) {\n\t\treturn nil\n\t}\n\n\tnewJob := j.job\n\tnewJob.Status = j.status\n\tnewJob, err := j.mxJobClient.Update(j.job.Metadata.Namespace, newJob)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tj.job = newJob\n\n\treturn nil\n}", "func (s *sched) del(t Task) {\n\ts.cache.Del(prefixTask + t.GetID())\n}", "func PostDeleteTrack(w http.ResponseWriter, r *http.Request) {\n\n\treqData := map[string]string{}\n\n\t// Parse JSON Data\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&reqData)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tt := reqData[\"track_id\"]\n\n\tcontext.tq.remove(t)\n\n\tw.WriteHeader(204)\n\tw.Write([]byte(`{\"status\":\"deleted\", \"track\":\"` + t + `\"}`))\n}", "func deleteOneTask(task string) {\n\tfmt.Println(task)\n\tid, _ := primitive.ObjectIDFromHex(task)\n\tfilter := bson.M{\"_id\": id}\n\t_, err := collection.DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Deleted task\", id)\n}", "func cleanupTaskDefinition(ctx context.Context, t *testing.T, c cocoa.ECSClient, out *ecs.RegisterTaskDefinitionOutput) {\n\tif out != nil && out.TaskDefinition != nil && out.TaskDefinition.TaskDefinitionArn != nil {\n\t\tout, err := c.DeregisterTaskDefinition(ctx, &ecs.DeregisterTaskDefinitionInput{\n\t\t\tTaskDefinition: out.TaskDefinition.TaskDefinitionArn,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\trequire.NotZero(t, out)\n\t}\n}", "func (m *kubeGenericRuntimeManager) SyncPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) {\n\t// Step 1: Compute sandbox and container changes.\n\tpodContainerChanges := m.computePodActions(ctx, pod, podStatus)\n\tklog.V(3).InfoS(\"computePodActions got for pod\", \"podActions\", podContainerChanges, \"pod\", klog.KObj(pod))\n\tif podContainerChanges.CreateSandbox {\n\t\tref, err := ref.GetReference(legacyscheme.Scheme, pod)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t}\n\t\tif podContainerChanges.SandboxID != \"\" {\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeNormal, events.SandboxChanged, \"Pod sandbox changed, it will be killed and re-created.\")\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"SyncPod received new pod, will create a sandbox for it\", \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n\n\t// Step 2: Kill the pod if the sandbox has changed.\n\tif podContainerChanges.KillPod {\n\t\tif podContainerChanges.CreateSandbox {\n\t\t\tklog.V(4).InfoS(\"Stopping PodSandbox for pod, will start new one\", \"pod\", klog.KObj(pod))\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Stopping PodSandbox for pod, because all other containers are dead\", \"pod\", klog.KObj(pod))\n\t\t}\n\n\t\tkillResult := m.killPodWithSyncResult(ctx, pod, kubecontainer.ConvertPodStatusToRunningPod(m.runtimeName, podStatus), nil)\n\t\tresult.AddPodSyncResult(killResult)\n\t\tif killResult.Error() != nil {\n\t\t\tklog.ErrorS(killResult.Error(), \"killPodWithSyncResult failed\")\n\t\t\treturn\n\t\t}\n\n\t\tif podContainerChanges.CreateSandbox {\n\t\t\tm.purgeInitContainers(ctx, pod, podStatus)\n\t\t}\n\t} else {\n\t\t// Step 3: kill any running containers in this pod which are not to keep.\n\t\tfor containerID, containerInfo := range podContainerChanges.ContainersToKill {\n\t\t\tklog.V(3).InfoS(\"Killing unwanted container for pod\", \"containerName\", containerInfo.name, \"containerID\", containerID, \"pod\", klog.KObj(pod))\n\t\t\tkillContainerResult := kubecontainer.NewSyncResult(kubecontainer.KillContainer, containerInfo.name)\n\t\t\tresult.AddSyncResult(killContainerResult)\n\t\t\tif err := m.killContainer(ctx, pod, containerID, containerInfo.name, containerInfo.message, containerInfo.reason, nil); err != nil {\n\t\t\t\tkillContainerResult.Fail(kubecontainer.ErrKillContainer, err.Error())\n\t\t\t\tklog.ErrorS(err, \"killContainer for pod failed\", \"containerName\", containerInfo.name, \"containerID\", containerID, \"pod\", klog.KObj(pod))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Keep terminated init containers fairly aggressively controlled\n\t// This is an optimization because container removals are typically handled\n\t// by container garbage collector.\n\tm.pruneInitContainersBeforeStart(ctx, pod, podStatus)\n\n\t// We pass the value of the PRIMARY podIP and list of podIPs down to\n\t// generatePodSandboxConfig and generateContainerConfig, which in turn\n\t// passes it to various other functions, in order to facilitate functionality\n\t// that requires this value (hosts file and downward API) and avoid races determining\n\t// the pod IP in cases where a container requires restart but the\n\t// podIP isn't in the status manager yet. The list of podIPs is used to\n\t// generate the hosts file.\n\t//\n\t// We default to the IPs in the passed-in pod status, and overwrite them if the\n\t// sandbox needs to be (re)started.\n\tvar podIPs []string\n\tif podStatus != nil {\n\t\tpodIPs = podStatus.IPs\n\t}\n\n\t// Step 4: Create a sandbox for the pod if necessary.\n\tpodSandboxID := podContainerChanges.SandboxID\n\tif podContainerChanges.CreateSandbox {\n\t\tvar msg string\n\t\tvar err error\n\n\t\tklog.V(4).InfoS(\"Creating PodSandbox for pod\", \"pod\", klog.KObj(pod))\n\t\tmetrics.StartedPodsTotal.Inc()\n\t\tcreateSandboxResult := kubecontainer.NewSyncResult(kubecontainer.CreatePodSandbox, format.Pod(pod))\n\t\tresult.AddSyncResult(createSandboxResult)\n\n\t\t// ConvertPodSysctlsVariableToDotsSeparator converts sysctl variable\n\t\t// in the Pod.Spec.SecurityContext.Sysctls slice into a dot as a separator.\n\t\t// runc uses the dot as the separator to verify whether the sysctl variable\n\t\t// is correct in a separate namespace, so when using the slash as the sysctl\n\t\t// variable separator, runc returns an error: \"sysctl is not in a separate kernel namespace\"\n\t\t// and the podSandBox cannot be successfully created. Therefore, before calling runc,\n\t\t// we need to convert the sysctl variable, the dot is used as a separator to separate the kernel namespace.\n\t\t// When runc supports slash as sysctl separator, this function can no longer be used.\n\t\tsysctl.ConvertPodSysctlsVariableToDotsSeparator(pod.Spec.SecurityContext)\n\n\t\t// Prepare resources allocated by the Dynammic Resource Allocation feature for the pod\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\t\tif err := m.runtimeHelper.PrepareDynamicResources(pod); err != nil {\n\t\t\t\tref, referr := ref.GetReference(legacyscheme.Scheme, pod)\n\t\t\t\tif referr != nil {\n\t\t\t\t\tklog.ErrorS(referr, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedPrepareDynamicResources, \"Failed to prepare dynamic resources: %v\", err)\n\t\t\t\tklog.ErrorS(err, \"Failed to prepare dynamic resources\", \"pod\", klog.KObj(pod))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tpodSandboxID, msg, err = m.createPodSandbox(ctx, pod, podContainerChanges.Attempt)\n\t\tif err != nil {\n\t\t\t// createPodSandbox can return an error from CNI, CSI,\n\t\t\t// or CRI if the Pod has been deleted while the POD is\n\t\t\t// being created. If the pod has been deleted then it's\n\t\t\t// not a real error.\n\t\t\t//\n\t\t\t// SyncPod can still be running when we get here, which\n\t\t\t// means the PodWorker has not acked the deletion.\n\t\t\tif m.podStateProvider.IsPodTerminationRequested(pod.UID) {\n\t\t\t\tklog.V(4).InfoS(\"Pod was deleted and sandbox failed to be created\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmetrics.StartedPodsErrorsTotal.Inc()\n\t\t\tcreateSandboxResult.Fail(kubecontainer.ErrCreatePodSandbox, msg)\n\t\t\tklog.ErrorS(err, \"CreatePodSandbox for pod failed\", \"pod\", klog.KObj(pod))\n\t\t\tref, referr := ref.GetReference(legacyscheme.Scheme, pod)\n\t\t\tif referr != nil {\n\t\t\t\tklog.ErrorS(referr, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedCreatePodSandBox, \"Failed to create pod sandbox: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).InfoS(\"Created PodSandbox for pod\", \"podSandboxID\", podSandboxID, \"pod\", klog.KObj(pod))\n\n\t\tresp, err := m.runtimeService.PodSandboxStatus(ctx, podSandboxID, false)\n\t\tif err != nil {\n\t\t\tref, referr := ref.GetReference(legacyscheme.Scheme, pod)\n\t\t\tif referr != nil {\n\t\t\t\tklog.ErrorS(referr, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedStatusPodSandBox, \"Unable to get pod sandbox status: %v\", err)\n\t\t\tklog.ErrorS(err, \"Failed to get pod sandbox status; Skipping pod\", \"pod\", klog.KObj(pod))\n\t\t\tresult.Fail(err)\n\t\t\treturn\n\t\t}\n\t\tif resp.GetStatus() == nil {\n\t\t\tresult.Fail(errors.New(\"pod sandbox status is nil\"))\n\t\t\treturn\n\t\t}\n\n\t\t// If we ever allow updating a pod from non-host-network to\n\t\t// host-network, we may use a stale IP.\n\t\tif !kubecontainer.IsHostNetworkPod(pod) {\n\t\t\t// Overwrite the podIPs passed in the pod status, since we just started the pod sandbox.\n\t\t\tpodIPs = m.determinePodSandboxIPs(pod.Namespace, pod.Name, resp.GetStatus())\n\t\t\tklog.V(4).InfoS(\"Determined the ip for pod after sandbox changed\", \"IPs\", podIPs, \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n\n\t// the start containers routines depend on pod ip(as in primary pod ip)\n\t// instead of trying to figure out if we have 0 < len(podIPs)\n\t// everytime, we short circuit it here\n\tpodIP := \"\"\n\tif len(podIPs) != 0 {\n\t\tpodIP = podIPs[0]\n\t}\n\n\t// Get podSandboxConfig for containers to start.\n\tconfigPodSandboxResult := kubecontainer.NewSyncResult(kubecontainer.ConfigPodSandbox, podSandboxID)\n\tresult.AddSyncResult(configPodSandboxResult)\n\tpodSandboxConfig, err := m.generatePodSandboxConfig(pod, podContainerChanges.Attempt)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"GeneratePodSandboxConfig for pod %q failed: %v\", format.Pod(pod), err)\n\t\tklog.ErrorS(err, \"GeneratePodSandboxConfig for pod failed\", \"pod\", klog.KObj(pod))\n\t\tconfigPodSandboxResult.Fail(kubecontainer.ErrConfigPodSandbox, message)\n\t\treturn\n\t}\n\n\t// Helper containing boilerplate common to starting all types of containers.\n\t// typeName is a description used to describe this type of container in log messages,\n\t// currently: \"container\", \"init container\" or \"ephemeral container\"\n\t// metricLabel is the label used to describe this type of container in monitoring metrics.\n\t// currently: \"container\", \"init_container\" or \"ephemeral_container\"\n\tstart := func(ctx context.Context, typeName, metricLabel string, spec *startSpec) error {\n\t\tstartContainerResult := kubecontainer.NewSyncResult(kubecontainer.StartContainer, spec.container.Name)\n\t\tresult.AddSyncResult(startContainerResult)\n\n\t\tisInBackOff, msg, err := m.doBackOff(pod, spec.container, podStatus, backOff)\n\t\tif isInBackOff {\n\t\t\tstartContainerResult.Fail(err, msg)\n\t\t\tklog.V(4).InfoS(\"Backing Off restarting container in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod))\n\t\t\treturn err\n\t\t}\n\n\t\tmetrics.StartedContainersTotal.WithLabelValues(metricLabel).Inc()\n\t\tif sc.HasWindowsHostProcessRequest(pod, spec.container) {\n\t\t\tmetrics.StartedHostProcessContainersTotal.WithLabelValues(metricLabel).Inc()\n\t\t}\n\t\tklog.V(4).InfoS(\"Creating container in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod))\n\t\t// NOTE (aramase) podIPs are populated for single stack and dual stack clusters. Send only podIPs.\n\t\tif msg, err := m.startContainer(ctx, podSandboxID, podSandboxConfig, spec, pod, podStatus, pullSecrets, podIP, podIPs); err != nil {\n\t\t\t// startContainer() returns well-defined error codes that have reasonable cardinality for metrics and are\n\t\t\t// useful to cluster administrators to distinguish \"server errors\" from \"user errors\".\n\t\t\tmetrics.StartedContainersErrorsTotal.WithLabelValues(metricLabel, err.Error()).Inc()\n\t\t\tif sc.HasWindowsHostProcessRequest(pod, spec.container) {\n\t\t\t\tmetrics.StartedHostProcessContainersErrorsTotal.WithLabelValues(metricLabel, err.Error()).Inc()\n\t\t\t}\n\t\t\tstartContainerResult.Fail(err, msg)\n\t\t\t// known errors that are logged in other places are logged at higher levels here to avoid\n\t\t\t// repetitive log spam\n\t\t\tswitch {\n\t\t\tcase err == images.ErrImagePullBackOff:\n\t\t\t\tklog.V(3).InfoS(\"Container start failed in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod), \"containerMessage\", msg, \"err\", err)\n\t\t\tdefault:\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%v %+v start failed in pod %v: %v: %s\", typeName, spec.container, format.Pod(pod), err, msg))\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// Step 5: start ephemeral containers\n\t// These are started \"prior\" to init containers to allow running ephemeral containers even when there\n\t// are errors starting an init container. In practice init containers will start first since ephemeral\n\t// containers cannot be specified on pod creation.\n\tfor _, idx := range podContainerChanges.EphemeralContainersToStart {\n\t\tstart(ctx, \"ephemeral container\", metrics.EphemeralContainer, ephemeralContainerStartSpec(&pod.Spec.EphemeralContainers[idx]))\n\t}\n\n\t// Step 6: start init containers.\n\tfor _, idx := range podContainerChanges.InitContainersToStart {\n\t\tcontainer := &pod.Spec.InitContainers[idx]\n\t\t// Start the next init container.\n\t\tif err := start(ctx, \"init container\", metrics.InitContainer, containerStartSpec(container)); err != nil {\n\t\t\tif types.IsRestartableInitContainer(container) {\n\t\t\t\tklog.V(4).InfoS(\"Failed to start the restartable init container for the pod, skipping\", \"initContainerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Failed to initialize the pod, as the init container failed to start, aborting\", \"initContainerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\treturn\n\t\t}\n\n\t\t// Successfully started the container; clear the entry in the failure\n\t\tklog.V(4).InfoS(\"Completed init container for pod\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t}\n\n\t// Step 7: For containers in podContainerChanges.ContainersToUpdate[CPU,Memory] list, invoke UpdateContainerResources\n\tif isInPlacePodVerticalScalingAllowed(pod) {\n\t\tif len(podContainerChanges.ContainersToUpdate) > 0 || podContainerChanges.UpdatePodResources {\n\t\t\tm.doPodResizeAction(pod, podStatus, podContainerChanges, result)\n\t\t}\n\t}\n\n\t// Step 8: start containers in podContainerChanges.ContainersToStart.\n\tfor _, idx := range podContainerChanges.ContainersToStart {\n\t\tstart(ctx, \"container\", metrics.Container, containerStartSpec(&pod.Spec.Containers[idx]))\n\t}\n\n\treturn\n}", "func (w *worker) updateTask(bq *InMemoryBuildQueue, scq *sizeClassQueue, workerID map[string]string, actionDigest *remoteexecution.Digest, preferBeingIdle bool) (*remoteworker.SynchronizeResponse, error) {\n\tif !w.isRunningCorrectTask(actionDigest) {\n\t\treturn w.getCurrentOrNextTask(nil, bq, scq, workerID, preferBeingIdle)\n\t}\n\t// The worker is doing fine. Allow it to continue with what it's\n\t// doing right now.\n\treturn &remoteworker.SynchronizeResponse{\n\t\tNextSynchronizationAt: bq.getNextSynchronizationAtDelay(),\n\t}, nil\n}", "func (t Task) watchPod(ctx context.Context, jobName string, namespace string) error {\n\tclientset, err := kubernetesclient.Client(t.kubectl.KubeContext)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting Kubernetes client: %w\", err)\n\t}\n\n\twatcher, err := clientset.CoreV1().Pods(namespace).Watch(ctx, v1.ListOptions{\n\t\tLabelSelector: fmt.Sprintf(\"job-name=%v\", jobName),\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting Kubernetes client: %w\", err)\n\t}\n\n\tfor event := range watcher.ResultChan() {\n\t\tpod, ok := event.Object.(*corev1.Pod)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif err := k8sjobutil.CheckIfPullImgErr(pod, t.Name()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func UndoTask(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"PUT\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tparams := mux.Vars(r)\n\tundoTask(params[\"id\"])\n\tjson.NewEncoder(w).Encode(params[\"id\"])\n}", "func KillTask(tid int) Errno {\n\t_, e := internal.Syscall1(KILLTASK, uintptr(tid))\n\treturn Errno(e)\n}", "func (w *Worker) handleTask() {\n\tvar handleTaskInterval = time.Second\n\tfailpoint.Inject(\"handleTaskInterval\", func(val failpoint.Value) {\n\t\tif milliseconds, ok := val.(int); ok {\n\t\t\thandleTaskInterval = time.Duration(milliseconds) * time.Millisecond\n\t\t\tw.l.Info(\"set handleTaskInterval\", zap.String(\"failpoint\", \"handleTaskInterval\"), zap.Int(\"value\", milliseconds))\n\t\t}\n\t})\n\tticker := time.NewTicker(handleTaskInterval)\n\tdefer ticker.Stop()\n\n\tretryCnt := 0\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.ctx.Done():\n\t\t\tw.l.Info(\"handle task process exits!\")\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tif w.closed.Get() == closedTrue {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\topLog := w.meta.PeekLog()\n\t\t\tif opLog == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tw.l.Info(\"start to execute operation\", zap.Reflect(\"oplog\", opLog))\n\n\t\t\tst := w.subTaskHolder.findSubTask(opLog.Task.Name)\n\t\t\tvar err error\n\t\t\tswitch opLog.Task.Op {\n\t\t\tcase pb.TaskOp_Start:\n\t\t\t\tif st != nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskExists.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif w.relayPurger.Purging() {\n\t\t\t\t\tif retryCnt < maxRetryCount {\n\t\t\t\t\t\tretryCnt++\n\t\t\t\t\t\tw.l.Warn(\"relay log purger is purging, cannot start subtask, would try again later\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t\t\tcontinue Loop\n\t\t\t\t\t}\n\n\t\t\t\t\tretryCnt = 0\n\t\t\t\t\terr = terror.ErrWorkerRelayIsPurging.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tretryCnt = 0\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar cfgDecrypted *config.SubTaskConfig\n\t\t\t\tcfgDecrypted, err = taskCfg.DecryptPassword()\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = terror.WithClass(err, terror.ClassDMWorker)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"started sub task\", zap.Stringer(\"config\", cfgDecrypted))\n\t\t\t\tst = NewSubTask(cfgDecrypted)\n\t\t\t\tw.subTaskHolder.recordSubTask(st)\n\t\t\t\tst.Run()\n\n\t\t\tcase pb.TaskOp_Update:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttaskCfg := new(config.SubTaskConfig)\n\t\t\t\tif err1 := taskCfg.Decode(string(opLog.Task.Task)); err1 != nil {\n\t\t\t\t\terr = terror.Annotate(err1, \"decode subtask config error in handleTask\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"updated sub task\", zap.String(\"task\", opLog.Task.Name), zap.Stringer(\"new config\", taskCfg))\n\t\t\t\terr = st.Update(taskCfg)\n\t\t\tcase pb.TaskOp_Stop:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"stop sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\tst.Close()\n\t\t\t\tw.subTaskHolder.removeSubTask(opLog.Task.Name)\n\t\t\tcase pb.TaskOp_Pause:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"pause sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Pause()\n\t\t\tcase pb.TaskOp_Resume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\tcase pb.TaskOp_AutoResume:\n\t\t\t\tif st == nil {\n\t\t\t\t\terr = terror.ErrWorkerSubTaskNotFound.Generate(opLog.Task.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw.l.Info(\"auto_resume sub task\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\terr = st.Resume()\n\t\t\t}\n\n\t\t\tw.l.Info(\"end to execute operation\", zap.Int64(\"oplog ID\", opLog.Id), log.ShortError(err))\n\n\t\t\tif err != nil {\n\t\t\t\topLog.Message = err.Error()\n\t\t\t} else {\n\t\t\t\topLog.Task.Stage = st.Stage()\n\t\t\t\topLog.Success = true\n\t\t\t}\n\n\t\t\t// fill current task config\n\t\t\tif len(opLog.Task.Task) == 0 {\n\t\t\t\ttm := w.meta.GetTask(opLog.Task.Name)\n\t\t\t\tif tm == nil {\n\t\t\t\t\tw.l.Warn(\"task meta not found\", zap.String(\"task\", opLog.Task.Name))\n\t\t\t\t} else {\n\t\t\t\t\topLog.Task.Task = append([]byte{}, tm.Task...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr = w.meta.MarkOperation(opLog)\n\t\t\tif err != nil {\n\t\t\t\tw.l.Error(\"fail to mark subtask operation\", zap.Reflect(\"oplog\", opLog))\n\t\t\t}\n\t\t}\n\t}\n}", "func (t *TimeTask) DeleteTask(task *RawTask) {\n\tt.deleteChan <- task\n}", "func UndoTask(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"PUT\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tparams := mux.Vars(r)\n\tundoTask(params[\"id\"])\n\tjson.NewEncoder(w).Encode(params[\"id\"])\n}", "func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.removePodTask(driver, taskId.GetValue(), messages.TaskKilled, mesos.TaskState_TASK_KILLED)\n}", "func (p *PruneTask) ClearTimeout() {}", "func (m *TaskManager) ResetOverdueTask() {\n\tm.WIPTable.Range(func(key, value interface{}) bool {\n\t\tif t := value.(*Task); t.IsTimeout() {\n\t\t\tif t.LifeCycle != WIP {\n\t\t\t\tlog.Logger.Fatalf(\"the LifeCycle of the task under check is %d, but `WIP` is expected\", t.LifeCycle)\n\t\t\t}\n\t\t\tt.LifeCycle = READY\n\t\t\tm.ReadyQueue <- t\n\t\t\tm.WIPTable.Delete(key)\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\t\"ID\": t.ID,\n\t\t\t\t\"TaskType\": t.TaskType,\n\t\t\t}).Warn(\"reset an overdue task\")\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}", "func (task *Task) Kill() {\n\tif task.Config.CmdString != \"\" && task.Command.Started && !task.Command.Complete {\n\t\tsyscall.Kill(-task.Command.Cmd.Process.Pid, syscall.SIGKILL)\n\t}\n\n\tfor _, subTask := range task.Children {\n\t\tif subTask.Config.CmdString != \"\" && subTask.Command.Started && !subTask.Command.Complete {\n\t\t\tsyscall.Kill(-subTask.Command.Cmd.Process.Pid, syscall.SIGKILL)\n\t\t}\n\t}\n\n}", "func CleanupNonReadyPod(ctx context.Context, client crc.Client, statefulSet *appsv1.StatefulSet, index int32) error {\n\tctxlog.Debug(ctx, \"Cleaning up non ready pod for StatefulSet \", statefulSet.Namespace, \"/\", statefulSet.Name, \"-\", index)\n\tpod, ready, err := getPodWithIndex(ctx, client, statefulSet, index)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ready || pod == nil {\n\t\treturn nil\n\t}\n\tctxlog.Debug(ctx, \"Deleting pod \", pod.Name)\n\tif err = client.Delete(ctx, pod); err != nil {\n\t\tctxlog.Error(ctx, \"Error deleting non-ready pod \", err)\n\t}\n\treturn err\n}", "func (c *Client) TerminateTask(guid string) error {\n\treq := c.NewRequest(\"PUT\", fmt.Sprintf(\"/v3/tasks/%s/cancel\", guid))\n\tresp, err := c.DoRequest(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error terminating task\")\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 202 {\n\t\treturn errors.Wrapf(err, \"Failed terminating task, response status code %d\", resp.StatusCode)\n\t}\n\treturn nil\n}", "func (t *Task) fail() {\n\tif t.Retry >= t.tasker.Retry() && t.tasker.Retry() != -1 {\n\t\tt.Failed = time.Now()\n\t\tt.Closed = true\n\t} else {\n\t\tt.Retry++\n\t}\n\n\tt.Owner = data.EmptyKey //throw it back in the queue for processing by any available task runner\n\n\terr := data.TaskUpdate(t, t.Key)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"taskKey\": t.Key,\n\t\t\t\"type\": t.Type,\n\t\t}).Errorf(\"An error occured when updating a task for failure: %s\", err)\n\t}\n}", "func (tr *TaskRunner) restartImpl(ctx context.Context, event *structs.TaskEvent, failure bool) error {\n\n\t// Check if the task is able to restart based on its state and the type of\n\t// restart event that was triggered.\n\ttaskState := tr.TaskState()\n\tif taskState == nil {\n\t\treturn ErrTaskNotRunning\n\t}\n\n\t// Emit the event since it may take a long time to kill\n\ttr.EmitEvent(event)\n\n\t// Tell the restart tracker that a restart triggered the exit\n\ttr.restartTracker.SetRestartTriggered(failure)\n\n\t// Signal a restart to unblock tasks that are in the \"dead\" state, but\n\t// don't block since the channel is buffered. Only one signal is enough to\n\t// notify the tr.Run() loop.\n\t// The channel must be signaled after SetRestartTriggered is called so the\n\t// tr.Run() loop runs again.\n\tif taskState.State == structs.TaskStateDead {\n\t\tselect {\n\t\tcase tr.restartCh <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\n\t// Grab the handle to see if the task is still running and needs to be\n\t// killed.\n\thandle := tr.getDriverHandle()\n\tif handle == nil {\n\t\treturn nil\n\t}\n\n\t// Run the pre-kill hooks prior to restarting the task\n\ttr.preKill()\n\n\t// Grab a handle to the wait channel that will timeout with context cancelation\n\t// _before_ killing the task.\n\twaitCh, err := handle.WaitCh(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Kill the task using an exponential backoff in-case of failures.\n\tif _, err := tr.killTask(handle, waitCh); err != nil {\n\t\t// We couldn't successfully destroy the resource created.\n\t\ttr.logger.Error(\"failed to kill task. Resources may have been leaked\", \"error\", err)\n\t}\n\n\tselect {\n\tcase <-waitCh:\n\tcase <-ctx.Done():\n\t}\n\treturn nil\n}", "func (c Control) ServeDeleteTask(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tc.Config.Lock()\n\tdefer c.Config.Unlock()\n\tindex, task := c.findTaskById(id)\n\tif task == nil {\n\t\thttp.Error(w, \"Invalid task ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttask.StopLoop()\n\tfor i := index; i < len(c.Config.Tasks)-1; i++ {\n\t\tc.Config.Tasks[i] = c.Config.Tasks[i+1]\n\t}\n\tc.Config.Tasks = c.Config.Tasks[0 : len(c.Config.Tasks)-1]\n\tc.Config.Save()\n\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n}", "func (md *ManagementNode) SetTaskState(ctx context.Context, task *pb.Task) (*pb.Empty, error) {\n\n\t// TBD: check of existed object might be needed\n\t// might be dead before state change\n\n\tlog.Infof(\"SetTaskState with params %+v\", task)\n\n\tif err := md.StopTaskDeadTimeout(ctx, task.Id); err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t\treturn nil, err\n\t}\n\n\tif err := md.SetToDb(ctx, task, EtcdTaskPrefix+task.Id); err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t\treturn nil, err\n\t}\n\n\treturn &pb.Empty{}, nil\n}", "func deleteTask(w http.ResponseWriter, r *http.Request) {\r\n\tvars := mux.Vars(r) //copio del anterior porque el metodo de busqueda es el mismo\r\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\r\n\tif err != nil {\r\n\t\tfmt.Fprintf(w, \"Invalid ID\")\r\n\t\treturn\r\n\t}\r\n\tfor i, task := range tasks { //misma busqueda que en el caso anterior\r\n\t\tif task.ID == taskID {\r\n\t\t\ttasks = append(tasks[:i], tasks[i+1:]...) //en realidad no borra sino que arma un slice con los elementos previos y posteriores al indice dado\r\n\t\t\tfmt.Fprintf(w, \"The task with ID: %v has been successfully removed.\", taskID)\r\n\t\t}\r\n\t}\r\n}", "func (c Control) ServeEditTask(w http.ResponseWriter, r *http.Request) {\n\tid, err := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\tc.Config.Lock()\n\t\tdefer c.Config.Unlock()\n\n\t\t_, task := c.findTaskById(id)\n\t\tif task == nil {\n\t\t\thttp.Error(w, \"Invalid task ID\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\toldStatus := task.Status()\n\t\toldEnv := task.Env\n\t\ttask.Env = nil\n\t\ttask.StopLoop()\n\t\tif err := json.Unmarshal([]byte(r.PostFormValue(\"task\")), task); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\ttask.Env = oldEnv\n\t\t\ttask.StartLoop()\n\t\t\tif oldStatus != TaskStatusStopped {\n\t\t\t\ttask.Start()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tc.Config.Save()\n\t\ttask.StartLoop()\n\t\tif oldStatus != TaskStatusStopped {\n\t\t\ttask.Start()\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tc.Config.RLock()\n\tdefer c.Config.RUnlock()\n\tindex, task := c.findTaskById(id)\n\tif task == nil {\n\t\thttp.Error(w, \"Invalid task ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(c.Config.Tasks[index])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tserveTemplate(w, r, \"edit_task\", map[string]interface{}{\"taskData\": string(data),\n\t\t\"id\": strconv.FormatInt(id, 10)})\n}", "func (tdl *toDoList) markUnDone(fileName string, taskId int) {\n\tif taskId > len(*tdl)-1 || taskId < 0 {\n\t\tfmt.Println(\"Error: Invalid task id. Try again\")\n\t\tos.Exit(1)\n\t}\n\tif len(*tdl) == 0 {\n\t\tfmt.Println(\"To Do List empty\\nAdd new task\")\n\t\treturn\n\t}\n\tfor i, task := range *tdl {\n\t\tif i == taskId {\n\t\t\tif task.done == \"done\" {\n\t\t\t\ttask.done = \"undone\"\n\t\t\t\t(*tdl)[i] = task\n\t\t\t\terr := toDoListToFile(fileName, *tdl)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Error:\", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"'\" + task.taskName + \"' marked as incomplete\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"'\" + task.taskName + \"' has not been done yet. Nothing to do\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (k *KubernetesExecutor) launchTask(driver bindings.ExecutorDriver, taskId string, pod *api.Pod) {\n\tdeleteTask := func() {\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tdelete(k.tasks, taskId)\n\t\tk.resetSuicideWatch(driver)\n\t}\n\n\t// TODO(k8s): use Pods interface for binding once clusters are upgraded\n\t// return b.Pods(binding.Namespace).Bind(binding)\n\tif pod.Spec.NodeName == \"\" {\n\t\t//HACK(jdef): cloned binding construction from k8s plugin/pkg/scheduler/scheduler.go\n\t\tbinding := &api.Binding{\n\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t\tName: pod.Name,\n\t\t\t\tAnnotations: make(map[string]string),\n\t\t\t},\n\t\t\tTarget: api.ObjectReference{\n\t\t\t\tKind: \"Node\",\n\t\t\t\tName: pod.Annotations[meta.BindingHostKey],\n\t\t\t},\n\t\t}\n\n\t\t// forward the annotations that the scheduler wants to apply\n\t\tfor k, v := range pod.Annotations {\n\t\t\tbinding.Annotations[k] = v\n\t\t}\n\n\t\t// create binding on apiserver\n\t\tlog.Infof(\"Binding '%v/%v' to '%v' with annotations %+v...\", pod.Namespace, pod.Name, binding.Target.Name, binding.Annotations)\n\t\tctx := api.WithNamespace(api.NewContext(), binding.Namespace)\n\t\terr := k.client.Post().Namespace(api.NamespaceValue(ctx)).Resource(\"bindings\").Body(binding).Do().Error()\n\t\tif err != nil {\n\t\t\tdeleteTask()\n\t\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\t\tmessages.CreateBindingFailure))\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// post annotations update to apiserver\n\t\tpatch := struct {\n\t\t\tMetadata struct {\n\t\t\t\tAnnotations map[string]string `json:\"annotations\"`\n\t\t\t} `json:\"metadata\"`\n\t\t}{}\n\t\tpatch.Metadata.Annotations = pod.Annotations\n\t\tpatchJson, _ := json.Marshal(patch)\n\t\tlog.V(4).Infof(\"Patching annotations %v of pod %v/%v: %v\", pod.Annotations, pod.Namespace, pod.Name, string(patchJson))\n\t\terr := k.client.Patch(api.MergePatchType).RequestURI(pod.SelfLink).Body(patchJson).Do().Error()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error updating annotations of ready-to-launch pod %v/%v: %v\", pod.Namespace, pod.Name, err)\n\t\t\tdeleteTask()\n\t\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\t\tmessages.AnnotationUpdateFailure))\n\t\t\treturn\n\t\t}\n\t}\n\n\tpodFullName := container.GetPodFullName(pod)\n\n\t// allow a recently failed-over scheduler the chance to recover the task/pod binding:\n\t// it may have failed and recovered before the apiserver is able to report the updated\n\t// binding information. replays of this status event will signal to the scheduler that\n\t// the apiserver should be up-to-date.\n\tdata, err := json.Marshal(api.PodStatusResult{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: podFullName,\n\t\t\tSelfLink: \"/podstatusresult\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tdeleteTask()\n\t\tlog.Errorf(\"failed to marshal pod status result: %v\", err)\n\t\tk.sendStatus(driver, newStatus(mutil.NewTaskID(taskId), mesos.TaskState_TASK_FAILED,\n\t\t\terr.Error()))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// Add the task.\n\ttask, found := k.tasks[taskId]\n\tif !found {\n\t\tlog.V(1).Infof(\"task %v not found, probably killed: aborting launch, reporting lost\", taskId)\n\t\tk.reportLostTask(driver, taskId, messages.LaunchTaskFailed)\n\t\treturn\n\t}\n\n\t//TODO(jdef) check for duplicate pod name, if found send TASK_ERROR\n\n\t// from here on, we need to delete containers associated with the task\n\t// upon it going into a terminal state\n\ttask.podName = podFullName\n\tk.pods[podFullName] = pod\n\n\t// send the new pod to the kubelet which will spin it up\n\tupdate := kubelet.PodUpdate{\n\t\tOp: kubelet.ADD,\n\t\tPods: []*api.Pod{pod},\n\t}\n\tk.updateChan <- update\n\n\tstatusUpdate := &mesos.TaskStatus{\n\t\tTaskId: mutil.NewTaskID(taskId),\n\t\tState: mesos.TaskState_TASK_STARTING.Enum(),\n\t\tMessage: proto.String(messages.CreateBindingSuccess),\n\t\tData: data,\n\t}\n\tk.sendStatus(driver, statusUpdate)\n\n\t// Delay reporting 'task running' until container is up.\n\tpsf := podStatusFunc(func() (*api.PodStatus, error) {\n\t\tstatus, err := k.podStatusFunc(k.kl, pod)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstatus.Phase = kubelet.GetPhase(&pod.Spec, status.ContainerStatuses)\n\t\thostIP, err := k.kl.GetHostIP()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Cannot get host IP: %v\", err)\n\t\t} else {\n\t\t\tstatus.HostIP = hostIP.String()\n\t\t}\n\t\treturn status, nil\n\t})\n\n\tgo k._launchTask(driver, taskId, podFullName, psf)\n}", "func checkPodsFromTask(cluster *imec_db.DB_INFRASTRUCTURE_CLUSTER, namespace string, id string, expectedReplicas int) (string, map[string]interface{}, error) {\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Getting pods ...\")\n\n\t// get pods from task\n\t_, result, err := common.HTTPGETStruct(\n\t\turls.GetPathKubernetesPodsApp(cluster, namespace, id),\n\t\t//cfg.Config.Clusters[clusterIndex].KubernetesEndPoint+\"/api/v1/namespaces/\"+namespace+\"/pods?labelSelector=app=\"+id,\n\t\ttrue)\n\tif err != nil {\n\t\tlog.Error(pathLOG+\"COMPSs [checkPodsFromTask] ERROR\", err)\n\t\treturn \"error\", nil, err\n\t}\n\n\t// items\n\titems := result[\"items\"].([]interface{})\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Retrieved pods = \" + strconv.Itoa(len(items)))\n\tlog.Println(pathLOG + \"COMPSs [checkPodsFromTask] Expected pods = \" + strconv.Itoa(expectedReplicas))\n\n\tif len(items) == expectedReplicas {\n\t\treturn \"ready\", result, err\n\t}\n\n\treturn \"not-ready\", result, err\n}", "func DeleteTask(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprint(w, \"DeleteTask\\n\")\n}", "func deleteTask(w http.ResponseWriter, r *http.Request){\n\t//definimos variable de vars que devuelve las variables de ruta\n\tvars := mux.Vars(r)\n\n\ttaskID, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil{\n\t\tfmt.Fprintf(w, \"Invalid ID\")\n\t\treturn\n\t}\n\n\t//Se elimina la task a la lista, guardando todas las que estan hasta su indice, y la que le sigue en adelante.\n\tfor i, task := range tasks {\n\t\tif task.ID == taskID {\n\t\t\ttasks = append(tasks[:i], tasks[i + 1:] ...)\n\t\t\tfmt.Fprintf(w, \"The task with ID %v has been removed succesfully\", taskID)\n\t\t}\n\t}\n}", "func (s *taskService) SetTaskStatus(c context.Context, typ int, date string, err error) (int64, error) {\n\tif err != nil {\n\t\treturn s.setTaskFail(c, typ, date, err.Error())\n\t}\n\treturn s.setTaskSuccess(c, typ, date, \"success\")\n}", "func (w *WaitTask) startInner(taskContext *TaskContext) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\tklog.V(3).Infof(\"wait task progress: %d/%d\", 0, len(w.Ids))\n\n\tpending := object.ObjMetadataSet{}\n\tfor _, id := range w.Ids {\n\t\tswitch {\n\t\tcase w.skipped(taskContext, id):\n\t\t\terr := taskContext.InventoryManager().SetSkippedReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as skipped reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSkipped)\n\t\tcase w.changedUID(taskContext, id):\n\t\t\t// replaced\n\t\t\tw.handleChangedUID(taskContext, id)\n\t\tcase w.reconciledByID(taskContext, id):\n\t\t\terr := taskContext.InventoryManager().SetSuccessfulReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as successful reconcile: %v\", err)\n\t\t\t}\n\t\t\tw.sendEvent(taskContext, id, event.ReconcileSuccessful)\n\t\tdefault:\n\t\t\terr := taskContext.InventoryManager().SetPendingReconcile(id)\n\t\t\tif err != nil {\n\t\t\t\t// Object never applied or deleted!\n\t\t\t\tklog.Errorf(\"Failed to mark object as pending reconcile: %v\", err)\n\t\t\t}\n\t\t\tpending = append(pending, id)\n\t\t\tw.sendEvent(taskContext, id, event.ReconcilePending)\n\t\t}\n\t}\n\tw.pending = pending\n\n\tklog.V(3).Infof(\"wait task progress: %d/%d\", len(w.Ids)-len(w.pending), len(w.Ids))\n\n\tif len(pending) == 0 {\n\t\t// all reconciled - clear pending and exit\n\t\tklog.V(3).Infof(\"all objects reconciled or skipped (name: %q)\", w.TaskName)\n\t\tw.cancelFunc()\n\t}\n}", "func (m *Master) finishTask(args *Args) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif m.status == MapStage {\n\t\tdelete(m.mapInProgress, args.TaskId)\n\t\tm.mapFinished++\n\t\tif m.mapFinished == len(m.mapTasks) {\n\t\t\tm.status = ReduceStage\n\t\t}\n\t\tfmt.Println(\"finished 1 map task\")\n\t} else if m.status == ReduceStage {\n\t\tdelete(m.reduceInProgress, args.TaskId)\n\t\tm.reduceFinished++\n\t\tif m.reduceFinished == m.reduceTasks {\n\t\t\tm.status = FinishedStage\n\t\t}\n\t\tm.deleteIntermediates(args.TaskId)\n\t\tfmt.Println(\"finished 1 reduce task\")\n\t}\n}", "func testUpdateTaskWithRetriesSimple(t sktest.TestingT, db TaskDB) {\n\tctx := context.Background()\n\tbegin := time.Now()\n\n\t// Create new task t1.\n\tt1 := types.MakeTestTask(time.Time{}, []string{\"a\", \"b\", \"c\", \"d\"})\n\trequire.NoError(t, db.AssignId(ctx, t1))\n\tt1.Created = time.Now().Add(TS_RESOLUTION)\n\trequire.NoError(t, db.PutTask(ctx, t1))\n\n\t// Update t1.\n\tt1Updated, err := UpdateTaskWithRetries(ctx, db, t1.Id, func(task *types.Task) error {\n\t\ttask.Status = types.TASK_STATUS_RUNNING\n\t\treturn nil\n\t})\n\trequire.NoError(t, err)\n\trequire.Equal(t, t1.Id, t1Updated.Id)\n\trequire.Equal(t, types.TASK_STATUS_RUNNING, t1Updated.Status)\n\trequire.NotEqual(t, t1.DbModified, t1Updated.DbModified)\n\n\t// Check that return value matches what's in the DB.\n\tt1Again, err := db.GetTaskById(ctx, t1.Id)\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, t1Again, t1Updated)\n\n\t// Check no extra tasks in the TaskDB.\n\ttasks, err := db.GetTasksFromDateRange(ctx, begin, time.Now().Add(2*TS_RESOLUTION), \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(tasks))\n\trequire.Equal(t, t1.Id, tasks[0].Id)\n}", "func UndoTask(c *gin.Context) {\n\ttask := c.Param(\"id\")\n\tfmt.Println(task)\n\tundoTask(task)\n\tc.JSON(http.StatusOK, task)\n}", "func (d *dispatcher) scheduleTask(taskID int64) {\n\tticker := time.NewTicker(checkTaskFinishedInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-d.ctx.Done():\n\t\t\tlogutil.BgLogger().Info(\"schedule task exits\", zap.Int64(\"task ID\", taskID), zap.Error(d.ctx.Err()))\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tstepIsFinished, errs := d.monitorTask(taskID)\n\t\t\tfailpoint.Inject(\"cancelTaskAfterMonitorTask\", func(val failpoint.Value) {\n\t\t\t\tif val.(bool) && d.task.State == proto.TaskStateRunning {\n\t\t\t\t\terr := d.taskMgr.CancelGlobalTask(taskID)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogutil.BgLogger().Error(\"cancel task failed\", zap.Error(err))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t// The global task isn't finished and not failed.\n\t\t\tif !stepIsFinished && len(errs) == 0 {\n\t\t\t\tGetTaskFlowHandle(d.task.Type).OnTicker(d.ctx, d.task)\n\t\t\t\tlogutil.BgLogger().Debug(\"schedule task, this task keeps current state\",\n\t\t\t\t\tzap.Int64(\"task-id\", d.task.ID), zap.String(\"state\", d.task.State))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\terr := d.processFlow(d.task, errs)\n\t\t\tif err == nil && d.task.IsFinished() {\n\t\t\t\tlogutil.BgLogger().Info(\"schedule task, task is finished\",\n\t\t\t\t\tzap.Int64(\"task-id\", d.task.ID), zap.String(\"state\", d.task.State))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfailpoint.Inject(\"mockOwnerChange\", func(val failpoint.Value) {\n\t\t\tif val.(bool) {\n\t\t\t\tlogutil.BgLogger().Info(\"mockOwnerChange called\")\n\t\t\t\tMockOwnerChange()\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t})\n\t}\n}" ]
[ "0.59660363", "0.5913115", "0.58440596", "0.584174", "0.5816163", "0.57812667", "0.57751364", "0.5666499", "0.5642281", "0.5642281", "0.54600894", "0.54341114", "0.5352631", "0.5351886", "0.53392446", "0.5282333", "0.5256723", "0.5238282", "0.52283925", "0.5227994", "0.51916224", "0.51603806", "0.5136679", "0.513294", "0.5128508", "0.5117613", "0.51070124", "0.50986505", "0.50885296", "0.5062257", "0.5060039", "0.5050445", "0.50484025", "0.5043977", "0.5028562", "0.49893385", "0.49821755", "0.49772018", "0.49631006", "0.49567986", "0.4942781", "0.4923143", "0.49192208", "0.49187103", "0.49166077", "0.48873952", "0.48818952", "0.48774025", "0.4875064", "0.48590082", "0.48565736", "0.48542508", "0.48467016", "0.48350564", "0.48287714", "0.48286098", "0.48211363", "0.4813177", "0.4809358", "0.4806541", "0.48056352", "0.4783641", "0.47791928", "0.47450066", "0.4744943", "0.47382239", "0.4736555", "0.4735594", "0.47279954", "0.47261766", "0.47200763", "0.4712037", "0.47023624", "0.46991366", "0.468497", "0.4680939", "0.46800825", "0.4677325", "0.46744683", "0.46653312", "0.466172", "0.4658729", "0.46521467", "0.4640133", "0.46369788", "0.46297863", "0.4622921", "0.46206725", "0.46130255", "0.4609747", "0.46037388", "0.45974523", "0.45917848", "0.45911422", "0.45869806", "0.45867175", "0.45838654", "0.45834035", "0.457442", "0.45655814" ]
0.5875251
2
FrameworkMessage is called when the framework sends some message to the executor
func (k *KubernetesExecutor) FrameworkMessage(driver bindings.ExecutorDriver, message string) { if k.isDone() { return } if !k.isConnected() { log.Warningf("Ignore framework message because the executor is disconnected\n") return } log.Infof("Receives message from framework %v\n", message) //TODO(jdef) master reported a lost task, reconcile this! @see scheduler.go:handleTaskLost if strings.HasPrefix(message, messages.TaskLost+":") { taskId := message[len(messages.TaskLost)+1:] if taskId != "" { // clean up pod state k.lock.Lock() defer k.lock.Unlock() k.reportLostTask(driver, taskId, messages.TaskLostAck) } } switch message { case messages.Kamikaze: k.attemptSuicide(driver, nil) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k *KubernetesScheduler) FrameworkMessage(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, message string) {\n\tlog.Infof(\"Received messages from executor %v of slave %v, %v\\n\", executorId, slaveId, message)\n}", "func (k *KubernetesExecutor) FrameworkMessage(driver bindings.ExecutorDriver, message string) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tif !k.isConnected() {\n\t\tlog.Warningf(\"Ignore framework message because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tlog.Infof(\"Receives message from framework %v\\n\", message)\n\t//TODO(jdef) master reported a lost task, reconcile this! @see scheduler.go:handleTaskLost\n\tif strings.HasPrefix(\"task-lost:\", message) && len(message) > 10 {\n\t\ttaskId := message[10:]\n\t\tif taskId != \"\" {\n\t\t\t// clean up pod state\n\t\t\tk.reportLostTask(driver, taskId, messages.TaskLostAck)\n\t\t}\n\t}\n}", "func (driver *MesosExecutorDriver) SendFrameworkMessage(data string) (mesosproto.Status, error) {\n\tlog.Infoln(\"Send framework message\")\n\n\tdriver.mutex.Lock()\n\tdefer driver.mutex.Unlock()\n\n\tif driver.status != mesosproto.Status_DRIVER_RUNNING {\n\t\treturn driver.status, nil\n\t}\n\tmessage := &mesosproto.ExecutorToFrameworkMessage{\n\t\tSlaveId: driver.slaveID,\n\t\tFrameworkId: driver.frameworkID,\n\t\tExecutorId: driver.executorID,\n\t\tData: []byte(data),\n\t}\n\t// Send the message.\n\tif err := driver.messenger.Send(driver.slaveUPID, message); err != nil {\n\t\tlog.Errorf(\"Failed to send %v: %v\\n\")\n\t\treturn driver.status, err\n\t}\n\treturn driver.status, nil\n}", "func registeredCB(\n ptr unsafe.Pointer,\n frameworkMessage *C.ProtobufObj,\n masterMessage *C.ProtobufObj) {\n if (ptr != nil) {\n var driver *SchedulerDriver = (*SchedulerDriver)(ptr)\n\n if (driver.Scheduler.Registered == nil) {\n return\n }\n\n frameworkData := C.GoBytes(\n frameworkMessage.data,\n C.int(frameworkMessage.size))\n\n var frameworkId FrameworkID\n err := proto.Unmarshal(frameworkData, &frameworkId); if err != nil {\n return\n }\n\n masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))\n var masterInfo MasterInfo\n err = proto.Unmarshal(masterData, &masterInfo); if err != nil {\n return\n }\n\n driver.Scheduler.Registered(driver, frameworkId, masterInfo)\n }\n}", "func (w *BaseWebsocketClient) OnWsMessage(payload []byte, isBinary bool) {}", "func (*GenericFramework) NewMessage(ctx *MessageContext) {}", "func (this *IoHandlerImp) MessageReceived(filter *IoFilter, obj BaseObject) {\n}", "func (f *Handler) dispatch(msg *provisioners.Message) error {\n\terr := f.dispatcher.DispatchMessage(msg, f.destination, \"\", provisioners.DispatchDefaults{})\n\tif err != nil {\n\t\tf.logger.Error(\"Error dispatching message\", zap.String(\"destination\", f.destination))\n\t}\n\treturn err\n}", "func processMessage(q *sqs.Queue, m sqs.Message, wo work_order.WorkOrder, wg *sync.WaitGroup) {\n logger.Debug(\"Starting process on %d from '%s'\", wo.Id, m.MessageId)\n\n // start heartbeat\n beat := heartbeat.Start(q, &m)\n \n // execute the work\n err := wo.Execute()\n if err != nil {\n logger.Error(\"Error executing: %d - %v\", wo.Id, err)\n }\n\n // send response back to devops-web\n wo.Report()\n\n // stop the heartbeat\n beat.Stop()\n\n // delete message\n logger.Debug(\"Deleting message: %s\", m.MessageId)\n _, err = q.DeleteMessage(&m)\n if err != nil {\n logger.Error(\"ERROR: Couldn't delete message: %s - %v\", m.MessageId, err)\n }\n\n // exit this goroutine\n wg.Done()\n}", "func (f *Handler) dispatch(msg *provisioners.Message) error {\n\tf.logger.Info(\"Message to be sent = \", zap.Any(\"msg\", msg))\n\t f.logger.Info(\"Message Payload\", zap.Any(\"payload\", string(msg.Payload[:])))\n\t\n\t jStr := string(msg.Payload[:])\n\t fmt.Println(jStr)\n \n\t type Payload struct {\n\t\t Id string `json:\"id\"`\n\t\t Data string `json:\"data\"`\n\t }\n\t \n\t var payload Payload\n \n\t json.Unmarshal([]byte(jStr), &payload)\n\t fmt.Printf(\"%+v\\n\", payload.Data)\n\t dataDec, _ := b64.StdEncoding.DecodeString(payload.Data)\n\t fmt.Printf(\"%+v\\n\", string(dataDec))\n\t \n\t type Data struct {\n\t\t Source string `json:\"source\"`\n\t\t Type string `json:\"type\"`\n\t }\n\t \n\t var data Data\n\t \n\t \n\t json.Unmarshal([]byte(string(dataDec)), &data)\n\t fmt.Printf(\"%+v\\n\", data)\n\t var destination = f.destination\n\t if data.Source == \"GITHUB\" {\n\t\tdestination = getRequiredEnv(\"GITHUB_CHANNEL_URL\")\n\t } else if data.Source == \"FRESHBOOKS\" {\n\t\t destination = getRequiredEnv(\"FRESHBOOKS_CHANNEL_URL\")\n\t } else {\n\t\t destination = getRequiredEnv(\"COMMON_CHANNEL_URL\")\n\t }\n\t fmt.Printf(\"%+v\\n\", destination)\n\n\t err := f.dispatcher.DispatchMessage(msg, destination, \"\", provisioners.DispatchDefaults{})\n\t if err != nil {\n\t\t f.logger.Error(\"Error dispatching message\", zap.String(\"destination\", destination))\n\t\t f.logger.Error(\"Error received\", zap.Error(err))\n\t }\n\t return err\n }", "func (object *MQMessageHandler) OnMQMessage(raw []byte, offset int64) {\n}", "func (f *fakeDiskUpdateWatchServer) SendMsg(m interface{}) error { return nil }", "func (b *Bot) dispatchMessage(s *Server, msg *irc.IrcMessage) {\n\tendpoint := createServerEndpoint(s)\n\tb.dispatcher.Dispatch(msg, endpoint)\n\ts.dispatcher.Dispatch(msg, endpoint)\n}", "func (b *Bus) dispatchMessage(msg *Message) {\n\tb.messageHandler[msg.Mtype](msg.Addr, msg.Msg)\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 (worker *Worker) processMessage(d *amqp.Delivery) {\n\tsignature := TaskSignature{}\n\tjson.Unmarshal([]byte(d.Body), &signature)\n\n\ttask := worker.server.GetRegisteredTask(signature.Name)\n\tif task == nil {\n\t\tlog.Printf(\"Task with a name '%s' not registered\", signature.Name)\n\t\treturn\n\t}\n\n\t// Everything seems fine, process the task!\n\tlog.Printf(\"Started processing %s\", signature.Name)\n\n\treflectedTask := reflect.ValueOf(task)\n\trelfectedArgs, err := ReflectArgs(signature.Args)\n\tif err != nil {\n\t\tworker.finalize(\n\t\t\t&signature,\n\t\t\treflect.ValueOf(nil),\n\t\t\terr,\n\t\t)\n\t\treturn\n\t}\n\n\tresults := reflectedTask.Call(relfectedArgs)\n\tif !results[1].IsNil() {\n\t\tworker.finalize(\n\t\t\t&signature,\n\t\t\treflect.ValueOf(nil),\n\t\t\terrors.New(results[1].String()),\n\t\t)\n\t\treturn\n\t}\n\n\t// Trigger success or error tasks\n\tworker.finalize(&signature, results[0], err)\n}", "func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}", "func (em *EventManager) handleMessage(i interface{}) error {\n\tvar err error = nil\n\n\tm := i.(Message)\n\n\tlog.Printf(\"Processing message\")\n\n\t// TODO: process incoming message\n\tres, err := em.wc.HandleMessage(m.Text())\n\tif err != nil {\n\t\tlog.Printf(\"Error processing message\")\n\t\treturn err\n\t}\n\n\t// TODO: act on message\n\tswitch res.Intent {\n\tcase analysis.IntentCreateEvent:\n \n\n\tcase analysis.IntentCancelEvent:\n // Check owner, when and where match\n\n // Delete event\n\n\tcase analysis.IntentFindEvents:\n // Find events based on when / where filters\n\n\tcase analysis.IntentAttending:\n // Set attending flag for a given event\n\n\tcase analysis.IntentNotAttending:\n // Set not attending flag for a given event\n\n case analysis.IntentArrived:\n // Set arrived flag for a given event\n\n\t}\n\n\tif res.Response != \"\" {\n\t\tlog.Printf(\"Sending reply\")\n\n\t\t// Generate reply\n\t\treply := m.Reply(res.Response)\n\n\t\t// Locate matching client\n\t\tc, ok := em.clients[m.Connector()]\n\t\tif !ok {\n\t\t\tlog.Printf(\"Invalid connector %s for response\", m.Connector())\n\t\t\treturn err\n\t\t}\n\n\t\t// Send reply\n\t\tc.Send(reply)\n\t}\n\n\treturn err\n}", "func (*GenericFramework) ValidateMessage(ctx *MessageContext) bool { return true }", "func (broker *Broker) dispatcher() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-broker.inbox:\n\t\t\thareMsg := &pb.HareMessage{}\n\t\t\terr := proto.Unmarshal(msg.Bytes(), hareMsg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Could not unmarshal message: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinstanceId := NewBytes32(hareMsg.Message.InstanceId)\n\n\t\t\tbroker.mutex.RLock()\n\t\t\tc, exist := broker.outbox[instanceId.Id()]\n\t\t\tbroker.mutex.RUnlock()\n\t\t\tmOut := Message{hareMsg, msg.Bytes(), msg.ValidationCompletedChan()}\n\t\t\tif exist {\n\t\t\t\t// todo: err if chan is full (len)\n\t\t\t\tc <- mOut\n\t\t\t} else {\n\n\t\t\t\tbroker.mutex.Lock()\n\t\t\t\tif _, exist := broker.pending[instanceId.Id()]; !exist {\n\t\t\t\t\tbroker.pending[instanceId.Id()] = make([]Message, 0)\n\t\t\t\t}\n\t\t\t\tbroker.pending[instanceId.Id()] = append(broker.pending[instanceId.Id()], mOut)\n\t\t\t\tbroker.mutex.Unlock()\n\t\t\t\t// report validity so that the message will be propagated without delay\n\t\t\t\tmOut.reportValidationResult(true) // TODO consider actually validating the message before reporting the validity\n\t\t\t}\n\n\t\tcase <-broker.CloseChannel():\n\t\t\treturn\n\t\t}\n\t}\n}", "func handleMessage(msg *game.InMessage, ws *websocket.Conn, board *game.Board) {\n\tfmt.Println(\"Message Got: \", msg)\n\n}", "func (a *customAdapter) sendMessage(ctx *customAdapterWorkerContext, req interface{}) error {\n\tb, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Trace(\"xfer: Custom adapter worker %d sending message: %v\", ctx.workerNum, string(b))\n\t// Line oriented JSON\n\tb = append(b, '\\n')\n\t_, err = ctx.stdin.Write(b)\n\treturn err\n}", "func (c *Client) messageReceived(data []byte) {\n\tfor _, v := range c.onDebugListeners {\n\t\tv(data)\n\t}\n\tif bytes.HasPrefix(data, c.config.EvtMessagePrefix) {\n\t\t//it's a custom ws message\n\t\treceivedEvt := c.messageSerializer.getWebsocketCustomEvent(data)\n\t\tvalue, ok := c.onEventListeners.Load(string(receivedEvt))\n\t\tif !ok || value == nil {\n\t\t\treturn\n\t\t}\n\n\t\tlisteners, ok := value.([]MessageFunc)\n\t\tif !ok || len(listeners) == 0 {\n\t\t\treturn // if not listeners for this event exit from here\n\t\t}\n\n\t\tcustomMessage, err := c.messageSerializer.deserialize(receivedEvt, data)\n\t\tif customMessage == nil || err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor i := range listeners {\n\t\t\tif fn, ok := listeners[i].(func()); ok { // its a simple func(){} callback\n\t\t\t\tfn()\n\t\t\t} else if fnString, ok := listeners[i].(func(string)); ok {\n\n\t\t\t\tif msgString, is := customMessage.(string); is {\n\t\t\t\t\tfnString(msgString)\n\t\t\t\t} else if msgInt, is := customMessage.(int); is {\n\t\t\t\t\t// here if server side waiting for string but client side sent an int, just convert this int to a string\n\t\t\t\t\tfnString(strconv.Itoa(msgInt))\n\t\t\t\t}\n\n\t\t\t} else if fnInt, ok := listeners[i].(func(int)); ok {\n\t\t\t\tfnInt(customMessage.(int))\n\t\t\t} else if fnBool, ok := listeners[i].(func(bool)); ok {\n\t\t\t\tfnBool(customMessage.(bool))\n\t\t\t} else if fnBytes, ok := listeners[i].(func([]byte)); ok {\n\t\t\t\tfnBytes(customMessage.([]byte))\n\t\t\t} else {\n\t\t\t\tlisteners[i].(func(interface{}))(customMessage)\n\t\t\t}\n\n\t\t}\n\t} else {\n\t\t// it's native websocket message\n\t\tfor i := range c.onNativeMessageListeners {\n\t\t\tc.onNativeMessageListeners[i](data)\n\t\t}\n\t}\n\n}", "func (l *LifeCycle) fetchMessage(f processFunc) error {\n\tif l.sqs == nil {\n\t\treturn errors.New(\"SQS service is not set\")\n\t}\n\n\tif l.queueURL == nil {\n\t\treturn errors.New(\"queueURL is not set\")\n\t}\n\n\t// try to get messages from qeueue, will longpoll for 20 secs\n\trecieveResp, err := l.sqs.ReceiveMessage(&sqs.ReceiveMessageInput{\n\t\tQueueUrl: l.queueURL, // Required\n\t\tMaxNumberOfMessages: aws.Int64(1),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif recieveResp == nil {\n\t\treturn errors.New(\"recieveResp is nil\")\n\t}\n\n\t// we can operate in sync mode, becase we are already fetching one message\n\tfor _, message := range recieveResp.Messages {\n\t\t// process message\n\t\tif err := f(message.Body); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// if we got sucess just delete the message from queue\n\t\tif _, err := l.sqs.DeleteMessage(&sqs.DeleteMessageInput{\n\t\t\tQueueUrl: l.queueURL, // Required\n\t\t\tReceiptHandle: message.ReceiptHandle, // Required\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Worker) handleMessage(msg *sarama.ConsumerMessage) error {\n\tbuf, err := w.partitioner.GetBuffer(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = buf.WriteMessage(msg)\n\treturn err\n}", "func (k Keeper) dispatchMessage(ctx sdk.Context, contractAddr sdk.AccAddress, msg wasmvmtypes.CosmosMsg) (events sdk.Events, data []byte, err error) {\n\tsdkMsg, err := k.msgParser.Parse(ctx, contractAddr, msg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif sdkMsg == nil {\n\t\treturn nil, nil, sdkerrors.Wrapf(types.ErrInvalidMsg, \"failed to parse msg %v\", msg)\n\t}\n\n\t// Charge tax on result msg\n\ttaxes := ante.FilterMsgAndComputeTax(ctx, k.treasuryKeeper, sdkMsg)\n\tif !taxes.IsZero() {\n\t\teventManager := sdk.NewEventManager()\n\t\tcontractAcc := k.accountKeeper.GetAccount(ctx, contractAddr)\n\t\tif err := cosmosante.DeductFees(k.bankKeeper, ctx.WithEventManager(eventManager), contractAcc, taxes); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tevents = eventManager.Events()\n\t}\n\n\tres, err := k.handleSdkMessage(ctx, contractAddr, sdkMsg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// set data\n\tdata = make([]byte, len(res.Data))\n\tcopy(data, res.Data)\n\n\t// convert Tendermint.Events to sdk.Event\n\tsdkEvents := make(sdk.Events, len(res.Events))\n\tfor i := range res.Events {\n\t\tsdkEvents[i] = sdk.Event(res.Events[i])\n\t}\n\n\t// append message action attribute\n\tevents = append(events, sdkEvents...)\n\n\treturn\n}", "func (b *broker) handleMsg(mc mqtt.Client, msg mqtt.Message) {\n\tsm, err := senml.Decode(msg.Payload(), senml.JSON)\n\tif err != nil {\n\t\tb.logger.Warn(fmt.Sprintf(\"SenML decode failed: %s\", err))\n\t\treturn\n\t}\n\n\tif len(sm.Records) == 0 {\n\t\tb.logger.Error(fmt.Sprintf(\"SenML payload empty: `%s`\", string(msg.Payload())))\n\t\treturn\n\t}\n\tcmdType := sm.Records[0].Name\n\tcmdStr := *sm.Records[0].StringValue\n\tuuid := strings.TrimSuffix(sm.Records[0].BaseName, \":\")\n\n\tswitch cmdType {\n\tcase control:\n\t\tb.logger.Info(fmt.Sprintf(\"Control command for uuid %s and command string %s\", uuid, cmdStr))\n\t\tif err := b.svc.Control(uuid, cmdStr); err != nil {\n\t\t\tb.logger.Warn(fmt.Sprintf(\"Control operation failed: %s\", err))\n\t\t}\n\tcase exec:\n\t\tb.logger.Info(fmt.Sprintf(\"Execute command for uuid %s and command string %s\", uuid, cmdStr))\n\t\tif _, err := b.svc.Execute(uuid, cmdStr); err != nil {\n\t\t\tb.logger.Warn(fmt.Sprintf(\"Execute operation failed: %s\", err))\n\t\t}\n\tcase config:\n\t\tb.logger.Info(fmt.Sprintf(\"Config service for uuid %s and command string %s\", uuid, cmdStr))\n\t\tif err := b.svc.ServiceConfig(uuid, cmdStr); err != nil {\n\t\t\tb.logger.Warn(fmt.Sprintf(\"Execute operation failed: %s\", err))\n\t\t}\n\tcase service:\n\t\tb.logger.Info(fmt.Sprintf(\"Services view for uuid %s and command string %s\", uuid, cmdStr))\n\t\tif err := b.svc.ServiceConfig(uuid, cmdStr); err != nil {\n\t\t\tb.logger.Warn(fmt.Sprintf(\"Services view operation failed: %s\", err))\n\t\t}\n\tcase term:\n\t\tb.logger.Info(fmt.Sprintf(\"Services view for uuid %s and command string %s\", uuid, cmdStr))\n\t\tif err := b.svc.Terminal(uuid, cmdStr); err != nil {\n\t\t\tb.logger.Warn(fmt.Sprintf(\"Services view operation failed: %s\", err))\n\t\t}\n\t}\n\n}", "func (q *FakeQueueDispatcher) DispatchMessage(message interface{}) (err error) {\n\tq.Messages = append(q.Messages, message)\n\treturn\n}", "func (f *FrameProcessor) ProcessMessage(msg *sarama.ConsumerMessage) {\n\tif f.DecodeJSON != 0 {\n\t\tvar decoded map[string]*json.RawMessage\n\t\terr := json.Unmarshal(msg.Value, &decoded)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error occured during decoding\", err)\n\t\t}\n\t}\n\t// Lets record the event\n\tf.Counter.Incr(1)\n}", "func (mgmt *Management) handleFrontendMessage(received []byte) {\n\tvar cm collaborationMessage\n\terr := json.Unmarshal(received, &cm)\n\tif err != nil {\n\t\tlog.Println(\"Error while unmarshalling collaborationMessage:\", err)\n\t}\n\n\tswitch cm.Event {\n\tcase \"ABTU\":\n\t\tmgmt.doc.FrontendToABTU <- cm.Content\n\tcase \"AccessControl\":\n\t//\tTODO Handle access control messages\n\tcase \"Cursor\":\n\t//\tTODO Handle cursor messages\n\t}\n}", "func (self *OFSwitch) handleMessages(dpid net.HardwareAddr, msg util.Message) {\n\tlog.Debugf(\"Received message: %+v, on switch: %s\", msg, dpid.String())\n\n\tswitch t := msg.(type) {\n\tcase *common.Header:\n\t\tswitch t.Header().Type {\n\t\tcase openflow13.Type_Hello:\n\t\t\t// Send Hello response\n\t\t\th, err := common.NewHello(4)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error creating hello message\")\n\t\t\t}\n\t\t\tself.Send(h)\n\n\t\tcase openflow13.Type_EchoRequest:\n\t\t\t// Send echo reply\n\t\t\tres := openflow13.NewEchoReply()\n\t\t\tself.Send(res)\n\n\t\tcase openflow13.Type_EchoReply:\n\t\t\tself.lastUpdate = time.Now()\n\n\t\tcase openflow13.Type_FeaturesRequest:\n\n\t\tcase openflow13.Type_GetConfigRequest:\n\n\t\tcase openflow13.Type_BarrierRequest:\n\n\t\tcase openflow13.Type_BarrierReply:\n\n\t\t}\n\tcase *openflow13.ErrorMsg:\n\t\terrMsg := GetErrorMessage(t.Type, t.Code, 0)\n\t\tmsgType := GetErrorMessageType(t.Data)\n\t\tlog.Errorf(\"Received OpenFlow1.3 error: %s on message %s\", errMsg, msgType)\n\t\tresult := MessageResult{\n\t\t\tsucceed: false,\n\t\t\terrType: t.Type,\n\t\t\terrCode: t.Code,\n\t\t\txID: t.Xid,\n\t\t\tmsgType: UnknownMessage,\n\t\t}\n\t\tself.publishMessage(t.Xid, result)\n\n\tcase *openflow13.VendorHeader:\n\t\tlog.Debugf(\"Received Experimenter message, VendorType: %d, ExperimenterType: %d, VendorData: %+v\", t.Vendor, t.ExperimenterType, t.VendorData)\n\t\tswitch t.ExperimenterType {\n\t\tcase openflow13.Type_TlvTableReply:\n\t\t\treply := t.VendorData.(*openflow13.TLVTableReply)\n\t\t\tstatus := TLVTableStatus(*reply)\n\t\t\tself.tlvMgr.TLVMapReplyRcvd(self, &status)\n\t\tcase openflow13.Type_BundleCtrl:\n\t\t\tresult := MessageResult{\n\t\t\t\txID: t.Header.Xid,\n\t\t\t\tsucceed: true,\n\t\t\t\tmsgType: BundleControlMessage,\n\t\t\t}\n\t\t\treply := t.VendorData.(*openflow13.BundleControl)\n\t\t\tself.publishMessage(reply.BundleID, result)\n\t\t}\n\n\tcase *openflow13.SwitchFeatures:\n\t\tswitch t.Header.Type {\n\t\tcase openflow13.Type_FeaturesReply:\n\t\t\tgo func() {\n\t\t\t\tswConfig := openflow13.NewSetConfig()\n\t\t\t\tswConfig.MissSendLen = 128\n\t\t\t\tself.Send(swConfig)\n\t\t\t\tself.Send(openflow13.NewSetControllerID(self.ctrlID))\n\t\t\t}()\n\t\t}\n\n\tcase *openflow13.SwitchConfig:\n\t\tswitch t.Header.Type {\n\t\tcase openflow13.Type_GetConfigReply:\n\n\t\tcase openflow13.Type_SetConfig:\n\n\t\t}\n\tcase *openflow13.PacketIn:\n\t\tlog.Debugf(\"Received packet(ofctrl): %+v\", t)\n\t\t// send packet rcvd callback\n\t\tself.app.PacketRcvd(self, (*PacketIn)(t))\n\n\tcase *openflow13.FlowRemoved:\n\n\tcase *openflow13.PortStatus:\n\t\t// FIXME: This needs to propagated to the app.\n\tcase *openflow13.PacketOut:\n\n\tcase *openflow13.FlowMod:\n\n\tcase *openflow13.PortMod:\n\n\tcase *openflow13.MultipartRequest:\n\n\tcase *openflow13.MultipartReply:\n\t\tlog.Debugf(\"Received MultipartReply\")\n\t\trep := (*openflow13.MultipartReply)(t)\n\t\tif self.monitorEnabled {\n\t\t\tkey := fmt.Sprintf(\"%d\", rep.Xid)\n\t\t\tch, found := monitoredFlows.Get(key)\n\t\t\tif found {\n\t\t\t\treplyChan := ch.(chan *openflow13.MultipartReply)\n\t\t\t\treplyChan <- rep\n\t\t\t}\n\t\t}\n\t\t// send packet rcvd callback\n\t\tself.app.MultipartReply(self, rep)\n\tcase *openflow13.VendorError:\n\t\terrData := t.ErrorMsg.Data.Bytes()\n\t\tresult := MessageResult{\n\t\t\tsucceed: false,\n\t\t\terrType: t.Type,\n\t\t\terrCode: t.Code,\n\t\t\texperimenter: int32(t.ExperimenterID),\n\t\t\txID: t.Xid,\n\t\t}\n\t\texperimenterID := binary.BigEndian.Uint32(errData[8:12])\n\t\terrMsg := GetErrorMessage(t.Type, t.Code, experimenterID)\n\t\texperimenterType := binary.BigEndian.Uint32(errData[12:16])\n\t\tswitch experimenterID {\n\t\tcase openflow13.ONF_EXPERIMENTER_ID:\n\t\t\tswitch experimenterType {\n\t\t\tcase openflow13.Type_BundleCtrl:\n\t\t\t\tbundleID := binary.BigEndian.Uint32(errData[16:20])\n\t\t\t\tresult.msgType = BundleControlMessage\n\t\t\t\tself.publishMessage(bundleID, result)\n\t\t\t\tlog.Errorf(\"Received Vendor error: %s on ONFT_BUNDLE_CONTROL message\", errMsg)\n\t\t\tcase openflow13.Type_BundleAdd:\n\t\t\t\tbundleID := binary.BigEndian.Uint32(errData[16:20])\n\t\t\t\tresult.msgType = BundleAddMessage\n\t\t\t\tself.publishMessage(bundleID, result)\n\t\t\t\tlog.Errorf(\"Received Vendor error: %s on ONFT_BUNDLE_ADD_MESSAGE message\", errMsg)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Errorf(\"Received Vendor error: %s\", errMsg)\n\t\t}\n\t}\n}", "func Run(ctx context.Context, message []byte) error {\n\tstopwatch := globalBackendStatsClient().TaskExecutionTime().Start()\n\tdefer stopwatch.Stop()\n\n\tvar s fnSignature\n\tif err := GlobalBackend().Encoder().Unmarshal(message, &s); err != nil {\n\t\treturn errors.Wrap(err, \"unable to decode the message\")\n\t}\n\t// TODO (madhu): Do we need a timeout here?\n\tretValues, err := s.Execute(ctx)\n\tif err != nil {\n\t\tglobalBackendStatsClient().TaskExecuteFail().Inc(1)\n\t\treturn err\n\t}\n\t// Assume only an error will be returned since that is verified before adding to fnRegister\n\treturn castToError(retValues[0])\n}", "func (h *hub) onMasterMessage(data []byte) error {\n\treturn nil\n}", "func (c app) handle(msg message) {\n\tswitch msg := msg.(type) {\n\n\tcase *event:\n\t\tfor _, x := range c.domains {\n\t\t\tif binding, ok := x.subscriptions[msg.Subscription]; ok {\n\t\t\t\tgo x.handlePublish(msg, binding)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tWarn(\"No handler registered for subscription:\", msg.Subscription)\n\n\tcase *invocation:\n\t\tfor _, x := range c.domains {\n\t\t\tif binding, ok := x.registrations[msg.Registration]; ok {\n\t\t\t\tgo x.handleInvocation(msg, binding)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tWarn(\"No handler registered for registration:\", msg.Registration)\n\t\ts := fmt.Sprintf(\"no handler for registration: %v\", msg.Registration)\n\t\tm := &errorMessage{Type: iNVOCATION, Request: msg.Request, Details: make(map[string]interface{}), Error: s}\n\n\t\tif err := c.Send(m); err != nil {\n\t\t\tWarn(\"error sending message:\", err)\n\t\t}\n\n\tcase *goodbye:\n\t\tc.Close(\"Fabric said goodbye. Closing connection\")\n\n\tdefault:\n\t\tid, ok := requestID(msg)\n\n\t\t// Catch control messages here and replace getMessageTimeout\n\n\t\tif ok {\n\t\t\tif l, found := c.listeners[id]; found {\n\t\t\t\tl <- msg\n\t\t\t} else {\n\t\t\t\tlog.Println(\"no listener for message\", msg)\n\t\t\t\tInfo(\"Listeners: \", c.listeners)\n\t\t\t\tpanic(\"Unhandled message!\")\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(\"Bad handler picking up requestID!\")\n\t\t}\n\t}\n}", "func (l *listener) run(ch <-chan interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ch:\n\t\t\t\tif msg == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// remove threading guarantees when mulitplexing into channels\n\t\t\t\tlog.Printf(\"listener raw: %#v\", msg)\n\t\t\t\tswitch msg.(type) {\n\t\t\t\tcase error:\n\t\t\t\t\tl.errors <- msg.(error)\n\t\t\t\tcase *bitfinex.Ticker:\n\t\t\t\t\tl.ticks <- msg.(*bitfinex.Ticker)\n\t\t\t\tcase *websocket.InfoEvent:\n\t\t\t\t\tl.infoEvents <- msg.(*websocket.InfoEvent)\n\t\t\t\tcase *websocket.SubscribeEvent:\n\t\t\t\t\tl.subscriptionEvents <- msg.(*websocket.SubscribeEvent)\n\t\t\t\tcase *websocket.UnsubscribeEvent:\n\t\t\t\t\tl.unsubscriptionEvents <- msg.(*websocket.UnsubscribeEvent)\n\t\t\t\tcase *websocket.AuthEvent:\n\t\t\t\t\tl.authEvents <- msg.(*websocket.AuthEvent)\n\t\t\t\tcase *bitfinex.WalletUpdate:\n\t\t\t\t\tl.walletUpdates <- msg.(*bitfinex.WalletUpdate)\n\t\t\t\tcase *bitfinex.BalanceUpdate:\n\t\t\t\t\tl.balanceUpdates <- msg.(*bitfinex.BalanceUpdate)\n\t\t\t\tcase *bitfinex.Notification:\n\t\t\t\t\tl.notifications <- msg.(*bitfinex.Notification)\n\t\t\t\tcase *bitfinex.TradeExecutionUpdate:\n\t\t\t\t\tl.tradeUpdates <- msg.(*bitfinex.TradeExecutionUpdate)\n\t\t\t\tcase *bitfinex.TradeExecution:\n\t\t\t\t\tl.tradeExecutions <- msg.(*bitfinex.TradeExecution)\n\t\t\t\tcase *bitfinex.PositionUpdate:\n\t\t\t\t\tl.positions <- msg.(*bitfinex.PositionUpdate)\n\t\t\t\tcase *bitfinex.OrderCancel:\n\t\t\t\t\tl.cancels <- msg.(*bitfinex.OrderCancel)\n\t\t\t\tcase *bitfinex.MarginInfoBase:\n\t\t\t\t\tl.marginBase <- msg.(*bitfinex.MarginInfoBase)\n\t\t\t\tcase *bitfinex.MarginInfoUpdate:\n\t\t\t\t\tl.marginUpdate <- msg.(*bitfinex.MarginInfoUpdate)\n\t\t\t\tcase *bitfinex.OrderNew:\n\t\t\t\t\tl.orderNew <- msg.(*bitfinex.OrderNew)\n\t\t\t\tcase *bitfinex.FundingInfo:\n\t\t\t\t\tl.funding <- msg.(*bitfinex.FundingInfo)\n\t\t\t\tcase *bitfinex.PositionSnapshot:\n\t\t\t\t\tl.positionSnapshot <- msg.(*bitfinex.PositionSnapshot)\n\t\t\t\tcase *bitfinex.WalletSnapshot:\n\t\t\t\t\tl.walletSnapshot <- msg.(*bitfinex.WalletSnapshot)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func processMessage(ws *Conn, msg []byte) {\n\n\tr := ws.r\n\n\t// Parse request\n\tvar req *reqres.Req\n\tvar err error\n\tif req, err = ParseReq(msg); err != nil {\n\t\tres := NewResponse_Err(req,\n\t\t\terrors.New_AppErr(err, \"Cannot unmarshal request\"))\n\t\tws.chanOut <- res\n\t\treturn\n\t}\n\n\t/* NOTE: Relax this requirement\n\t // Validate request\n\t if req.Id == 0 {\n\t err = fmt.Errorf(\"Request ID is missing\")\n\t res := NewResponse_Err(req,\n\t errors.New_AppErr(err, \"Request must have _reqId\"))\n\t ws.chanOut <- res\n\t return\n\t }\n\t*/\n\n\t// HTTP request\n\treq.HttpReq = r\n\n\t// Catch panic\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tstack := util.Stack()\n\t\t\tres := NewResponse_Err(req,\n\t\t\t\terrors.New_AppErr(fmt.Errorf(\"%v\", err),\n\t\t\t\t\t\"Application error, support notified\"))\n\t\t\tws.chanOut <- res\n\n\t\t\t// Report panic: err, url, params, stack\n\t\t\t_onPanic(\n\t\t\t\tfmt.Sprintf(\"Error processing WS request: %v\", err),\n\t\t\t\tfmt.Sprintf(\"%v : %v : %v\", r.Host, ws.router.URL, req.Op),\n\t\t\t\t\"Params\", fmt.Sprint(req.Params),\n\t\t\t\t\"Session\", fmt.Sprint(req.GetSessionValues()),\n\t\t\t\t\"Stack\", stack)\n\t\t}\n\t}()\n\n\t// Find proc for given op\n\tvar proc func(*reqres.Req) (interface{}, error)\n\tvar ok bool\n\n\t// First look in core procs in this package\n\t// Then look in app supplied procs\n\tif proc, ok = _coreProcs[req.Op]; !ok {\n\t\tif proc, ok = ws.router.Procs[req.Op]; !ok {\n\t\t\tres := NewResponse_Err(req,\n\t\t\t\terrors.New_NotFound(req.Op, \"No matching op processor found\"))\n\t\t\tws.chanOut <- res\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Call proc\n\tvar data interface{}\n\tdata, err = proc(req)\n\n\t// Respond\n\tvar res []byte\n\tif err == nil {\n\t\tres = NewResponse(req, data)\n\t} else {\n\t\t// Error can be either:\n\t\t// Request error: prepended with \"ERR:\" to be shown to user\n\t\t// Application error: all programming logic error\n\t\tres = NewResponse_Err(req, errors.New(err))\n\t}\n\tws.chanOut <- res\n}", "func (s *Switch) SendMessage(ctx context.Context, peerPubkey p2pcrypto.PublicKey, protocol string, payload []byte) error {\n\treturn s.sendMessageImpl(ctx, peerPubkey, protocol, service.DataBytes{Payload: payload})\n}", "func (f *Frontend) Receive() (BackendMessage, error) {\n\tif !f.partialMsg {\n\t\theader, err := f.cr.Next(5)\n\t\tif err != nil {\n\t\t\treturn nil, translateEOFtoErrUnexpectedEOF(err)\n\t\t}\n\n\t\tf.msgType = header[0]\n\t\tf.bodyLen = int(binary.BigEndian.Uint32(header[1:])) - 4\n\t\tf.partialMsg = true\n\t\tif f.bodyLen < 0 {\n\t\t\treturn nil, errors.New(\"invalid message with negative body length received\")\n\t\t}\n\t}\n\n\tmsgBody, err := f.cr.Next(f.bodyLen)\n\tif err != nil {\n\t\treturn nil, translateEOFtoErrUnexpectedEOF(err)\n\t}\n\n\tf.partialMsg = false\n\n\tvar msg BackendMessage\n\tswitch f.msgType {\n\tcase '1':\n\t\tmsg = &f.parseComplete\n\tcase '2':\n\t\tmsg = &f.bindComplete\n\tcase '3':\n\t\tmsg = &f.closeComplete\n\tcase 'A':\n\t\tmsg = &f.notificationResponse\n\tcase 'c':\n\t\tmsg = &f.copyDone\n\tcase 'C':\n\t\tmsg = &f.commandComplete\n\tcase 'd':\n\t\tmsg = &f.copyData\n\tcase 'D':\n\t\tmsg = &f.dataRow\n\tcase 'E':\n\t\tmsg = &f.errorResponse\n\tcase 'G':\n\t\tmsg = &f.copyInResponse\n\tcase 'H':\n\t\tmsg = &f.copyOutResponse\n\tcase 'I':\n\t\tmsg = &f.emptyQueryResponse\n\tcase 'K':\n\t\tmsg = &f.backendKeyData\n\tcase 'n':\n\t\tmsg = &f.noData\n\tcase 'N':\n\t\tmsg = &f.noticeResponse\n\tcase 'R':\n\t\tvar err error\n\t\tmsg, err = f.findAuthenticationMessageType(msgBody)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase 's':\n\t\tmsg = &f.portalSuspended\n\tcase 'S':\n\t\tmsg = &f.parameterStatus\n\tcase 't':\n\t\tmsg = &f.parameterDescription\n\tcase 'T':\n\t\tmsg = &f.rowDescription\n\tcase 'V':\n\t\tmsg = &f.functionCallResponse\n\tcase 'W':\n\t\tmsg = &f.copyBothResponse\n\tcase 'Z':\n\t\tmsg = &f.readyForQuery\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown message type: %c\", f.msgType)\n\t}\n\n\terr = msg.Decode(msgBody)\n\treturn msg, err\n}", "func (d *WindowsDataplane) SendMessage(msg interface{}) error {\n\tlog.Debugf(\"WindowsDataPlane->SendMessage to felix: %T\", msg)\n\n\td.toDataplane <- msg\n\treturn nil\n}", "func (w *worker) Invoke(args interface{}) error { return ErrNotImplement }", "func SendMessage(w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"unsupport body type\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif hub == nil {\n\t\thttp.Error(w, \"unknown error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thub.sendMessage(string(b))\n}", "func (m *msgHandler) Message(_ []byte, hdr wire.Header, payload []byte) error {\n\tmsg := Message{\n\t\tMsgType: pb.MessageType(hdr.MessageType),\n\t\tMsg: make([]byte, len(payload)),\n\t}\n\tcopy(msg.Msg, payload)\n\n\tm.owner.cond.L.Lock()\n\tdefer m.owner.cond.L.Unlock()\n\tm.owner.points = append(m.owner.points, msg)\n\tm.owner.cond.Broadcast()\n\treturn nil\n}", "func (c *Client) SendMessage(data interface{}) {\n\tselect {\n\tcase c.ch <- data:\n\tdefault:\n\t\t//c.sr.monitor.AddDroppedMessage()\n\t}\n}", "func handleMessage(ctx context.Context, channelReference eventingchannel.ChannelReference, message binding.Message, transformers []binding.Transformer, _ nethttp.Header) error {\n\n\t// Note - The context provided here is a different context from the one created in main() and does not have our logger instance.\n\tlogger.Debug(\"~~~~~~~~~~~~~~~~~~~~ Processing Request ~~~~~~~~~~~~~~~~~~~~\")\n\tlogger.Debug(\"Received Message\", zap.Any(\"Message\", message), zap.Any(\"ChannelReference\", channelReference))\n\n\t//\n\t// Convert The CloudEvents Binding Message To A CloudEvent\n\t//\n\t// TODO - It is potentially inefficient to take the CloudEvent binding/Message and convert it into a CloudEvent,\n\t// just so that it can then be further transformed into a Confluent KafkaMessage. The current implementation\n\t// is based on CloudEvent Events, however, and until a \"protocol\" implementation for Confluent Kafka exists\n\t// this is the simplest path forward. Once such a protocol implementation exists, it would be more efficient\n\t// to convert directly from the binding/Message to the protocol/Message.\n\t//\n\tcloudEvent, err := binding.ToEvent(ctx, message, transformers...)\n\tif err != nil {\n\t\tlogger.Error(\"Failed To Convert Message To CloudEvent\", zap.Error(err))\n\t\treturn err\n\t}\n\n\t// Trim The \"-kafkachannel\" Suffix From The Service Name\n\tchannelReference.Name = kafkautil.TrimKafkaChannelServiceNameSuffix(channelReference.Name)\n\n\t// Validate The KafkaChannel Prior To Producing Kafka Message\n\terr = channel.ValidateKafkaChannel(channelReference)\n\tif err != nil {\n\t\tlogger.Warn(\"Unable To Validate ChannelReference\", zap.Any(\"ChannelReference\", channelReference), zap.Error(err))\n\t\treturn err\n\t}\n\n\t// Send The Event To The Appropriate Channel/Topic\n\terr = kafkaProducer.ProduceKafkaMessage(cloudEvent, channelReference)\n\tif err != nil {\n\t\tlogger.Error(\"Failed To Produce Kafka Message\", zap.Error(err))\n\t\treturn err\n\t}\n\n\t// Return Success\n\treturn nil\n}", "func processMessage(consumerMessage *sarama.ConsumerMessage) {\n\treceivedMessage := unmarshal(consumerMessage)\n\trunCallback(receivedMessage, consumerMessage)\n}", "func (l *logic) handleMessage(msgName, msg interface{}) (interface{}, error) {\n\tswitch msgName {\n\tcase \"TemplateMsgTest\":\n\t\tpbMsg := msg.(*TemplateMsgTest)\n\t\tif pbMsg != nil {\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (ctx *Context) SpecificMessageHandler(w http.ResponseWriter, r *http.Request) {\n\t//get the messageID form the request's URL path\n\t_, id := path.Split(r.URL.String())\n\n\t//Get current state\n\tss := &SessionState{}\n\t_, err := sessions.GetState(r, ctx.SessionKey, ctx.SessionStore, ss)\n\tif err != nil {\n\t\thttp.Error(w, \"error getting current session : \"+err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t//Get message from store\n\tm, err := ctx.MessageStore.GetMessageByID(messages.MessageID(id))\n\tif err != nil {\n\t\thttp.Error(w, \"error getting message: \"+err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\n\t//if the user is not owner throw error\n\tif ss.User.ID != m.CreatorID {\n\t\thttp.Error(w, \"error updating message: you aren't the owner\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tswitch r.Method {\n\t//updates the specified message if the current user is the is owner.\n\t//writes back the updated message\n\tcase \"PATCH\":\n\t\td := json.NewDecoder(r.Body)\n\t\tmu := &messages.MessageUpdates{}\n\t\tif err := d.Decode(mu); err != nil {\n\t\t\thttp.Error(w, \"error decoding JSON\"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tum, err := ctx.MessageStore.UpdateMessage(mu, m)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error updating message: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of updated message through websocket\n\t\tn, err := um.ToUpdatedMessageEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating message event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(um)\n\t//deletes the message if the current user is the owner.\n\tcase \"DELETE\":\n\t\tif err := ctx.MessageStore.DeleteMessage(messages.MessageID(id)); err != nil {\n\t\t\thttp.Error(w, \"error deleting message: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of updated message through websocket\n\t\tn, err := m.ToDeletedMessageEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating message event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeText)\n\t\tw.Write([]byte(\"message succesfully deleted\"))\n\t}\n}", "func (h *CronHandler) ProcessMessage(ctx context.Context, topic string, message []byte) {\n\tlogger.LogIf(\"PushNotif module: scheduler run on topic: %s, message: %s\\n\", topic, string(message))\n\n\tvar err error\n\tswitch topic {\n\tcase \"push-notif\":\n\t\tfmt.Println(\"mantab\")\n\tcase \"push\":\n\t\tfmt.Println(\"wkwkwk\")\n\t\ttime.Sleep(50 * time.Second)\n\t\tfmt.Println(\"wkwkwk done\")\n\t}\n\n\tif err != nil {\n\t\tlogger.LogE(err.Error())\n\t}\n}", "func (c *Common) HandleReceivedMessage(message messages.Messager) {\n\n switch message.(type) {\n case *messages.LocationMessage:\n c.rp.HandleLocationMessage(message.(*messages.LocationMessage))\n case *messages.MotorSpeedMessage:\n c.rp.HandleMotorSpeedMessage(message.(*messages.MotorSpeedMessage))\n }\n\n}", "func Run() (err error) {\n\n\t// Register Message Queue handler\n\thandler := mq.MsgHandler{Handler: msgHandler, UserData: nil}\n\tsbi.handlerId, err = sbi.mqLocal.RegisterHandler(handler)\n\tif err != nil {\n\t\tlog.Error(\"Failed to register local Msg Queue listener: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Registered local Msg Queue listener\")\n\n\treturn nil\n}", "func (h *Handler) handleMessage(c websocket.Connection, requestId string, req request.CreateMessage) {\n\t// Validate the request\n\tif err := h.Validator.Struct(req); err != nil {\n\t\tc.Emit(\"error\", WsResponse{\n\t\t\tRequestId: requestId,\n\t\t\tBody: h.Validator.FormatError(err),\n\t\t})\n\t\treturn\n\t}\n\n\t// Create the message\n\tres := h.CreateMessageInteractor.Call(req)\n\n\tvar successResponse response.CreateMessage\n\t// If the response code is not the correct one return the error\n\tif res.GetCode() != successResponse.GetCode() {\n\t\tc.Emit(\"error\", WsResponse{\n\t\t\tRequestId: requestId,\n\t\t\tBody: res,\n\t\t})\n\t}\n\n\t// Send a message to confirm that the message has been sent\n\tc.Emit(\"sent\", WsResponse{\n\t\tRequestId: requestId,\n\t\tBody: res,\n\t})\n}", "func (hub *Hub) ConsumeMessage(msgType string, bz []byte) {\n\thub.preHandleNewHeightInfo(msgType, bz)\n\tif hub.skipHeight {\n\t\treturn\n\t}\n\thub.recordMsg(msgType, bz)\n\tif !hub.isTimeToHandleMsg(msgType) {\n\t\treturn\n\t}\n\tif hub.skipToOldChain(msgType) {\n\t\treturn\n\t}\n\thub.handleMsg()\n}", "func (d delegate) NotifyMsg(data []byte) {}", "func TestDispatch(t *testing.T) {\n\tvar testDispatchMessageKey MessageKey = \"test_trigger_message_key\"\n\texpectedResult := 5\n\tresult := 0\n\n\tmessageBus := NewBasicMessageBus(&testErrorHandler{})\n\tmessageBus.Subscribe(\n\t\ttestDispatchMessageKey,\n\t\tfunc(p MessageParams) (validator.Messages, error) {\n\t\t\tresult++\n\t\t\treturn nil, nil\n\t\t},\n\t)\n\tmessageBus.Listen()\n\n\tm := Message{testDispatchMessageKey, MessageParams{}, CommandMessage}\n\tmessageBus.Dispatch(m)\n\tmessageBus.Dispatch(m)\n\tmessageBus.Dispatch(m)\n\tmessageBus.Dispatch(m)\n\tmessageBus.Dispatch(m)\n\ttime.Sleep(time.Millisecond * 5)\n\n\tif result != expectedResult {\n\t\tt.Errorf(\"Expected: '%d', got: '%d'\", expectedResult, result)\n\t}\n}", "func sendMessage(p orgbot.Platform, m message) error {\n\tqueueService, err := newQueueService(p.Config())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := queueService.submit(&m); err != nil {\n\t\treturn errors.Wrap(err, \"failed to submit command\")\n\t}\n\n\treturn nil\n}", "func handleMessage(ctx context.Context, channelReference eventingchannel.ChannelReference, message binding.Message, transformers []binding.Transformer, _ http.Header) error {\n\n\t// Get The Logger From The Context\n\tlogger := logging.FromContext(ctx).Desugar()\n\n\t// Note - The context provided here is a different context from the one created in main() and does not have our logger instance.\n\tif logger.Core().Enabled(zap.DebugLevel) {\n\t\t// Checked Logging Level First To Avoid Calling zap.Any In Production\n\t\tlogger.Debug(\"~~~~~~~~~~~~~~~~~~~~ Processing Request ~~~~~~~~~~~~~~~~~~~~\")\n\t\tlogger.Debug(\"Received Message\", zap.Any(\"ChannelReference\", channelReference))\n\t}\n\n\t// Trim The \"-kn-channel\" Suffix From The Service Name\n\tchannelReference.Name = kafkautil.TrimKafkaChannelServiceNameSuffix(channelReference.Name)\n\n\t// Validate The KafkaChannel Prior To Producing Kafka Message\n\terr := channel.ValidateKafkaChannel(channelReference)\n\tif err != nil {\n\t\tlogger.Warn(\"Unable To Validate ChannelReference\", zap.Any(\"ChannelReference\", channelReference), zap.Error(err))\n\t\treturn err\n\t}\n\n\t// Produce The CloudEvent Binding Message (Send To The Appropriate Kafka Topic)\n\terr = kafkaProducer.ProduceKafkaMessage(ctx, channelReference, message, transformers...)\n\tif err != nil {\n\t\tlogger.Error(\"Failed To Produce Kafka Message\", zap.Error(err))\n\t\treturn err\n\t}\n\n\t// Return Success\n\treturn nil\n}", "func (s *Switch) processMessage(ctx context.Context, ime net.IncomingMessageEvent) {\n\t// Extract request context and add to log\n\tif ime.RequestID != \"\" {\n\t\tctx = log.WithRequestID(ctx, ime.RequestID)\n\t} else {\n\t\tctx = log.WithNewRequestID(ctx)\n\t\ts.logger.WithContext(ctx).Warning(\"got incoming message event with no requestID, setting new id\")\n\t}\n\n\tif s.config.MsgSizeLimit != config.UnlimitedMsgSize && len(ime.Message) > s.config.MsgSizeLimit {\n\t\ts.logger.WithContext(ctx).With().Error(\"message is too big to process\",\n\t\t\tlog.Int(\"limit\", s.config.MsgSizeLimit),\n\t\t\tlog.Int(\"actual\", len(ime.Message)))\n\t\treturn\n\t}\n\n\tif err := s.onRemoteClientMessage(ctx, ime); err != nil {\n\t\t// TODO: differentiate action on errors\n\t\ts.logger.WithContext(ctx).With().Error(\"err reading incoming message, closing connection\",\n\t\t\tlog.FieldNamed(\"sender_id\", ime.Conn.RemotePublicKey()),\n\t\t\tlog.Err(err))\n\t\tif err := ime.Conn.Close(); err == nil {\n\t\t\ts.cPool.CloseConnection(ime.Conn.RemotePublicKey())\n\t\t\ts.Disconnect(ime.Conn.RemotePublicKey())\n\t\t}\n\t}\n}", "func (xio *SimpleXIO) Message(timestamp, from, to, channel string, msg []byte, isEncrypted bool, doBell bool) {\n\tChatCmds <- cmdRecvMessage{timestamp, from, to, channel, string(msg)}\n}", "func (s *ClientState) Dispatch(msg MsgBody) error {\n\tlogDebug(\"dispatcher received: %+v\", msg)\n\tswitch msg.Name {\n\tcase RECONFIGURE:\n\t\treturn s.Reconfigure(msg)\n\tcase PING:\n\t\treturn s.Ping(msg)\n\tcase INVALIDATE:\n\t\treturn s.Invalidate(msg)\n\tdefault:\n\t\tlogError(\"unexpected message: %s\", msg.Name)\n\t}\n\treturn nil\n}", "func (netSync *NetSync) messageHandler() {\nout:\n\tfor {\n\t\tselect {\n\t\tcase msgChan := <-netSync.cMessage:\n\t\t\t{\n\t\t\t\tgo func(msgC interface{}) {\n\t\t\t\t\tswitch msg := msgC.(type) {\n\t\t\t\t\tcase *wire.MessageTx:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageTx(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//case *wire.MessageRegistration:\n\t\t\t\t\t\t//\t{\n\t\t\t\t\t\t//\t\tnetSync.HandleMessageRegisteration(msg)\n\t\t\t\t\t\t//\t}\n\t\t\t\t\tcase *wire.MessageBFTPropose:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBFTMsg(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBFTPrepare:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBFTMsg(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBFTCommit:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBFTMsg(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBFTReady:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBFTMsg(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBlockBeacon:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBlockBeacon(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBlockShard:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBlockShard(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetCrossShard:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetCrossShard(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageCrossShard:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageCrossShard(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetShardToBeacon:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetShardToBeacon(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetShardToBeacons:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetShardToBeacons(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageShardToBeacon:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageShardToBeacon(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetBlockBeacon:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetBlockBeacon(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetBlockShard:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetBlockShard(msg)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t// case *wire.MessageInvalidBlock:\n\t\t\t\t\t// \t{\n\t\t\t\t\t// \t\tnetSync.HandleMessageInvalidBlock(msg)\n\t\t\t\t\t// \t}\n\t\t\t\t\tcase *wire.MessageGetBeaconState:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetBeaconState(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageBeaconState:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageBeaconState(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageGetShardState:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageGetShardState(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase *wire.MessageShardState:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnetSync.HandleMessageShardState(msg)\n\t\t\t\t\t\t}\n\t\t\t\t\t// case *wire.MessageSwapRequest:\n\t\t\t\t\t// \t{\n\t\t\t\t\t// \t\tnetSync.HandleMessageSwapRequest(msg)\n\t\t\t\t\t// \t}\n\t\t\t\t\t// case *wire.MessageSwapSig:\n\t\t\t\t\t// \t{\n\t\t\t\t\t// \t\tnetSync.HandleMessageSwapSig(msg)\n\t\t\t\t\t// \t}\n\t\t\t\t\t// case *wire.MessageSwapUpdate:\n\t\t\t\t\t// \t{\n\t\t\t\t\t// \t\tnetSync.HandleMessageSwapUpdate(msg)\n\t\t\t\t\t// \t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tLogger.log.Infof(\"Invalid message type in block \"+\"handler: %T\", msg)\n\t\t\t\t\t}\n\t\t\t\t}(msgChan)\n\t\t\t}\n\t\tcase msgChan := <-netSync.cQuit:\n\t\t\t{\n\t\t\t\tLogger.log.Warn(msgChan)\n\t\t\t\tbreak out\n\t\t\t}\n\t\t}\n\t}\n\n\tnetSync.waitgroup.Done()\n\tLogger.log.Info(\"Block handler done\")\n}", "func (msq *MockSend) handler() {\nout:\n\tfor {\n\t\tselect {\n\t\tcase <-msq.quit:\n\t\t\tbreak out\n\t\tcase inv := <-msq.requestQueue:\n\t\t\tmsq.conn.RequestData(inv)\n\t\tcase msg := <-msq.msgQueue:\n\t\t\tmsq.conn.WriteMessage(msg)\n\t\t}\n\t}\n}", "func (l *Listener) process(msg *stan.Msg) {\n\tif err := msg.Ack(); err != nil {\n\t\tlog.Errorf(\"Failed to ack message %s: %s\", msg.String(), err)\n\t}\n\n\tqrm := broker.QueueRequestMessage{}\n\tif err := json.Unmarshal(msg.Data, &qrm); err != nil {\n\t\tlog.Errorf(\"Failed to unmarshal queue request. Error: %s. Data: \", err, string(msg.Data))\n\t\treturn\n\t}\n\n\treq := qrm.Payload\n\n\tif !strings.HasPrefix(req.Path, \"/\") {\n\t\treq.Path = \"/\" + req.Path\n\t}\n\n\tif err := validateMessage(req); err != nil {\n\t\tlog.Errorf(\"%s. Dropping...\", err.Error())\n\t\treturn\n\t}\n\n\tdefaultTimelineFields := trigger.Fields{\n\t\t\"user_id\": req.UserID,\n\t\t\"request_id\": req.RequestID,\n\t\t\"function_id\": req.FunctionID,\n\t}\n\n\tdefaultEventFields := trigger.Fields{\n\t\t\"user_id\": req.UserID,\n\t\t\"request_id\": req.RequestID,\n\t\t\"type\": ett.EventTypeSystem,\n\t\t\"function_name\": req.FunctionName,\n\t\t\"function_id\": req.FunctionID,\n\t}\n\n\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\"event_name\": \"Dwell Time\",\n\t\t\"event_type\": ett.TimelineEventTypeDequeued,\n\t\t\"response\": http.StatusOK,\n\t\t\"duration\": time.Since(req.QueuedAt).Milliseconds(),\n\t}).Fire(types.TimelineHookType)\n\n\tl.metrics.ObserveDwellTime(req.FunctionID, req.FunctionName, req.UserID, time.Since(req.QueuedAt))\n\n\tsleepDuration := time.Minute * 0\n\tfor attempt := 1; attempt <= 3; attempt++ {\n\t\ttime.Sleep(sleepDuration)\n\t\tsleepDuration = sleepDuration + time.Minute*3\n\n\t\tstarted := time.Now()\n\n\t\ttrigger.WithFields(defaultEventFields).WithFields(trigger.Fields{\n\t\t\t\"path\": req.Path,\n\t\t\t\"query_params\": req.QueryParams,\n\t\t\t\"body\": req.Body,\n\t\t\t\"headers\": req.Headers,\n\t\t\t\"message\": types.AsyncExecutionStartMessage(attempt, req.FunctionName),\n\t\t}).Fire(types.EventHookType)\n\n\t\tl.metrics.ObserveInvocationStarted(req.FunctionID, req.FunctionName,\n\t\t\treq.UserID, req.Path, http.MethodPost)\n\n\t\tfilter := k8s.LabelSelector().\n\t\t\tEquals(types.UserIDLabel, req.UserID).\n\t\t\tEquals(types.FunctionIDLabel, req.FunctionID)\n\t\tscaleResult, err := l.k8s.ScaleFromZero(filter)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to scale function %q from zero: %s\", req.FunctionID, err)\n\n\t\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\t\"event_type\": ett.TimelineEventTypeSystemError,\n\t\t\t\t\"response\": http.StatusServiceUnavailable,\n\t\t\t\t\"duration\": time.Since(started).Milliseconds(),\n\t\t\t}).Fire(types.TimelineHookType)\n\n\t\t\ttrigger.WithFields(defaultEventFields).\n\t\t\t\tWithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.ServerErrorMessage(),\n\t\t\t\t}).Fire(types.EventHookType)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif !scaleResult.Found {\n\t\t\tlog.Errorf(\"Function %q deployment not found\")\n\n\t\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\t\"event_type\": ett.TimelineEventTypeFailed,\n\t\t\t\t\"response\": http.StatusNotFound,\n\t\t\t\t\"duration\": time.Since(started).Milliseconds(),\n\t\t\t}).Fire(types.TimelineHookType)\n\n\t\t\ttrigger.WithFields(defaultEventFields).\n\t\t\t\tWithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.FunctionNotFoundMessage(req.RequestID, req.FunctionID, req.FunctionName),\n\t\t\t\t}).Fire(types.EventHookType)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif !scaleResult.Available {\n\t\t\tlog.Errorf(\"Function %q scale request timed-out after %fs\", req.FunctionID, scaleResult.Duration)\n\n\t\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\t\"event_type\": ett.TimelineEventTypeSystemError,\n\t\t\t\t\"response\": http.StatusServiceUnavailable,\n\t\t\t\t\"duration\": time.Since(started).Milliseconds(),\n\t\t\t}).Fire(types.TimelineHookType)\n\n\t\t\ttrigger.WithFields(defaultEventFields).\n\t\t\t\tWithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.ServerErrorMessage(),\n\t\t\t\t}).Fire(types.EventHookType)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tstart := time.Now()\n\t\tfunctionAddr, err := l.k8s.Resolve(req.FunctionID)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"k8s error: cannot find %s: %s\\n\", req.FunctionID, err)\n\n\t\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\t\"event_type\": ett.TimelineEventTypeSystemError,\n\t\t\t\t\"response\": http.StatusServiceUnavailable,\n\t\t\t\t\"duration\": time.Since(started).Milliseconds(),\n\t\t\t}).Fire(types.TimelineHookType)\n\n\t\t\ttrigger.WithFields(defaultEventFields).\n\t\t\t\tWithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.ServerErrorMessage(),\n\t\t\t\t}).Fire(types.EventHookType)\n\n\t\t\tcontinue\n\t\t}\n\n\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\"event_type\": ett.TimelineEventTypeRunning,\n\t\t\t\"response\": http.StatusOK,\n\t\t\t\"duration\": int64(0),\n\t\t}).Fire(types.TimelineHookType)\n\n\t\theaders := map[string]string{}\n\t\tfor k, h := range req.Headers {\n\t\t\theaders[k] = strings.Join(h, \",\")\n\t\t}\n\n\t\turl := functionAddr + req.Path\n\t\tvar result wet.FunctionResponse\n\t\tfunctionRes, err := l.rc.R().\n\t\t\tSetBody(req.Body).\n\t\t\tSetResult(&result).\n\t\t\tSetHeaders(headers).\n\t\t\tSetQueryString(req.QueryParams).\n\t\t\tPost(url)\n\t\tif err != nil || functionRes.IsError() {\n\t\t\tlog.Errorf(\"Failed to execute function request [%s] %q: %s\", http.MethodPost, url, err)\n\n\t\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\t\"event_type\": ett.TimelineEventTypeSystemError,\n\t\t\t\t\"response\": http.StatusServiceUnavailable,\n\t\t\t\t\"duration\": time.Since(started).Milliseconds(),\n\t\t\t}).Fire(types.TimelineHookType)\n\n\t\t\ttrigger.WithFields(defaultEventFields).\n\t\t\t\tWithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.ServerErrorMessage(),\n\t\t\t\t}).Fire(types.EventHookType)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tduration := time.Since(start)\n\t\tl.metrics.ObserveInvocationComplete(req.FunctionID, req.FunctionName, req.UserID, req.Path, result.Status, duration)\n\n\t\tlog.Infof(\"[Attempt: #%s] Invoked: %s-%s [%d] in %fs\", attempt, req.FunctionID,\n\t\t\treq.FunctionName, result.Status, duration.Seconds())\n\n\t\teventType := ett.TimelineEventTypeFinished\n\t\tif result.Status >= 400 {\n\t\t\teventType = ett.TimelineEventTypeFailed\n\t\t}\n\n\t\ttrigger.WithFields(defaultTimelineFields).WithFields(trigger.Fields{\n\t\t\t\"event_name\": fmt.Sprintf(\"Attempt #%d\", attempt),\n\t\t\t\"event_type\": eventType,\n\t\t\t\"response\": result.Status,\n\t\t\t\"duration\": duration.Milliseconds(),\n\t\t}).Fire(types.TimelineHookType)\n\n\t\tdefaultEventFields[\"type\"] = ett.EventTypeUser\n\t\tdefaultEventFields[\"created_at\"] = started.Add(duration)\n\n\t\t// Inject back request id header\n\t\tif result.Headers == nil {\n\t\t\tresult.Headers = http.Header{}\n\t\t}\n\n\t\tresult.Headers.Set(\"X-Request-Id\", req.RequestID)\n\t\tresult.Headers.Del(\"X-Eywa-Token\")\n\n\t\ttrigger.WithFields(defaultEventFields).WithFields(trigger.Fields{\n\t\t\t\"is_error\": eventType == ett.TimelineEventTypeFailed,\n\t\t\t\"status\": result.Status,\n\t\t\t\"headers\": result.Headers,\n\t\t\t\"body\": result.Body,\n\t\t\t\"stdout\": result.Stdout,\n\t\t\t\"stderr\": result.Stderr,\n\t\t\t\"message\": types.AsyncExecutionFinishMessage(req.FunctionName, attempt, result.Status, duration),\n\t\t}).Fire(types.EventHookType)\n\n\t\tif req.CallbackURL != \"\" {\n\t\t\tlog.Infof(\"Sending callback to: %s\\n\", req.CallbackURL)\n\t\t\t_, err := l.rc.R().\n\t\t\t\tSetHeaders(map[string]string{\n\t\t\t\t\t\"X-Function-Name\": req.FunctionName,\n\t\t\t\t\t\"X-Function-Id\": req.FunctionID,\n\t\t\t\t\t\"X-Function-Status\": fmt.Sprint(result.Status),\n\t\t\t\t}).\n\t\t\t\tSetBody(functionRes.Body()).\n\t\t\t\tPost(req.CallbackURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Failed call callback url %q: %s\", req.CallbackURL, err)\n\t\t\t\ttrigger.WithFields(defaultEventFields).WithFields(trigger.Fields{\n\t\t\t\t\t\"is_error\": true,\n\t\t\t\t\t\"message\": types.CallbackError(err.Error()),\n\t\t\t\t}).Fire(types.EventHookType)\n\t\t\t}\n\t\t}\n\n\t\tif eventType != ett.TimelineEventTypeFinished {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn\n\t}\n}", "func (h *Handler) handleMsg(msg message.InboundMessage) error {\n\tstartTime := h.clock.Time()\n\n\tisPeriodic := isPeriodic(msg)\n\tif isPeriodic {\n\t\th.ctx.Log.Verbo(\"Forwarding message to consensus: %s\", msg)\n\t} else {\n\t\th.ctx.Log.Debug(\"Forwarding message to consensus: %s\", msg)\n\t}\n\n\th.ctx.Lock.Lock()\n\tdefer h.ctx.Lock.Unlock()\n\n\tvar (\n\t\terr error\n\t\top = msg.Op()\n\t)\n\tswitch op {\n\tcase message.Notify:\n\t\tvmMsg := msg.Get(message.VMMessage).(uint32)\n\t\terr = h.engine.Notify(common.Message(vmMsg))\n\tcase message.GossipRequest:\n\t\terr = h.engine.Gossip()\n\tcase message.Timeout:\n\t\terr = h.engine.Timeout()\n\tdefault:\n\t\terr = h.handleConsensusMsg(msg)\n\t}\n\n\tendTime := h.clock.Time()\n\t// If the message was caused by another node, track their CPU time.\n\tif op != message.Notify && op != message.GossipRequest && op != message.Timeout {\n\t\tnodeID := msg.NodeID()\n\t\th.cpuTracker.UtilizeTime(nodeID, startTime, endTime)\n\t}\n\n\t// Track how long the operation took.\n\thistogram := h.metrics.messages[op]\n\thistogram.Observe(float64(endTime.Sub(startTime)))\n\n\tmsg.OnFinishedHandling()\n\n\tif isPeriodic {\n\t\th.ctx.Log.Verbo(\"Finished handling message: %s\", op)\n\t} else {\n\t\th.ctx.Log.Debug(\"Finished handling message: %s\", op)\n\t}\n\treturn err\n}", "func initSendMsgHandler(q *data.Queue) func(ctx *neptulon.ReqCtx) error {\n\treturn func(ctx *neptulon.ReqCtx) error {\n\t\tvar sMsgs []models.Message\n\t\tif err := ctx.Params(&sMsgs); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tuid := ctx.Conn.Session.Get(\"userid\").(string)\n\n\t\tfor _, sMsg := range sMsgs {\n\t\t\tfrom := uid\n\t\t\tto := strings.ToLower(sMsg.To)\n\n\t\t\t// handle messages to bots\n\t\t\tif to == \"echo\" {\n\t\t\t\tfrom = \"echo\"\n\t\t\t\tto = uid\n\t\t\t}\n\n\t\t\t// submit the messages to send queue\n\t\t\terr := (*q).AddRequest(to, \"msg.recv\", []models.Message{models.Message{From: from, Message: sMsg.Message}}, func(ctx *neptulon.ResCtx) error {\n\t\t\t\tvar res string\n\t\t\t\tctx.Result(&res)\n\t\t\t\tif res == client.ACK {\n\t\t\t\t\t// todo: send 'delivered' message to sender (as a request?) about this message (or failed, depending on output)\n\t\t\t\t\t// todo: q.AddRequest(uid, \"msg.delivered\", ... // requeue if failed or handle resends automatically in the queue type, which is prefered)\n\t\t\t\t} else {\n\t\t\t\t\t// todo: auto retry or \"msg.failed\" ?\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"route: msg.recv: failed to add request to queue with error: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tctx.Res = client.ACK\n\t\treturn ctx.Next()\n\t}\n}", "func (mod *backendModule) consume(topic string, msg []byte, err error) {\n\tif err != nil {\n\t\tmod.Logger().Warn().\n\t\t\tError(\"error\", err).\n\t\t\tPrint(\"mq consume error\")\n\t\treturn\n\t}\n\tn, m, err := proto.Decode(msg, mod.arena)\n\tif err != nil {\n\t\tmod.Logger().Error().\n\t\t\tInt(\"size\", len(msg)).\n\t\t\tError(\"error\", err).\n\t\t\tPrint(\"unmarshal message from mq error\")\n\t\treturn\n\t}\n\tdefer mod.arena.Put(m)\n\tmod.Logger().Debug().\n\t\tInt(\"size\", len(msg)).\n\t\tInt(\"read\", n).\n\t\tInt(\"type\", int(m.Typeof())).\n\t\tPrint(\"received a message from mq\")\n\n\tswitch ptc := m.(type) {\n\tcase *gatepb.Unicast:\n\t\terr = mod.service.Frontend().Unicast(ptc.Uid, ptc.Msg)\n\tcase *gatepb.Multicast:\n\t\terr = mod.service.Frontend().Multicast(ptc.Uids, ptc.Msg)\n\tcase *gatepb.Broadcast:\n\t\terr = mod.service.Frontend().Broadcast(ptc.Msg)\n\tcase *gatepb.Kickout:\n\t\terr = mod.service.Frontend().Kickout(ptc.Uid, gatepb.KickoutReason(ptc.Reason))\n\tcase *gatepb.Router:\n\t\tif ptc.Addr == \"\" {\n\t\t\tmod.routers.Remove(ptc.Mod)\n\t\t} else {\n\t\t\tmod.routers.Add(ptc.Mod, ptc.Addr)\n\t\t}\n\tdefault:\n\t\terr = errUnknownMessage\n\t}\n\n\tif err != nil {\n\t\tmod.Logger().Warn().\n\t\t\tInt(\"type\", int(m.Typeof())).\n\t\t\tString(\"name\", m.Nameof()).\n\t\t\tError(\"error\", err).\n\t\t\tPrint(\"handle message error\")\n\t}\n}", "func (connection *SSEConnection) SetOnMessage(cb func([]byte)) {\n\n}", "func (s *Subscriber) SendMessage(message []byte) {\n\ts.message <- message\n}", "func (s *API) SendMessage(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"SendMessage\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (s *SWIM) handle(msg pb.Message) {\n\n\ts.handlePbk(msg.PiggyBack)\n\n\tswitch p := msg.Payload.(type) {\n\tcase *pb.Message_Ping:\n\t\ts.handlePing(msg)\n\tcase *pb.Message_Ack:\n\t\t// handle ack\n\tcase *pb.Message_IndirectPing:\n\t\ts.handleIndirectPing(msg)\n\tcase *pb.Message_Membership:\n\t\ts.handleMembership(p.Membership, msg.Address)\n\tdefault:\n\n\t}\n}", "func (cs *ConsensusState) sendInternalMessage(mi MsgInfo) {\n\tselect {\n\tcase cs.internalMsgQueue <- mi:\n\tdefault:\n\t\t// NOTE: using the go-routine means our votes can\n\t\t// be processed out of order.\n\t\t// TODO: use CList here for strict determinism and\n\t\t// attempt push to internalMsgQueue in receiveRoutine\n\t\tqbftlog.Info(\"Internal msg queue is full. Using a go-routine\")\n\t\tgo func() { cs.internalMsgQueue <- mi }()\n\t}\n}", "func (ma *FakeActor) RunsAnotherMessage(ctx exec.VMContext, target address.Address) (uint8, error) {\n\tif err := ctx.Charge(100); err != nil {\n\t\treturn exec.ErrInsufficientGas, errors.RevertErrorWrap(err, \"Insufficient gas\")\n\t}\n\t_, code, err := ctx.Send(target, \"hasReturnValue\", types.ZeroAttoFIL, []interface{}{})\n\treturn code, err\n}", "func (application *Application) sendServiceDescriptorMessage(topic string, message interface{}) {\n application.SendMessageToTopic(topic, message, application.DefaultSubscriptionClientOptions(), false)\n}", "func ws_MessageLoop(messages chan string, receive_channel ReceiveChannel) {\n\n\tfor {\n\t\tmsg := <-messages\n\t\tlog.Printf(\"[%s] MESSAGE !!! \", __FILE__)\n\t\trcv := Command{}\n\t\tjson.Unmarshal([]byte(msg), &rcv)\n\t\tlog.Printf(rcv.Cmd)\n\n\t\tswitch rcv.Cmd {\n\t\tcase \"connected\":\n\t\t\tlog.Printf(\"[%s] connected succefully~~\", __FILE__)\n\t\tcase \"GetContainersInfo\":\n\t\t\treceive_channel.containers <- true\n\t\tcase \"UpdateImage\":\n\t\t\tlog.Printf(\"[%s] command <UpdateImage>\", __FILE__)\n\t\t\tupdate_msg, r := parseUpdateParam(msg)\n\t\t\tif r == nil {\n\t\t\t\treceive_channel.updateinfo <- update_msg\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[%s] UpdateImage message null !!!\")\n\t\t\t}\n\t\tcase \"err\":\n\t\t\tlog.Printf(\"[%s] Error Case in connection need to recovery\", __FILE__)\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[%s] add command of {%s}\", __FILE__, rcv.Cmd)\n\t\t}\n\n\t}\n}", "func MsgHandler(tx juno.Tx, index int, msg sdk.Msg, w worker.Worker) error {\n\tif len(tx.Logs) == 0 {\n\t\tlog.Info().\n\t\t\tStr(\"module\", \"bank\").\n\t\t\tStr(\"tx_hash\", tx.TxHash).Int(\"msg_index\", index).\n\t\t\tMsg(\"skipping message as it was not successful\")\n\t\treturn nil\n\t}\n\n\tdatabase, ok := w.Db.(desmosdb.DesmosDb)\n\tif !ok {\n\t\treturn fmt.Errorf(\"database is not a DesmosDb instance\")\n\t}\n\n\tswitch cosmosMsg := msg.(type) {\n\n\t// Users\n\tcase bank.MsgSend:\n\t\treturn handleMsgSend(cosmosMsg, database)\n\tcase bank.MsgMultiSend:\n\t\treturn handleMsgMultiSend(cosmosMsg, database)\n\t}\n\n\treturn nil\n}", "func (s *Service) ProcessMessage(ctx context.Context, m *fspb.Message) error {\n\tselect {\n\tcase s.msgs <- m:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (srv *Server) handleMessage(msg *Message) error {\n\tswitch msg.msgType {\n\tcase MsgSignalBinary:\n\t\tfallthrough\n\tcase MsgSignalUtf8:\n\t\tfallthrough\n\tcase MsgSignalUtf16:\n\t\tsrv.handleSignal(msg)\n\n\tcase MsgRequestBinary:\n\t\tfallthrough\n\tcase MsgRequestUtf8:\n\t\tfallthrough\n\tcase MsgRequestUtf16:\n\t\tsrv.handleRequest(msg)\n\n\tcase MsgRestoreSession:\n\t\treturn srv.handleSessionRestore(msg)\n\tcase MsgCloseSession:\n\t\treturn srv.handleSessionClosure(msg)\n\t}\n\treturn nil\n}", "func (srv *Server) handleMessage(msg *Message) error {\n\tswitch msg.msgType {\n\tcase MsgSignalBinary:\n\t\tfallthrough\n\tcase MsgSignalUtf8:\n\t\tfallthrough\n\tcase MsgSignalUtf16:\n\t\tsrv.handleSignal(msg)\n\n\tcase MsgRequestBinary:\n\t\tfallthrough\n\tcase MsgRequestUtf8:\n\t\tfallthrough\n\tcase MsgRequestUtf16:\n\t\tsrv.handleRequest(msg)\n\n\tcase MsgRestoreSession:\n\t\treturn srv.handleSessionRestore(msg)\n\tcase MsgCloseSession:\n\t\treturn srv.handleSessionClosure(msg)\n\t}\n\treturn nil\n}", "func (_m *SlackRTMInterface) SendMessage(msg *slack.OutgoingMessage) {\n\t_m.Called(msg)\n}", "func (n *Notifier) SendMessage(msg string) {\n\tn.notificationMessages <- msg\n}", "func (b *Builder) HandleMessage(i interface{}) {\n\tswitch message := i.(type) {\n\tcase *rmake.RequiredFileMessage:\n\t\tslog.Info(\"Received required file.\")\n\t\t//Get a file from another node\n\t\tb.newfiles <- message\n\n\tcase *rmake.BuilderRequest:\n\t\tslog.Info(\"Received builder request.\")\n\t\tb.RequestQueue.Push(message)\n\n\tcase *rmake.BuilderResult:\n\t\tslog.Info(\"Received builder result.\")\n\t\tsdir := path.Join(\"builds\", message.Session)\n\t\tfor _, f := range message.Results {\n\t\t\terr := f.Save(sdir)\n\t\t\tif err != nil {\n\t\t\t\tslog.Error(\"Error saving file!\")\n\t\t\t\tslog.Error(err)\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tslog.Warnf(\"Received invalid message type. '%s'\", reflect.TypeOf(message))\n\t}\n}", "func (dpc *GameUnit) sendMsgToSpecialSubscriber(distributor *Distributor, protocal ClientMessageTypeCode, obj interface{}, err ...string) {\n\t// func (dpc *GameUnit) sendMsgToSpecialSubscriber(id string, protocal ClientMessageTypeCode, obj interface{}, err ...string) {\n\tmsg := NewMessageWithClient(protocal, distributor, obj, err...)\n\tdata, e := json.Marshal(msg)\n\tif e != nil {\n\t\tDebugMustF(\"Fail to marshal event: %s\", e)\n\t\treturn\n\t}\n\t// distributor := dpc.distributors.findOne(func(d *Distributor) bool { return id == d.ID })\n\t// if distributor != nil {\n\tif distributor.SendBinaryMessage(data) != nil {\n\t\t// User disconnected.\n\t\t// dpc.distributorOffLine(distributor)\n\t}\n\t// } else {\n\t// \tDebugSysF(\"系统异常,无法向 %d 发送消息\", id)\n\t// }\n\tif protocal != pro_2c_sys_time_elapse {\n\t\tDebugTraceF(\"=> %s : %v\", distributor.UserInfo.ID, msg)\n\t}\n}", "func (c messageHandler) receive(f interface{}) {\n\tmsg := reflect.TypeOf(f).In(0).Name()[1:]\n\tc.callbacks[msg] = append(c.callbacks[msg], f)\n}", "func (oo *OmciCC) receiveOnuMessage(ctx context.Context, omciMsg *omci.OMCI, packet *gp.Packet) error {\n\tlogger.Debugw(ctx, \"rx-onu-autonomous-message\", log.Fields{\"omciMsgType\": omciMsg.MessageType,\n\t\t\"payload\": hex.EncodeToString(omciMsg.Payload)})\n\tswitch omciMsg.MessageType {\n\tcase omci.AlarmNotificationType:\n\t\tdata := OmciMessage{\n\t\t\tOmciMsg: omciMsg,\n\t\t\tOmciPacket: packet,\n\t\t}\n\t\tgo oo.pOnuAlarmManager.HandleOmciAlarmNotificationMessage(ctx, data)\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"receiveOnuMessageType %s unimplemented\", omciMsg.MessageType.String())\n\t}\n\t/*\n\t\t\tmsgType = rxFrame.fields[\"message_type\"] //assumed OmciOperationsValue\n\t\t\trxOnuFrames++\n\n\t\t\tswitch msgType {\n\t\t\tcase AlarmNotification:\n\t\t\t\t{\n\t\t\t\t\tlogger.Info(\"Unhandled: received-onu-alarm-message\")\n\t\t\t\t\t// python code was:\n\t\t\t\t\t//if msg_type == EntityOperations.AlarmNotification.value:\n\t\t\t\t\t//\ttopic = OMCI_CC.event_bus_topic(self._device_id, RxEvent.Alarm_Notification)\n\t\t\t\t\t//\tself.reactor.callLater(0, self.event_bus.publish, topic, msg)\n\t\t\t\t\t//\n\t\t\t\t\treturn errors.New(\"RxAlarmNotification unimplemented\")\n\t\t\t\t}\n\t\t\tcase AttributeValueChange:\n\t\t\t\t{\n\t\t\t\t\tlogger.Info(\"Unhandled: received-attribute-value-change\")\n\t\t\t\t\t// python code was:\n\t\t\t\t\t//elif msg_type == EntityOperations.AttributeValueChange.value:\n\t\t\t\t\t//\ttopic = OMCI_CC.event_bus_topic(self._device_id, RxEvent.AVC_Notification)\n\t\t\t\t\t//\tself.reactor.callLater(0, self.event_bus.publish, topic, msg)\n\t\t\t\t\t//\n\t\t\t\t\treturn errors.New(\"RxAttributeValueChange unimplemented\")\n\t\t\t\t}\n\t\t\tcase TestResult:\n\t\t\t\t{\n\t\t\t\t\tlogger.Info(\"Unhandled: received-test-result\")\n\t\t\t\t\t// python code was:\n\t\t\t\t\t//elif msg_type == EntityOperations.TestResult.value:\n\t\t\t\t\t//\ttopic = OMCI_CC.event_bus_topic(self._device_id, RxEvent.Test_Result)\n\t\t\t\t\t//\tself.reactor.callLater(0, self.event_bus.publish, topic, msg)\n\t\t\t\t\t//\n\t\t\t\t\treturn errors.New(\"RxTestResult unimplemented\")\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tlogger.Errorw(ctx,\"rx-onu-unsupported-autonomous-message\", log.Fields{\"msgType\": msgType})\n\t\t\t\t\trxOnuDiscards++\n\t\t\t\t\treturn errors.New(\"RxOnuMsgType unimplemented\")\n\t\t\t\t}\n\t\t }\n\t*/\n}", "func TestDispatch(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\thub *EdgeHub\n\t\tmessage *model.Message\n\t\texpectedError error\n\t\tisResponse bool\n\t}{\n\t\t{\n\t\t\tname: \"dispatch with valid input\",\n\t\t\thub: &EdgeHub{},\n\t\t\tmessage: model.NewMessage(\"\").BuildRouter(module.EdgeHubModuleName, module.TwinGroup, \"\", \"\"),\n\t\t\texpectedError: nil,\n\t\t\tisResponse: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Error Case in dispatch\",\n\t\t\thub: &EdgeHub{},\n\t\t\tmessage: model.NewMessage(\"test\").BuildRouter(module.EdgeHubModuleName, module.EdgedGroup, \"\", \"\"),\n\t\t\texpectedError: fmt.Errorf(\"failed to handle message, no handler found for the message, message group: edged\"),\n\t\t\tisResponse: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Response Case in dispatch\",\n\t\t\thub: &EdgeHub{},\n\t\t\tmessage: model.NewMessage(\"test\").BuildRouter(module.EdgeHubModuleName, module.TwinGroup, \"\", \"\"),\n\t\t\texpectedError: nil,\n\t\t\tisResponse: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.hub.dispatch(*tt.message)\n\t\t\tif !reflect.DeepEqual(err, tt.expectedError) {\n\t\t\t\tt.Errorf(\"TestController_dispatch() error = %v, wantErr %v\", err, tt.expectedError)\n\t\t\t}\n\t\t})\n\t}\n}", "func (r *Resolver) Dispatch(m *models.Message) {\n\turbModule := r.Modules[URB].(*UrbModule)\n\thbfdModule := r.Modules[HBFD].(*HbfdModule)\n\tthetafdModule := r.Modules[THETAFD].(*ThetafdModule)\n\n\tswitch m.Type {\n\tcase models.MSG:\n\t\turbModule.onMSG(m)\n\tcase models.MSGack:\n\t\turbModule.onMSGack(m)\n\tcase models.GOSSIP:\n\t\turbModule.onGOSSIP(m)\n\tcase models.HBFDheartbeat:\n\t\thbfdModule.onHeartbeat(m.Sender)\n\tcase models.THETAheartbeat:\n\t\tthetafdModule.onHeartbeat(m.Sender)\n\tdefault:\n\t\tlog.Fatalf(\"Got unrecognized message %v\", m)\n\t}\n}", "func caller(msgType int) MyReply {\n\targs := MyArgs{}\n\targs.MessageType = msgType\n\treply := MyReply{}\n\tcall(\"Master.Handler\", &args, &reply)\n\n\treturn reply\n}", "func ProcessMessage(ctx context.Context, conn tao.WriteCloser) {\n\tconnId := tao.NetIDFromContext(ctx)\n\n\tmsg := tao.MessageFromContext(ctx).(Message)\n\n\t//取tcp服务器 变量\n\tserver := <-SkuRun.PiServer\n\n\tthisPi, err := server.GetPiByConnId(connId)\n\n\tif err != nil {\n\t\tholmes.Errorln(\"client-time-sync: 当前链接对应的pi不存在\")\n\t\treturn\n\t}\n\n\t//设置pi 上报分析结果\n\tthisPi.IsSendResult = true\n\tserver.UpdatePiByConnId(connId, thisPi)\n\n\t//设置tcp服务器 变量\n\tSkuRun.PiServer <- server\n\n\t//分析的结果数据加工\n\tfor k,module := range msg.Content {\n\t\tmsg.Content[k].Status = \"success\"\n\n\t\tfor kk,state := range module.Info {\n\t\t\tif state.Error != 0 {\n\t\t\t\tmsg.Content[k].Status = \"error\"\n\t\t\t}\n\n\t\t\tvar errRate float64\n\t\t\tif state.Total != 0 {\n\t\t\t\terrRate = float64(state.Error)/float64(state.Total)\n\t\t\t} else {\n\t\t\t\terrRate = 0\n\t\t\t\tmsg.Content[k].Status = \"error\"\n\t\t\t}\n\t\t\terrRate = math.Trunc(errRate*1e2 + 0.5)*1e-2\n\t\t\tmsg.Content[k].Info[kk].Proportion = errRate * 100\n\t\t}\n\t}\n\n\tresult := struct {\n\t\tPid string `json:\"pid\"`\n\t\tModules [] Module `json:\"modules\"`\n\t}{thisPi.Info.Name,msg.Content}\n\n\t//将结果发送至客户端\n\tChanWeb.SendWeb(WebKey.WEB_TSI_TEST_MODULE_RESULT, result)\n\n\t//通知浏览器-pi已上传测试结果\n\tChanWeb.SendWebLog(WebKey.LOG_TYPE_CLIENT, fmt.Sprintf(\"%v已分析完毕\", thisPi.Info.Name))\n}", "func save(message *pb.Message) {\n log.Println(\"异步保存消息数据到数据库...\")\n}", "func (sender *Sess) SendMessage(logEvent logevent.LogEvent) error {\n\tif sender.hecClient == nil {\n\t\treturn errors.New(\"SendMessage() called before OpenSvc()\")\n\t}\n\thecEvents := []*hec.Event{\n\t\tsender.formatLogEvent(logEvent),\n\t}\n\tsender.tracePretty(\"TRACE_SENDHEC time =\",\n\t\tlogEvent.Content.Time.UTC().Format(time.RFC3339),\n\t\t\" hecEvents =\", hecEvents)\n\terr := sender.hecClient.WriteBatch(hecEvents)\n\treturn err\n}", "func fakeMessageQueue() []message {\n\treturn []message{\n\t\tmessage{Type: \"REGULAR\", Text: \"Golang\"}, // will invoke regularConsumer\n\t\tmessage{Type: \"REVERSE\", Text: \"Golang\"}, // will invoke reverseConsumer\n\t\tmessage{Type: \"ANY\", Text: \"Golang\"}, // will throw error because there is no consumer\n\t}\n}", "func (_m *Callbacks) MessageCreated(sequence int64) {\n\t_m.Called(sequence)\n}", "func init(){\n\tskeleton.RegisterChanRPC(reflect.TypeOf(&msg.Hello{}), handleHello)\n}", "func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}", "func (h *handler) executeAsyncMsg(ctx context.Context, msg Message) error {\n\tvar (\n\t\tnodeID = msg.NodeID()\n\t\top = msg.Op()\n\t\tbody = msg.Message()\n\t\tstartTime = h.clock.Time()\n\t)\n\tif h.ctx.Log.Enabled(logging.Verbo) {\n\t\th.ctx.Log.Verbo(\"forwarding async message to consensus\",\n\t\t\tzap.Stringer(\"nodeID\", nodeID),\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t\tzap.Any(\"message\", body),\n\t\t)\n\t} else {\n\t\th.ctx.Log.Debug(\"forwarding async message to consensus\",\n\t\t\tzap.Stringer(\"nodeID\", nodeID),\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t)\n\t}\n\th.resourceTracker.StartProcessing(nodeID, startTime)\n\tdefer func() {\n\t\tvar (\n\t\t\tendTime = h.clock.Time()\n\t\t\tmessageHistograms = h.metrics.messages[op]\n\t\t\tprocessingTime = endTime.Sub(startTime)\n\t\t)\n\t\th.resourceTracker.StopProcessing(nodeID, endTime)\n\t\t// There is no lock grabbed here, so both metrics are identical\n\t\tmessageHistograms.processingTime.Observe(float64(processingTime))\n\t\tmessageHistograms.msgHandlingTime.Observe(float64(processingTime))\n\t\tmsg.OnFinishedHandling()\n\t\th.ctx.Log.Debug(\"finished handling async message\",\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t)\n\t}()\n\n\tstate := h.ctx.State.Get()\n\tengine, ok := h.engineManager.Get(state.Type).Get(state.State)\n\tif !ok {\n\t\treturn fmt.Errorf(\n\t\t\t\"%w %s running %s\",\n\t\t\terrMissingEngine,\n\t\t\tstate.State,\n\t\t\tstate.Type,\n\t\t)\n\t}\n\n\tswitch m := body.(type) {\n\tcase *p2p.AppRequest:\n\t\treturn engine.AppRequest(\n\t\t\tctx,\n\t\t\tnodeID,\n\t\t\tm.RequestId,\n\t\t\tmsg.Expiration(),\n\t\t\tm.AppBytes,\n\t\t)\n\n\tcase *p2p.AppResponse:\n\t\treturn engine.AppResponse(ctx, nodeID, m.RequestId, m.AppBytes)\n\n\tcase *message.AppRequestFailed:\n\t\treturn engine.AppRequestFailed(ctx, nodeID, m.RequestID)\n\n\tcase *p2p.AppGossip:\n\t\treturn engine.AppGossip(ctx, nodeID, m.AppBytes)\n\n\tcase *message.CrossChainAppRequest:\n\t\treturn engine.CrossChainAppRequest(\n\t\t\tctx,\n\t\t\tm.SourceChainID,\n\t\t\tm.RequestID,\n\t\t\tmsg.Expiration(),\n\t\t\tm.Message,\n\t\t)\n\n\tcase *message.CrossChainAppResponse:\n\t\treturn engine.CrossChainAppResponse(\n\t\t\tctx,\n\t\t\tm.SourceChainID,\n\t\t\tm.RequestID,\n\t\t\tm.Message,\n\t\t)\n\n\tcase *message.CrossChainAppRequestFailed:\n\t\treturn engine.CrossChainAppRequestFailed(\n\t\t\tctx,\n\t\t\tm.SourceChainID,\n\t\t\tm.RequestID,\n\t\t)\n\n\tdefault:\n\t\treturn fmt.Errorf(\n\t\t\t\"attempt to submit unhandled async msg %s from %s\",\n\t\t\top, nodeID,\n\t\t)\n\t}\n}", "func (o *trackInverter) ProcessMessage(ctx context.Context, r model.Output) error {\n\tvalue := r.GetRequest().GetValue()\n\to.targetState = model.TrackInverterState(value)\n\tatomic.StoreInt32(&o.sendActualNeeded, 1)\n\treturn nil\n}", "func (m *master) Submit(unit interface{}) {\n\tatomic.AddInt32(&m.wiq, 1)\n\tm.outgoing <- message.OfType(message.NewTask).WithPayload(unit)\n}", "func init() {\n\tcoolmsg.RegisterMessage(TYPE_MAKE_GREETER, func() coolmsg.Message { return &MakeGreeter{} })\n\tcoolmsg.RegisterMessage(TYPE_HELLO, func() coolmsg.Message { return &Hello{} })\n}", "func (mm *mattermostMessage) handleMessage(b *MMBot) {\n\tpost := model.PostFromJson(strings.NewReader(mm.Event.Data[\"post\"].(string)))\n\tchannelType := mmChannelType(mm.Event.Data[\"channel_type\"].(string))\n\tif channelType == mmChannelPrivate || channelType == mmChannelPublic {\n\t\t// Message posted in a channel\n\t\t// Serve only if starts with mention\n\t\tif !strings.HasPrefix(post.Message, \"@\"+BotName+\" \") {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Check if message posted in authenticated channel\n\tif mm.Event.Broadcast.ChannelId == b.getChannel().Id {\n\t\tmm.IsAuthChannel = true\n\t}\n\tlogging.Logger.Debugf(\"Received mattermost event: %+v\", mm.Event.Data)\n\n\t// Trim the @BotKube prefix if exists\n\tmm.Request = strings.TrimPrefix(post.Message, \"@\"+BotName+\" \")\n\n\te := execute.NewDefaultExecutor(mm.Request, b.AllowKubectl, b.ClusterName, b.ChannelName, mm.IsAuthChannel)\n\tmm.Response = e.Execute()\n\tmm.sendMessage()\n}", "func (h *handler) handleChanMsg(msg message.InboundMessage) error {\n\tvar (\n\t\top = msg.Op()\n\t\tbody = msg.Message()\n\t\tstartTime = h.clock.Time()\n\t\t// Check if the chain is in normal operation at the start of message\n\t\t// execution (may change during execution)\n\t\tisNormalOp = h.ctx.State.Get().State == snow.NormalOp\n\t)\n\tif h.ctx.Log.Enabled(logging.Verbo) {\n\t\th.ctx.Log.Verbo(\"forwarding chan message to consensus\",\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t\tzap.Any(\"message\", body),\n\t\t)\n\t} else {\n\t\th.ctx.Log.Debug(\"forwarding chan message to consensus\",\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t)\n\t}\n\th.ctx.Lock.Lock()\n\tlockAcquiredTime := h.clock.Time()\n\tdefer func() {\n\t\th.ctx.Lock.Unlock()\n\n\t\tvar (\n\t\t\tendTime = h.clock.Time()\n\t\t\tmessageHistograms = h.metrics.messages[op]\n\t\t\tprocessingTime = endTime.Sub(startTime)\n\t\t\tmsgHandlingTime = endTime.Sub(lockAcquiredTime)\n\t\t)\n\t\tmessageHistograms.processingTime.Observe(float64(processingTime))\n\t\tmessageHistograms.msgHandlingTime.Observe(float64(msgHandlingTime))\n\t\tmsg.OnFinishedHandling()\n\t\th.ctx.Log.Debug(\"finished handling chan message\",\n\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t)\n\t\tif processingTime > syncProcessingTimeWarnLimit && isNormalOp {\n\t\t\th.ctx.Log.Warn(\"handling chan message took longer than expected\",\n\t\t\t\tzap.Duration(\"processingTime\", processingTime),\n\t\t\t\tzap.Duration(\"msgHandlingTime\", msgHandlingTime),\n\t\t\t\tzap.Stringer(\"messageOp\", op),\n\t\t\t\tzap.Any(\"message\", body),\n\t\t\t)\n\t\t}\n\t}()\n\n\tstate := h.ctx.State.Get()\n\tengine, ok := h.engineManager.Get(state.Type).Get(state.State)\n\tif !ok {\n\t\treturn fmt.Errorf(\n\t\t\t\"%w %s running %s\",\n\t\t\terrMissingEngine,\n\t\t\tstate.State,\n\t\t\tstate.Type,\n\t\t)\n\t}\n\n\tswitch msg := body.(type) {\n\tcase *message.VMMessage:\n\t\treturn engine.Notify(context.TODO(), common.Message(msg.Notification))\n\n\tcase *message.GossipRequest:\n\t\treturn engine.Gossip(context.TODO())\n\n\tcase *message.Timeout:\n\t\treturn engine.Timeout(context.TODO())\n\n\tdefault:\n\t\treturn fmt.Errorf(\n\t\t\t\"attempt to submit unhandled chan msg %s\",\n\t\t\top,\n\t\t)\n\t}\n}", "func SendMessage() {\n\n\tmsg := fmt.Sprintf(`{\"Fuellid\":\"%t\", \"City\":\"%s\"}`, data.Fuellid, data.City)\n\terr := ch.Publish(\n\t\t\"\",\n\t\tq.Name,\n\t\tfalse,\n\t\tfalse,\n\t\tamqp.Publishing{\n\t\t\tContentType: \"text/plain\",\n\t\t\tBody: []byte(msg),\n\t\t},\n\t)\n\tlogger.LogMessage(err, \"Failed to Publish message\", \"Published the message\")\n}" ]
[ "0.76166224", "0.7523464", "0.7301339", "0.65361845", "0.581059", "0.5690735", "0.5615401", "0.55689687", "0.5547834", "0.5494455", "0.54745054", "0.5425644", "0.5393343", "0.53881025", "0.5377702", "0.5375619", "0.53561026", "0.5316209", "0.5300948", "0.5299889", "0.5255014", "0.52474326", "0.51930016", "0.5161388", "0.51301825", "0.51285565", "0.51098144", "0.5102792", "0.5101792", "0.5097502", "0.50869715", "0.50580996", "0.5043875", "0.5029734", "0.5028575", "0.5026446", "0.5026392", "0.5025651", "0.50088775", "0.49988705", "0.49949777", "0.49899638", "0.4979518", "0.49779642", "0.4973336", "0.49701276", "0.4967705", "0.496143", "0.4948737", "0.49418062", "0.49210823", "0.49124563", "0.49072602", "0.49070746", "0.49034426", "0.4902581", "0.48993233", "0.489562", "0.48955566", "0.4892631", "0.48796085", "0.4862612", "0.48530096", "0.48471949", "0.48456943", "0.4843322", "0.48422956", "0.48412624", "0.48361036", "0.48352388", "0.4833907", "0.48319942", "0.48276532", "0.48275605", "0.48251402", "0.48229998", "0.48229998", "0.48176655", "0.4814184", "0.4803437", "0.48034295", "0.4803237", "0.48018104", "0.4790095", "0.47877097", "0.47801894", "0.47745788", "0.47731057", "0.4771748", "0.47697827", "0.47677636", "0.47670296", "0.47585213", "0.47548816", "0.47496462", "0.4748257", "0.4746604", "0.47432184", "0.4741673", "0.4736831" ]
0.7578516
1
Shutdown is called when the executor receives a shutdown request.
func (k *KubernetesExecutor) Shutdown(driver bindings.ExecutorDriver) { k.lock.Lock() defer k.lock.Unlock() k.doShutdown(driver) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *bcsExecutor) Shutdown() {\n\te.isAskedShutdown = true\n\n\t//shutdown\n\te.innerShutdown()\n}", "func (k *KubernetesExecutor) Shutdown(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tclose(k.done)\n\n\tlog.Infoln(\"Shutdown the executor\")\n\tdefer func() {\n\t\tfor !k.swapState(k.getState(), doneState) {\n\t\t}\n\t}()\n\n\tfunc() {\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tk.tasks = map[string]*kuberTask{}\n\t}()\n\n\t// according to docs, mesos will generate TASK_LOST updates for us\n\t// if needed, so don't take extra time to do that here.\n\n\t// also, clear the pod configuration so that after we issue our Kill\n\t// kubernetes doesn't start spinning things up before we exit.\n\tk.updateChan <- kubelet.PodUpdate{Op: kubelet.SET}\n\n\tKillKubeletContainers(k.dockerClient)\n}", "func (ts *TaskService) Shutdown(requestCtx context.Context, req *taskAPI.ShutdownRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\tlog.G(requestCtx).WithFields(logrus.Fields{\"id\": req.ID, \"now\": req.Now}).Debug(\"shutdown\")\n\n\t// shimCancel will result in the runc shim to be canceled in addition to unblocking agent's\n\t// main func, which will allow it to exit gracefully.\n\tdefer ts.shimCancel()\n\n\tlog.G(requestCtx).Debug(\"going to gracefully shutdown agent\")\n\treturn &types.Empty{}, nil\n}", "func (ts *TaskService) Shutdown(ctx context.Context, req *taskAPI.ShutdownRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"now\": req.Now}).Debug(\"shutdown\")\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\n\t// We don't want to call runc.Shutdown here as it just os.Exits behind.\n\t// calling all cancels here for graceful shutdown instead and call runc Shutdown at end.\n\tts.taskManager.RemoveAll(ctx)\n\tts.cancel()\n\n\tlog.G(ctx).Debug(\"going to gracefully shutdown agent\")\n\treturn &types.Empty{}, nil\n}", "func (p *Pool) Shutdown() {\n\tp.sugar.Infow(\"workers pool shutting down\",\n\t\t\"func\", caller.GetCurrentFunctionName())\n\tclose(p.jobCh)\n\tp.wg.Wait()\n\tclose(p.errCh)\n}", "func Shutdown() {\n\tclose(shutdown)\n}", "func (workPool *WorkPool) Shutdown(goRoutine string) (err error) {\n\tdefer catchPanic(&err, goRoutine, \"Shutdown\")\n\n\twriteStdout(goRoutine, \"Shutdown\", \"Started\")\n\twriteStdout(goRoutine, \"Started\", \"Queue Routine\")\n\n\tworkPool.shutdownQueueChannel <- \"Down\"\n\t<-workPool.shutdownQueueChannel\n\n\tclose(workPool.queueChannel)\n\tclose(workPool.shutdownQueueChannel)\n\n\twriteStdout(goRoutine, \"Shutdown\", \"Shutting Down Work Routines\")\n\n\tclose(workPool.shutdownWorkChannel)\n\tworkPool.shutdownWaitGroup.Wait()\n\n\tclose(workPool.workChannel)\n\n\twriteStdout(goRoutine, \"Shutdown\", \"Completed\")\n\n\treturn\n}", "func (s *Stream) Shutdown() {\n\ts.log.Log(\"Sumex.Streams\", \"Shutdown\", \"Started : Shutdown Requested\")\n\tif atomic.LoadInt64(&s.closed) == 0 {\n\t\ts.log.Log(\"Sumex.Streams\", \"Stats\", \"Info : Shutdown Request : Previously Done\")\n\t\treturn\n\t}\n\n\tif pen := atomic.LoadInt64(&s.pending); pen > 0 {\n\t\ts.log.Log(\"Sumex.Streams\", \"Shutdown\", \"Info : Pending : %d\", pen)\n\t\tatomic.StoreInt64(&s.shutdownAfterpending, 1)\n\t\tatomic.StoreInt64(&s.closed, 1)\n\t}\n\n\ts.log.Log(\"Sumex.Streams\", \"Shutdown\", \"Started : WaitGroup.Wait()\")\n\ts.wg.Wait()\n\ts.log.Log(\"Sumex.Streams\", \"Shutdown\", \"Completed : WaitGroup.Wait()\")\n\n\tclose(s.data)\n\tclose(s.err)\n\tclose(s.nc)\n\tatomic.StoreInt64(&s.closed, 1)\n\ts.log.Log(\"Sumex.Streams\", \"Shutdown\", \"Completed : Shutdown Requested\")\n}", "func (zr *zipkinReceiver) Shutdown(context.Context) error {\n\tvar err error\n\tif zr.server != nil {\n\t\terr = zr.server.Close()\n\t}\n\tzr.shutdownWG.Wait()\n\treturn err\n}", "func (a *AbstractSSHConnectionHandler) OnShutdown(_ context.Context) {}", "func (wk *Worker) Shutdown(_ *struct{}, _ *struct{}) error {\n\tserverless.Debug(\"Worker shutdown %s\\n\", wk.address)\n\tclose(wk.shutdown)\n\twk.l.Close()\n\treturn nil\n}", "func (hmr *receiver) Shutdown(ctx context.Context) error {\n\tclose(hmr.done)\n\treturn hmr.closeScrapers(ctx)\n}", "func (k *KubernetesExecutor) doShutdown(driver bindings.ExecutorDriver) {\n\tdefer func() {\n\t\tlog.Errorf(\"exiting with unclean shutdown: %v\", recover())\n\t\tif k.exitFunc != nil {\n\t\t\tk.exitFunc(1)\n\t\t}\n\t}()\n\n\t(&k.state).transitionTo(terminalState)\n\n\t// signal to all listeners that this KubeletExecutor is done!\n\tclose(k.done)\n\n\tif k.shutdownAlert != nil {\n\t\tfunc() {\n\t\t\tutil.HandleCrash()\n\t\t\tk.shutdownAlert()\n\t\t}()\n\t}\n\n\tlog.Infoln(\"Stopping executor driver\")\n\t_, err := driver.Stop()\n\tif err != nil {\n\t\tlog.Warningf(\"failed to stop executor driver: %v\", err)\n\t}\n\n\tlog.Infoln(\"Shutdown the executor\")\n\n\t// according to docs, mesos will generate TASK_LOST updates for us\n\t// if needed, so don't take extra time to do that here.\n\tk.tasks = map[string]*kuberTask{}\n\n\tselect {\n\t// the main Run() func may still be running... wait for it to finish: it will\n\t// clear the pod configuration cleanly, telling k8s \"there are no pods\" and\n\t// clean up resources (pods, volumes, etc).\n\tcase <-k.kubeletFinished:\n\n\t//TODO(jdef) attempt to wait for events to propagate to API server?\n\n\t// TODO(jdef) extract constant, should be smaller than whatever the\n\t// slave graceful shutdown timeout period is.\n\tcase <-time.After(15 * time.Second):\n\t\tlog.Errorf(\"timed out waiting for kubelet Run() to die\")\n\t}\n\tlog.Infoln(\"exiting\")\n\tif k.exitFunc != nil {\n\t\tk.exitFunc(0)\n\t}\n}", "func (c *controllerAPIHandlers) Shutdown(arg *ShutdownArgs, reply *ShutdownReply) error {\n\tif arg.Reboot {\n\t\tglobalShutdownSignalCh <- shutdownRestart\n\t} else {\n\t\tglobalShutdownSignalCh <- shutdownHalt\n\t}\n\treturn nil\n}", "func (r *pReceiver) Shutdown(context.Context) error {\n\tif r.cancelFunc != nil {\n\t\tr.cancelFunc()\n\t}\n\tif r.scrapeManager != nil {\n\t\tr.scrapeManager.Stop()\n\t}\n\tclose(r.targetAllocatorStop)\n\treturn nil\n}", "func (s *tcpServerBase) Shutdown() {\n\tlog.WithField(\"name\", s.name).Debug(\"shutting down\")\n\tclose(s.quit)\n\t_ = s.listener.Close()\n}", "func (mc *MonitorCore) Shutdown() {\n\tatomic.StoreInt32(&mc.shutdownCalled, 1)\n\n\tmc.cancel()\n}", "func (w *worker) shutdown() {\n\tselect {\n\tcase w.shutdownc <- true:\n\tdefault:\n\t}\n}", "func (g *Generator) Shutdown(_ context.Context, _ *proto.EmptyRequest) (*proto.EmptyReply, error) {\n\tg.S.GracefulStop()\n\treturn &proto.EmptyReply{}, nil\n}", "func (sc *controller) Shutdown(ctx context.Context) error {\n\tsc.stopScraping()\n\n\t// wait until scraping ticker has terminated\n\tif sc.initialized {\n\t\t<-sc.terminated\n\t}\n\n\tvar errs []error\n\tfor _, scraper := range sc.resourceMetricScrapers {\n\t\tif err := scraper.Shutdown(ctx); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn consumererror.CombineErrors(errs)\n}", "func (w *Worker) Shutdown() {\n\tw.Stopped = true\n\tclose(w.stopChan)\n}", "func (pool *WorkPool) Shutdown() {\n\tif pool.IsShutDown() {\n\t\treturn\n\t}\n\tatomic.SwapUint32(&pool.isPoolOpen, poolClose)\n\t\n\tpool.isShutdownNow = false\n\tpool.stop <- true\n\t<- pool.stop\n\t\n\tclose(pool.stop)\n}", "func (m *Manager) Shutdown(ctx context.Context) error {\n\tinitShutdown := func() {\n\t\tctx, m.shutdownCancel = context.WithCancel(ctx)\n\t\tm.status <- StatusShutdown\n\t}\n\n\tvar isRunning bool\n\ts := <-m.status\n\tswitch s {\n\tcase StatusShutdown:\n\t\tm.status <- s\n\t\tselect {\n\t\tcase <-m.shutdownDone:\n\t\tcase <-ctx.Done():\n\t\t\t// if we timeout before the existing call, cancel it's context\n\t\t\tm.shutdownCancel()\n\t\t\t<-m.shutdownDone\n\t\t}\n\t\treturn m.shutdownErr\n\tcase StatusStarting:\n\t\tm.startupCancel()\n\t\tclose(m.pauseStart)\n\t\tinitShutdown()\n\t\t<-m.startupDone\n\tcase StatusUnknown:\n\t\tinitShutdown()\n\t\tclose(m.pauseStart)\n\t\tclose(m.shutdownDone)\n\t\treturn nil\n\tcase StatusPausing:\n\t\tisRunning = true\n\t\tm.pauseCancel()\n\t\tinitShutdown()\n\t\t<-m.pauseDone\n\tcase StatusReady:\n\t\tclose(m.pauseStart)\n\t\tfallthrough\n\tcase StatusPaused:\n\t\tisRunning = true\n\t\tinitShutdown()\n\t}\n\n\tdefer close(m.shutdownDone)\n\tdefer m.shutdownCancel()\n\n\terr := m.shutdownFunc(ctx)\n\n\tif isRunning {\n\t\tm.runCancel()\n\t\t<-m.runDone\n\t}\n\n\treturn err\n}", "func (m *Manager) Shutdown(context.Context) error {\n\tclose(m.shutdownCh)\n\tm.shutdownWg.Wait()\n\treturn nil\n}", "func (api *API) Shutdown() {\n\tc <- os.Interrupt\n}", "func (a *AbstractNetworkConnectionHandler) OnShutdown(_ context.Context) {}", "func (k *KeKahu) Shutdown() (err error) {\n\tinfo(\"shutting down the kekahu service\")\n\n\t// Shutdown the server\n\tif err = k.server.Shutdown(); err != nil {\n\t\tk.echan <- err\n\t}\n\n\t// Notify the run method we're done\n\t// NOTE: do this last or the cleanup proceedure won't be done.\n\tk.done <- true\n\treturn nil\n}", "func _shutdown(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Shutdown!\")\n\t//http.Shutdown(nil)\n}", "func (n *Notifier) Shutdown() {\n\tn.shutdown <- true\n}", "func (s *testDoQServer) Shutdown() {\n\t_ = s.listener.Close()\n}", "func (r *RuntimeImpl) Shutdown() {\n\tr.logger.Info(\"\\n\\n * Starting graceful shutdown\")\n\tr.logger.Info(\" * Waiting goroutines stop\")\n\tif r.slackWriter != nil {\n\t\tmessage, attachments := buildSlackShutdownMessage(r.dashboardTitle, false)\n\t\tr.slackWriter.PostNow(message, attachments)\n\t}\n\tr.syncManager.Stop()\n\tif r.impListener != nil {\n\t\tr.impListener.Stop(true)\n\t}\n\tr.appMonitor.Stop()\n\tr.servicesMonitor.Stop()\n\n\tr.logger.Info(\" * Shutdown complete - see you soon!\")\n\tr.blocker <- struct{}{}\n}", "func (acir *awsContainerInsightReceiver) Shutdown(context.Context) error {\n\tif acir.cancel == nil {\n\t\treturn nil\n\t}\n\tacir.cancel()\n\n\tvar errs error\n\n\tif acir.k8sapiserver != nil {\n\t\terrs = errors.Join(errs, acir.k8sapiserver.Shutdown())\n\t}\n\tif acir.cadvisor != nil {\n\t\terrs = errors.Join(errs, acir.cadvisor.Shutdown())\n\t}\n\n\treturn errs\n\n}", "func (rm *ResponseManager) Shutdown() {\n\trm.cancelFn()\n}", "func (sc *ServerConn) Shutdown() {\n\tsc.cancel()\n}", "func Shutdown() {\n\tglobalNotifier.Shutdown()\n}", "func (p *Pool) Shutdown() {\n\tif p.MonitorFunc != nil {\n\t\tgo p.MonitorFunc(newActionMsg(Shutdown))\n\t}\n\tfor {\n\t\tselect {\n\t\tcase res := <-p.resourceQueue:\n\t\t\t//Don't terminate in goroutine or caller may close the program before we\n\t\t\t//have had chance to call Terminate on all resources.\n\t\t\tres.Terminate()\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sr *sapmReceiver) Shutdown(context.Context) error {\n\tif sr.server == nil {\n\t\treturn nil\n\t}\n\terr := sr.server.Close()\n\tsr.shutdownWG.Wait()\n\treturn err\n}", "func (co *Coordinator) Shutdown() {\n\ttlog.Note.Print(\"Filthy little hobbites. They stole it from us. (shutdown)\")\n\n\tstateAtShutdown := co.state\n\tco.state = coordinatorStateShutdown\n\n\tco.shutdownConsumers(stateAtShutdown)\n\n\t// Make sure remaining warning / errors are written to stderr\n\ttlog.Note.Print(\"I'm not listening... I'm not listening... (flushing)\")\n\ttlog.SetWriter(os.Stdout)\n\n\t// Shutdown producers\n\tco.shutdownProducers(stateAtShutdown)\n\n\tco.state = coordinatorStateStopped\n}", "func (proxy *ProxyService) Shutdown(ctx context.Context) error {\n\tproxy.doTerminate()\n\tselect {\n\tcase <-proxy.doneCh:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn trace.Wrap(ctx.Err())\n\t}\n}", "func (p *Processor) Shutdown(_ context.Context) error {\n\tp.Logger.Infof(\"attempting graceful shutdown\")\n\tif p.isStopped() {\n\t\treturn ErrStopped\n\t}\n\n\tp.mu.Lock()\n\tp.stopped = true\n\tp.mu.Unlock()\n\n\tp.Logger.Infof(\"waiting up to %v for inflight events to finish processing\", waitShutdown)\n\treturn errors.Wrap(p.wg.WaitTimeout(waitShutdown), \"shutdown\")\n}", "func (c *Client) Shutdown() error {\n\tif _, err := c.httpPost(\"system/shutdown\", \"\"); err != nil {\n\t\treturn maskAny(err)\n\t}\n\treturn nil\n}", "func (s *Server) shutdown() error {\n\ts.shutdownLock.Lock()\n\tdefer s.shutdownLock.Unlock()\n\n\ts.unregister(s.initialEntry)\n\n\tif s.shouldShutdown {\n\t\treturn nil\n\t}\n\ts.shouldShutdown = true\n\n\ts.shutdownChan <- true\n\t//s.shutdownChanProbe <- true\n\n\tif s.ipv4conn != nil {\n\t\ts.ipv4conn.Close()\n\t}\n\tif s.ipv6conn != nil {\n\t\ts.ipv6conn.Close()\n\t}\n\n\tlog.Println(\"Waiting for goroutines to finish\")\n\ts.waitGroup.Wait()\n\n\treturn nil\n}", "func (brw *blockRetrievalWorker) Shutdown() {\n\tselect {\n\tcase <-brw.stopCh:\n\tdefault:\n\t\tclose(brw.stopCh)\n\t}\n}", "func (c *Cluster) Shutdown() {\n\tc.manager.quit()\n}", "func (p *Proxy) Shutdown() {\n\tlog.Info(\"Shutting down server gracefully\")\n\tclose(p.shutdown)\n\tgraceful.Shutdown()\n\tp.gRPCStop()\n}", "func (s *Server) Shutdown() error {\n\ts.ctxCancel()\n\treturn nil\n}", "func (h *Hookbot) Shutdown() {\n\tclose(h.shutdown)\n\th.wg.Wait()\n}", "func (monitor *TaskMonitor) Shutdown() error {\n\t// Close the events channel\n\tclose(monitor.EventsChannel)\n\n\t// Will close() the deliveries channel\n\tif err := monitor.channel.Cancel(monitor.consumerTag, true); err != nil {\n\t\treturn fmt.Errorf(\"failed to cancel monitor: %s\", err)\n\t}\n\n\tif err := monitor.connection.Close(); err != nil {\n\t\treturn fmt.Errorf(\"error closing AMQP connection: %s\", err)\n\t}\n\n\tdefer log.Printf(\"shutdown AMQP OK\")\n\n\t// Wait for handle() to exit\n\treturn <-monitor.done\n}", "func (f *Fs) Shutdown(ctx context.Context) error {\n\treturn f.multithread(ctx, func(ctx context.Context, u *upstream) error {\n\t\tif do := u.f.Features().Shutdown; do != nil {\n\t\t\treturn do(ctx)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (e EventStream) Shutdown() {\n\te.ctxCancel()\n}", "func (x *Pep) Shutdown() error {\n\tc := make(chan struct{})\n\tx.runQueue.Stop(func() { close(c) })\n\t<-c\n\treturn nil\n}", "func (p *Pool) Shutdown() chan bool {\n\tp.termSignal = make(chan bool)\n\tclose(p.taskQueue)\n\n\treturn p.termSignal\n}", "func (tc *Target) Shutdown() {\n\tclose(tc.shutdown)\n}", "func (dd *DefaultDriver) Shutdown(ctx context.Context) error {\n\treturn dd.Server.Shutdown(ctx)\n}", "func (h *healthcheckManager) shutdown() {\n\th.quit <- true\n\t<-h.stopped\n}", "func (a *Axon) Shutdown() {\n\ta.shutdownCh <- syscall.SIGTERM\n}", "func (l *LocalSDKServer) Shutdown(context.Context, *sdk.Empty) (*sdk.Empty, error) {\n\tlogrus.Info(\"Shutdown request has been received!\")\n\treturn &sdk.Empty{}, nil\n}", "func (srv *Server) Shutdown() {\n\tsrv.opsLock.Lock()\n\tsrv.shutdown = true\n\t// Don't block if there's no currently processed operations\n\tif srv.currentOps < 1 {\n\t\treturn\n\t}\n\tsrv.opsLock.Unlock()\n\t<-srv.shutdownRdy\n}", "func (c *Checker) Shutdown() {\n\tc.shutdown <- struct{}{}\n\tc.wg.Wait()\n}", "func (s *T) Shutdown() {\n\tif s.srv != nil {\n\t\ts.srv.Close()\n\t}\n}", "func (t *Trigger) Shutdown() {\n\tclose(t.closeChan)\n}", "func (h *ContainerImpl) Shutdown() {\n\tlogger.Trace(\"Container Handler shutting down...\")\n}", "func (c *LspConn) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}", "func (a *AbstractHandler) OnShutdown(_ context.Context) {\n}", "func (srv *Server) Shutdown(ctx context.Context) error {\n\tsrv.inShutdown.Store(true)\n\tsrv.mu.Lock()\n\tlnerr := srv.closeListenersLocked()\n\tsrv.closeDoneChanLocked()\n\n\tfor _, f := range srv.onShutdown {\n\t\tgo f()\n\t}\n\tsrv.mu.Unlock()\n\n\tticker := time.NewTicker(shutdownPollInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tif srv.closeIdleConns() {\n\t\t\treturn lnerr\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-ticker.C:\n\t\t}\n\t}\n}", "func (d *Driver) Shutdown(ctx context.Context) error {\n\treturn d.Server.Shutdown(ctx)\n}", "func (q *CoreClient) Shutdown(safe bool) (err error) {\n\tif safe {\n\t\t_, err = q.RequestWithoutData(http.MethodPost, \"/safeExit\", nil, nil, 200)\n\t} else {\n\t\t_, err = q.RequestWithoutData(http.MethodPost, \"/exit\", nil, nil, 200)\n\t}\n\treturn\n}", "func (s *Server) Shutdown() {\n\tclose(stop)\n}", "func (p *DirectBuy) Shutdown() {\n\tp.log.Info(\"Shutting down DirectBuy\")\n\tclose(p.quit)\n\tp.log.Info(\"Waiting for run to finish\")\n\t<-p.done\n\tp.log.Info(\"Shutdown complete\")\n}", "func (a *AbstractSessionChannelHandler) OnShutdown(_ context.Context) {}", "func shutdown(root *Task, mainTasks []*Task) func() {\n\treturn func() {\n\t\troot.Logger.Print(\"shutting down by closing Stopped channel on the root\")\n\t\tclose(root.Stopped)\n\t\texitcode := waitForTasksToDie(root, mainTasks)\n\t\tos.Exit(exitcode)\n\t}\n}", "func Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n}", "func (m *Machine) Shutdown(ctx context.Context) error {\n\tm.logger.Debug(\"Called machine.Shutdown()\")\n\treturn m.sendCtrlAltDel(ctx)\n}", "func (s *Scheduler) Shutdown() {\n\ts.state.mu.Lock()\n\tif s.state.value == srvStateNew || s.state.value == srvStateClosed {\n\t\t// scheduler is not running, do nothing and return.\n\t\ts.state.mu.Unlock()\n\t\treturn\n\t}\n\ts.state.value = srvStateClosed\n\ts.state.mu.Unlock()\n\n\ts.logger.Info(\"Scheduler shutting down\")\n\tclose(s.done) // signal heartbeater to stop\n\tctx := s.cron.Stop()\n\t<-ctx.Done()\n\ts.wg.Wait()\n\n\ts.clearHistory()\n\ts.client.Close()\n\ts.rdb.Close()\n\ts.logger.Info(\"Scheduler stopped\")\n}", "func (this *ReceiverHolder) Shutdown() error {\n\tfmt.Println(\"Shutting down Server...please wait.\")\n\tfmt.Println(\"######################################\")\n\tthis.receiver.Stop()\n\tfmt.Println(\"######################################\")\n\treturn nil\n}", "func (opt *GuacamoleHTTPTunnelMap) Shutdown() {\n\tfor _, c := range opt.executor {\n\t\tc.Stop()\n\t}\n\topt.executor = make([]*time.Ticker, 0, 1)\n}", "func (s *SrvSession) Shutdown(ctx context.Context) {\n\tif s.srv != nil {\n\t\tif err := s.srv.Shutdown(ctx); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Warningf(\"Shutdown for [%v] %v\", s.listenAddr, err)\n\t\t}\n\t}\n}", "func (n *NodeosMonitor) Shutdown(ctx context.Context) {\n\tn.failover.Shutdown(ctx)\n\tn.leaseManager.Shutdown(ctx)\n\tn.httpServer.Close()\n\tlogrus.Infof(\"all processes have been shut down\")\n}", "func (bft *ProtocolBFTCoSi) Shutdown() error {\n\tdefer func() {\n\t\t// In case the channels were already closed\n\t\trecover()\n\t}()\n\tbft.setClosing()\n\tclose(bft.announceChan)\n\tclose(bft.challengePrepareChan)\n\tclose(bft.challengeCommitChan)\n\tif !bft.IsLeaf() {\n\t\tclose(bft.commitChan)\n\t\tclose(bft.responseChan)\n\t}\n\treturn nil\n}", "func (s *Service) Shutdown() {\n\tlog.Debugln(s.name, \"- Service shutting down...\")\n\n\ts.lk.Lock()\n\tif s.state != Started {\n\t\ts.lk.Unlock()\n\t\treturn\n\t}\n\ts.state = Stopping\n\ts.lk.Unlock()\n\n\tclose(s.shutdown)\n\t<-s.done\n\tlog.Debugln(s.name, \"- Service was shut down\")\n}", "func Shutdown() {\n\tlm().shutdown()\n}", "func (r *otlpReceiver) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\tif r.serverHTTP != nil {\n\t\terr = r.serverHTTP.Shutdown(ctx)\n\t}\n\n\tif r.serverGRPC != nil {\n\t\tr.serverGRPC.GracefulStop()\n\t}\n\n\tr.shutdownWG.Wait()\n\treturn err\n}", "func (r *otlpReceiver) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\tif r.serverHTTP != nil {\n\t\terr = r.serverHTTP.Shutdown(ctx)\n\t}\n\n\tif r.serverGRPC != nil {\n\t\tr.serverGRPC.GracefulStop()\n\t}\n\n\tr.shutdownWG.Wait()\n\treturn err\n}", "func (c *TimeoutChan) Shutdown() {\n\tclose(c.in)\n\tc.pushCtrl.Shutdown()\n\tclose(c.closePush)\n\tc.popCtrl.Shutdown()\n\tclose(c.out)\n\tclose(c.resumePush)\n\tclose(c.resumePop)\n\tclose(c.reschedule)\n}", "func callback() {\n\tlog.Println(\"shutdown requested\")\n}", "func (wq *queuedWorkerPool[T, U]) Shutdown() {\n\tif !wq.isShutdown.CompareAndSwap(false, true) {\n\t\treturn\n\t}\n\n\tfor i := 0; i < wq.workers; i++ {\n\t\twq.queue.Enqueue(entry[T, U]{\n\t\t\tclose: true,\n\t\t})\n\t}\n}", "func (r *Raft) Shutdown(ctx context.Context) error {\n\tr.doClose(ErrServerClosed)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-r.closed:\n\t\treturn nil\n\t}\n}", "func (e *EntryPoint) Shutdown(ctx context.Context, code int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcancelFn()\n\tif _, ok := ctx.Deadline(); ok {\n\t\t<-ctx.Done()\n\t}\n\tos.Exit(code)\n}", "func (c *Connector) Shutdown() error {\n\tc.NATS().Close()\n\treturn nil\n}", "func (h *HealthImpl) Shutdown() {\n\th.isPreparingShutdown = false\n\tlogger.Trace(\"Health Handler shutting down...\")\n}", "func (sc *serverConfig) Shutdown() {\n\tlog.Println(\"shutting down http server...\")\n\tsc.Shutdown()\n}", "func (factory *Factory) Shutdown() {\n\tfactory.shutdownInProgress = true\n\t// If the cleanup flag is present don't do any cleanup\n\tif !factory.options.cleanup {\n\t\treturn\n\t}\n\n\t// Wait 15 seconds before running all shutdown handlers to ensure everything can catch up.\n\ttime.Sleep(15 * time.Second)\n\terr := factory.CleanupChaosMeshExperiments()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfactory.invariantShutdownHooks.InvokeShutdownHandlers()\n\tfactory.shutdownHooks.InvokeShutdownHandlers()\n}", "func (a *App) Shutdown() {\n\ta.shutdown <- syscall.SIGTERM\n}", "func (b *GithubBridge) Shutdown(ctx context.Context) error {\n\treturn nil\n}", "func (s *Switch) Shutdown() {\n\ts.shutdownOnce.Do(func() {\n\t\ts.cancelFunc()\n\t\ts.discover.Shutdown()\n\t\ts.cPool.Shutdown()\n\t\ts.network.Shutdown()\n\t\t// udpServer (udpMux) shuts down the udpnet as well\n\t\ts.udpServer.Shutdown()\n\t\ts.peersWatcher.Close()\n\t\ts.gossip.Close()\n\n\t\tfor i := range s.directProtocolHandlers {\n\t\t\tdelete(s.directProtocolHandlers, i)\n\t\t\t//close(prt) //todo: signal protocols to shutdown with closing chan. (this makes us send on closed chan.)\n\t\t}\n\t\tfor i := range s.gossipProtocolHandlers {\n\t\t\tdelete(s.gossipProtocolHandlers, i)\n\t\t\t//close(prt) //todo: signal protocols to shutdown with closing chan. (this makes us send on closed chan.)\n\t\t}\n\n\t\ts.peerLock.Lock()\n\t\tfor _, ch := range s.newPeerSub {\n\t\t\tclose(ch)\n\t\t}\n\t\tfor _, ch := range s.delPeerSub {\n\t\t\tclose(ch)\n\t\t}\n\t\ts.delPeerSub = nil\n\t\ts.newPeerSub = nil\n\t\ts.peerLock.Unlock()\n\t\tif s.releaseUpnp != nil {\n\t\t\ts.releaseUpnp()\n\t\t}\n\t\ts.logger.Info(\"waiting for switch goroutines to finish\")\n\t\ts.eg.Wait()\n\t\ts.logger.Info(\"switch goroutines finished\")\n\t})\n}", "func (t *taskQueue) shutdown() {\n\tt.queue.ShutDown()\n\t<-t.workerDone\n}", "func (i *Instance) Shutdown() {\n\t// Shutdown all dependencies\n\ti.Service.Shutdown()\n\n\t// Shutdown HTTP server\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\terr := i.httpServer.Shutdown(ctx)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Failed to shutdown HTTP server gracefully\")\n\t\tos.Exit(1)\n\t}\n\n\tlogrus.Info(\"Shutdown HTTP server...\")\n\tos.Exit(0)\n}", "func (e *Etcd) Shutdown() error {\n\tetcdStopped := e.etcd.Server.StopNotify()\n\te.etcd.Close()\n\t<-etcdStopped\n\treturn nil\n}", "func (e *Engine) Shutdown() {\n\te.shutdown <- true\n}", "func (h *Hub) Shutdown() {\n\th.shutdown <- struct{}{}\n\n\t// Wait for stop listening channels\n\th.done.Wait()\n}" ]
[ "0.77749574", "0.74859995", "0.7293281", "0.7045941", "0.70429516", "0.69103533", "0.68971735", "0.6863724", "0.6858713", "0.6847161", "0.68009514", "0.67958325", "0.67107534", "0.66885036", "0.66786605", "0.6673801", "0.66667897", "0.66601294", "0.6658383", "0.66421247", "0.6629118", "0.6628106", "0.6623596", "0.66117555", "0.6605853", "0.6602719", "0.65860045", "0.6582118", "0.6576561", "0.65686804", "0.6563532", "0.65543205", "0.65325356", "0.65319186", "0.6530011", "0.65260893", "0.6515372", "0.65136266", "0.65117234", "0.65064263", "0.6503708", "0.6502577", "0.64836305", "0.64830923", "0.64643764", "0.64626193", "0.6459521", "0.6458298", "0.64317024", "0.6426755", "0.64259756", "0.6420884", "0.64153624", "0.64131385", "0.6411994", "0.6402724", "0.6400856", "0.6394736", "0.63946074", "0.6392932", "0.63868314", "0.63860893", "0.63738114", "0.635064", "0.6345436", "0.63443416", "0.63439554", "0.63358784", "0.6335376", "0.633352", "0.633232", "0.63259864", "0.63255566", "0.6320109", "0.63179666", "0.6311706", "0.6297141", "0.62971294", "0.6295219", "0.62942415", "0.628404", "0.6276873", "0.6276873", "0.6270706", "0.6269145", "0.62683994", "0.626569", "0.62655216", "0.62634003", "0.6261209", "0.6257024", "0.6255492", "0.62521744", "0.6244148", "0.622655", "0.6218464", "0.62146306", "0.62133986", "0.6209287", "0.62067133" ]
0.7389451
2
assumes that caller has obtained state lock
func (k *KubernetesExecutor) doShutdown(driver bindings.ExecutorDriver) { defer func() { log.Errorf("exiting with unclean shutdown: %v", recover()) if k.exitFunc != nil { k.exitFunc(1) } }() (&k.state).transitionTo(terminalState) // signal to all listeners that this KubeletExecutor is done! close(k.done) if k.shutdownAlert != nil { func() { util.HandleCrash() k.shutdownAlert() }() } log.Infoln("Stopping executor driver") _, err := driver.Stop() if err != nil { log.Warningf("failed to stop executor driver: %v", err) } log.Infoln("Shutdown the executor") // according to docs, mesos will generate TASK_LOST updates for us // if needed, so don't take extra time to do that here. k.tasks = map[string]*kuberTask{} select { // the main Run() func may still be running... wait for it to finish: it will // clear the pod configuration cleanly, telling k8s "there are no pods" and // clean up resources (pods, volumes, etc). case <-k.kubeletFinished: //TODO(jdef) attempt to wait for events to propagate to API server? // TODO(jdef) extract constant, should be smaller than whatever the // slave graceful shutdown timeout period is. case <-time.After(15 * time.Second): log.Errorf("timed out waiting for kubelet Run() to die") } log.Infoln("exiting") if k.exitFunc != nil { k.exitFunc(0) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r GopassRepo) lockState(payload []byte) error { return nil }", "func (s *SharedState) unlock() {\n s.mutex.Unlock()\n}", "func (*S) Lock() {}", "func (*Item) Lock() {}", "func (s *SharedState) lock() *SharedState {\n s.mutex.Lock()\n return s\n}", "func (*NoCopy) Lock() {}", "func (d delegate) LocalState(join bool) []byte { return nil }", "func (e *Enumerate) lock() {\n\te.u.m.Lock()\n}", "func (*noCopy) Lock() {}", "func (r *Radix) lock() {\n\tif r.ts {\n\t\tr.mu.Lock()\n\t}\n}", "func (q *RxQueue) lock() {\n\tq.pendingMutex.Lock()\n}", "func (e *neighborEntry) setStateLocked(next NeighborState) {\n\te.cancelTimerLocked()\n\n\tprev := e.mu.neigh.State\n\te.mu.neigh.State = next\n\te.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\n\tconfig := e.nudState.Config()\n\n\tswitch next {\n\tcase Incomplete:\n\t\tpanic(fmt.Sprintf(\"should never transition to Incomplete with setStateLocked; neigh = %#v, prev state = %s\", e.mu.neigh, prev))\n\n\tcase Reachable:\n\t\t// Protected by e.mu.\n\t\tdone := false\n\n\t\te.mu.timer = timer{\n\t\t\tdone: &done,\n\t\t\ttimer: e.cache.nic.stack.Clock().AfterFunc(e.nudState.ReachableTime(), func() {\n\t\t\t\te.mu.Lock()\n\t\t\t\tdefer e.mu.Unlock()\n\n\t\t\t\tif done {\n\t\t\t\t\t// The timer was stopped because the entry changed state.\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\te.setStateLocked(Stale)\n\t\t\t\te.dispatchChangeEventLocked()\n\t\t\t}),\n\t\t}\n\n\tcase Delay:\n\t\t// Protected by e.mu.\n\t\tdone := false\n\n\t\te.mu.timer = timer{\n\t\t\tdone: &done,\n\t\t\ttimer: e.cache.nic.stack.Clock().AfterFunc(config.DelayFirstProbeTime, func() {\n\t\t\t\te.mu.Lock()\n\t\t\t\tdefer e.mu.Unlock()\n\n\t\t\t\tif done {\n\t\t\t\t\t// The timer was stopped because the entry changed state.\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\te.setStateLocked(Probe)\n\t\t\t\te.dispatchChangeEventLocked()\n\t\t\t}),\n\t\t}\n\n\tcase Probe:\n\t\t// Protected by e.mu.\n\t\tdone := false\n\n\t\tremaining := config.MaxUnicastProbes\n\t\taddr := e.mu.neigh.Addr\n\t\tlinkAddr := e.mu.neigh.LinkAddr\n\n\t\t// Send a probe in another gorountine to free this thread of execution\n\t\t// for finishing the state transition. This is necessary to escape the\n\t\t// currently held lock so we can send the probe message without holding\n\t\t// a shared lock.\n\t\te.mu.timer = timer{\n\t\t\tdone: &done,\n\t\t\ttimer: e.cache.nic.stack.Clock().AfterFunc(immediateDuration, func() {\n\t\t\t\tvar err tcpip.Error = &tcpip.ErrTimeout{}\n\t\t\t\tif remaining != 0 {\n\t\t\t\t\terr = e.cache.linkRes.LinkAddressRequest(addr, tcpip.Address{} /* localAddr */, linkAddr)\n\t\t\t\t}\n\n\t\t\t\te.mu.Lock()\n\t\t\t\tdefer e.mu.Unlock()\n\n\t\t\t\tif done {\n\t\t\t\t\t// The timer was stopped because the entry changed state.\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\te.setStateLocked(Unreachable)\n\t\t\t\t\te.notifyCompletionLocked(err)\n\t\t\t\t\te.dispatchChangeEventLocked()\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tremaining--\n\t\t\t\te.mu.timer.timer.Reset(config.RetransmitTimer)\n\t\t\t}),\n\t\t}\n\n\tcase Unreachable:\n\n\tcase Unknown, Stale, Static:\n\t\t// Do nothing\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Invalid state transition from %q to %q\", prev, next))\n\t}\n}", "func (r GopassRepo) unlockState(payload []byte) error { return nil }", "func Lock() {\n\tlock.Lock()\n}", "func SyncRuntimeDoSpin()", "func (x *XcChaincode) lock(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) < 3 {\n\t\treturn shim.Error(\"Params Error\")\n\t}\n\t//get operator\n\tsender, err := stub.GetSender()\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t} else if sender == \"\" {\n\t\treturn shim.Error(\"Account not exist\")\n\t}\n\ttoPlatform := strings.ToLower(args[0])\n\ttoAccount := strings.ToLower(args[1])\n\tamount := big.NewInt(0)\n\t_, ok := amount.SetString(args[2], 10)\n\tif !ok {\n\t\treturn shim.Error(\"Expecting integer value for amount\")\n\t}\n\n\t//try to get state from book which key is variable toPlatform's value\n\tplatState, err := stub.GetState(toPlatform)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get platform: \" + err.Error())\n\t} else if platState == nil {\n\t\treturn shim.Error(\"The platform named \" + toPlatform + \" is not registered\")\n\t}\n\n\t//set txId to be key\n\tkey := stub.GetTxID()\n\t//do transfer\n\terr = stub.Transfer(x.tacTokenAddr, \"TAB\", amount)\n\tif err != nil {\n\t\treturn shim.Error(\"Transfer error \" + err.Error())\n\t}\n\ttxTimestamp, err := stub.GetTxTimestamp()\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\ttimeStr := fmt.Sprintf(\"%d\", txTimestamp.GetSeconds())\n\t//build turn out state\n\tstate := x.buildTurnOutMessage(sender, toPlatform, toAccount, amount, timeStr)\n\terr = stub.PutState(key, state)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t//build composite key\n\tindexName := \"type~address~datetime~platform~key\"\n\tindexKey, err := stub.CreateCompositeKey(indexName, []string{\"out\", sender, timeStr, x.platName, key})\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tvalue := []byte{0x00}\n\tstub.PutState(indexKey, value)\n\n\t//sign\n\tsignJson, err := x.signJson([]byte(\"abc\"), \"60320b8a71bc314404ef7d194ad8cac0bee1e331\")\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\treturn shim.Success(signJson)\n}", "func (rf *Raft) GetState() (int, bool) {\n\n var term int\n var isleader bool\n // Your code here (2A).\n rf.mu.Lock()\n term = rf.currentTerm\n isleader = (rf.state == StateLeader)\n rf.mu.Unlock()\n return term, isleader\n}", "func (e Locked) IsLocked() {}", "func (rf *Raft) GetState() (int, bool) {\n\n var term int\n var isleader bool\n // Your code here (2A).\n rf.mu.Lock()\n defer rf.mu.Unlock()\n term = rf.currentTerm\n isleader = false\n if rf.state == LEADER {\n isleader = true\n }\n return term, isleader\n}", "func (am *AccountManager) Grab() {\n\t<-am.bsem\n}", "func GetCurrentState() {\n\n}", "func (m *MutexSafe) lock() {\n\tm.Mutex.Lock()\n}", "func (c *CycleState) Lock() {\n\tc.mx.Lock()\n}", "func initLockNames() {}", "func (w *writer) updateStateLocked(overrideBusy bool, consumed int) {\n\tw.free.IncN(uint(consumed))\n\n\t// The w.isActive state does not depend on the deficit.\n\tisActive := (w.size == 0 && w.isClosed) ||\n\t\t(w.size != 0 && (w.released < 0 || w.contents.Front().(*iobuf.Slice).Size() <= w.released))\n\tw.q.updateWriterState(w, overrideBusy, isActive, consumed)\n}", "func idle() State_t {\n\t\n}", "func (d *mlDelegate) LocalState(bool) []byte { return nil }", "func (rf *Raft) GetState() (int, bool) {\n\n var term int\n var isleader bool\n\n rf.mu.Lock()\n defer rf.mu.Unlock()\n term = rf.currentTerm\n isleader = false\n if rf.state == Leader {\n isleader = true\n } \n\n // Your code here (2A).\n return term, isleader\n}", "func (p AMQPClient) State() chan bool {\n\treturn p.stateUpdates\n}", "func (obj *cancel) Lock() hash.Hash {\n\treturn obj.lock\n}", "func (d *Dam) Lock() {\n\td.freeze.Lock()\n}", "func (p Pin) Lock() {\n\tp.Port().Lock(Pin0 << p.index())\n}", "func (e *endpointMap) lock() func() {\n\te.mu.Lock()\n\treturn func() { e.mu.Unlock() }\n}", "func (c *CheckedLock) Lock() {\n\tc.lock.Lock()\n\tc.locked = true\n}", "func MWAIT() { ctx.MWAIT() }", "func (rw *RWMutex) AssertHeld() {\n}", "func (this *DeployLock) start() {\n\tthis.mutex.Lock()\n\tthis.numStarted++\n\tthis.mutex.Unlock()\n}", "func (wt *Wallet) Lock() {\n\twt.lockRequests <- struct{}{}\n}", "func (h *schedulerHelper) lockCallBack() {\n\tglog.V(3).Infof(\"lockCallBack--Expired lock for pod[%s], parent[%s]\", h.podName, h.controllerName)\n\t// check whether need to do reset scheduler\n\tif !(h.flag) {\n\t\treturn\n\t}\n\n\t// check whether the scheduler has been changed.\n\tscheduler, err := h.getSchedulerName(h.client, h.nameSpace, h.controllerName)\n\tif err != nil || scheduler != h.schedulerNone {\n\t\treturn\n\t}\n\n\t// restore the original scheduler\n\tinterval := defaultUpdateSchedulerSleep\n\ttimeout := time.Duration(defaultRetryMore+1) * interval\n\tutil.RetryDuring(defaultRetryMore, timeout, interval, func() error {\n\t\t_, err := h.updateSchedulerName(h.client, h.nameSpace, h.controllerName, h.scheduler)\n\t\treturn err\n\t})\n\n\treturn\n}", "func (this *Peer) update() {\n\t// ping the peer\n\t// we do this outside the lock to avoid communication latency in the lock\n\tonline := this.protocol.ping(this.id)\n\n\tthis.mu.Lock()\n\tif online && this.status == STATUS_OFFLINE {\n\t\tLog.Info.Printf(\"Peer %s came online\", this.id.String())\n\t\tthis.status = STATUS_ONLINE\n\t} else if !online && this.status == STATUS_ONLINE {\n\t\tLog.Info.Printf(\"Peer %s went offline\", this.id.String())\n\t\tthis.status = STATUS_OFFLINE\n\t}\n\n\tverificationDelay := 300 * time.Second\n\tif Debug {\n\t\tverificationDelay = time.Second\n\t}\n\n\tvar randomShard *BlockShardId\n\tif time.Now().After(this.lastVerifyTime.Add(verificationDelay)) {\n\t\tthis.lastVerifyTime = time.Now()\n\n\t\t// pick a random shard to verify\n\t\tavailableShards := make([]BlockShardId, 0)\n\t\tfor shardId, available := range this.shardsAccounted {\n\t\t\tif available {\n\t\t\t\tavailableShards = append(availableShards, shardId)\n\t\t\t}\n\t\t}\n\n\t\tif len(availableShards) > 0 {\n\t\t\trandomShard = &availableShards[rand.Intn(len(availableShards))]\n\t\t}\n\t}\n\tthis.mu.Unlock()\n\n\tif randomShard != nil {\n\t\tLog.Debug.Printf(\"Verifying shard %d on peer %s\", *randomShard, this.id.String())\n\t\tbytes, success := this.retrieveShard(*randomShard)\n\n\t\tif !success || !this.fluidBackup.blockStore.VerifyShard(this, *randomShard, bytes) {\n\t\t\t// either we failed to communicate with the peer (if !success),\n\t\t\t// or the peer sent us corrupted shard data (if success)\n\t\t\tfailReason := \"invalid shard data\"\n\t\t\tif !success {\n\t\t\t\tfailReason = \"peer communication failed\"\n\t\t\t}\n\t\t\tLog.Info.Printf(\"Failed verification of shard %d on peer %s: %s\", *randomShard, this.id.String(), failReason)\n\n\t\t\tthis.mu.Lock()\n\t\t\tif success {\n\t\t\t\t// shard is invalid, delete from remote end\n\t\t\t\t// block store will re-assign it already from the verifyshard call, so don't need to do anything else about that\n\t\t\t\tdelete(this.shardsAccounted, *randomShard)\n\t\t\t\tgo this.deleteShard(*randomShard)\n\t\t\t}\n\n\t\t\t// we also check if this peer is failed per our one-day policy, in which case we would want to clear all accounted shards\n\t\t\tthis.verifyFailCount++\n\t\t\tif this.verifyFailCount > 5 && time.Now().After(this.lastVerifySuccessTime.Add(time.Second * VERIFY_FAIL_WAIT_INTERVAL)) {\n\t\t\t\tgo this.terminateAgreement()\n\t\t\t}\n\t\t\tthis.mu.Unlock()\n\n\t\t\t// Decrease trust\n\t\t\tthis.peerList.UpdateTrustPostVerification(this.id, false)\n\t\t} else {\n\t\t\tthis.peerList.UpdateTrustPostVerification(this.id, true)\n\n\t\t\tthis.mu.Lock()\n\t\t\tthis.verifyFailCount = 0\n\t\t\tthis.lastVerifySuccessTime = time.Now()\n\t\t\tthis.mu.Unlock()\n\t\t}\n\t}\n}", "func internalAcquire(fm *filemutex.FileMutex) chan error {\n\tresult := make(chan error)\n\tgo func() {\n\t\tif err := fm.Lock(); err != nil {\n\t\t\tresult <- err\n\t\t}\n\t\tclose(result)\n\t}()\n\treturn result\n}", "func (w *Wallet) Lock() {\n\tw.lockRequests <- struct{}{}\n}", "func Lock() {\n\tmutex.Lock()\n}", "func (*dir) Lock(pid, locktype, flags int, start, length uint64, client string) error {\n\treturn nil\n}", "func (in *inMemorySink) acquire() {\n\t<-in.token\n}", "func lockItUp() {\n\twait := make(chan struct{})\n\tvar n AtomicInt\n\tgo func() {\n\t\tn.Add(1) // one access.\n\t\tclose(wait)\n\t}()\n\tn.Add(1) // another concurrent access.\n\t<-wait\n\tfmt.Println(n.Value())\n}", "func Unlock() {\n\t// TO DO\n}", "func LockOSThread() {\n}", "func (_m *StateOps) RefreshTaskState() {\n\t_m.Called()\n}", "func (c *client) state(me NodeID) (state *State, err error) {\n\terr = c.client.Call(\"Server.State\", me, &state)\n\tfor err == rpc.ErrShutdown {\n\t\terr = c.client.Call(\"Server.State\", me, &state)\n\t}\n\treturn\n}", "func (g *glock) Lock() context.Context {\n\tvar (\n\t\tkv goku.KV\n\t\terr error\n\t)\n\n\tg.mt.Lock()\n\tg.waiting = true\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tg.cancel = cancel\n\n\tfor {\n\t\tfor {\n\t\t\tkv, err = g.gok.Get(ctx, g.key)\n\t\t\tif errors.Is(err, goku.ErrNotFound) {\n\t\t\t\t// First set so there's no key\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(string(kv.Value), \"locked\") {\n\t\t\t\tg.awaitRetry()\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Case for fist time trying to acquire lock.\n\t\tif err != nil {\n\t\t\terr = g.gok.Set(ctx, g.key, []byte(\"locked_\"+g.processID),\n\t\t\t\tgoku.WithCreateOnly(),\n\t\t\t\tgoku.WithExpiresAt(time.Now().Add(time.Second*20)))\n\t\t} else {\n\t\t\terr = g.gok.Set(ctx, g.key, []byte(\"locked_\"+g.processID),\n\t\t\t\tgoku.WithPrevVersion(kv.Version),\n\t\t\t\tgoku.WithExpiresAt(time.Now().Add(time.Second*20)))\n\t\t}\n\n\t\tif err != nil {\n\t\t\t// retry\n\t\t\tcontinue\n\t\t}\n\n\t\t// ensure the lock is ours\n\t\tkv, err = g.gok.Get(ctx, g.key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sanity check, paranoid\n\t\tif string(kv.Value) != \"locked_\"+g.processID {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.locked = true\n\t\tgo g.keepAlive(ctx)\n\t\treturn ctx\n\t}\n}", "func (c *cluster) reset() error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\t// Reset all transactions to their original state.\n\tfor id := range c.txnRecords {\n\t\tr := c.txnRecords[id]\n\t\tr.mu.Lock()\n\t\tr.updatedStatus = roachpb.PENDING\n\t\tr.updatedTimestamp = hlc.Timestamp{}\n\t\tr.mu.Unlock()\n\t}\n\t// There should be no remaining concurrency guards.\n\tfor name := range c.guardsByReqName {\n\t\treturn errors.Errorf(\"unfinished guard for request: %s\", name)\n\t}\n\t// There should be no outstanding latches.\n\tglobal, local := c.m.LatchMetrics()\n\tif global.ReadCount > 0 || global.WriteCount > 0 ||\n\t\tlocal.ReadCount > 0 || local.WriteCount > 0 {\n\t\treturn errors.Errorf(\"outstanding latches\")\n\t}\n\t// Clear the lock table by transferring the lease away and reacquiring it.\n\tc.m.OnRangeLeaseUpdated(1, false /* isLeaseholder */)\n\tc.m.OnRangeLeaseUpdated(1, true /* isLeaseholder */)\n\treturn nil\n}", "func (kss *keyspaceState) ensureConsistentLocked() {\n\t// if this keyspace is consistent, there's no ongoing availability event\n\tif kss.consistent {\n\t\treturn\n\t}\n\n\tif kss.moveTablesState != nil && kss.moveTablesState.Typ != MoveTablesNone && kss.moveTablesState.State != MoveTablesSwitched {\n\t\treturn\n\t}\n\n\t// get the topology metadata for our primary from `lastKeyspace`; this value is refreshed\n\t// from our topology watcher whenever a change is detected, so it should always be up to date\n\tprimary := topoproto.SrvKeyspaceGetPartition(kss.lastKeyspace, topodatapb.TabletType_PRIMARY)\n\n\t// if there's no primary, the keyspace is unhealthy;\n\t// if there are ShardTabletControls active, the keyspace is undergoing a topology change;\n\t// either way, the availability event is still ongoing\n\tif primary == nil || len(primary.ShardTabletControls) > 0 {\n\t\treturn\n\t}\n\n\tactiveShardsInPartition := make(map[string]bool)\n\n\t// iterate through all the primary shards that the topology server knows about;\n\t// for each shard, if our HealthCheck stream hasn't found the shard yet, or\n\t// if the HealthCheck stream still thinks the shard is unhealthy, this\n\t// means the availability event is still ongoing\n\tfor _, shard := range primary.ShardReferences {\n\t\tsstate := kss.shards[shard.Name]\n\t\tif sstate == nil || !sstate.serving {\n\t\t\treturn\n\t\t}\n\t\tactiveShardsInPartition[shard.Name] = true\n\t}\n\n\t// iterate through all the shards as seen by our HealthCheck stream. if there are any\n\t// shards that HealthCheck thinks are healthy, and they haven't been seen by the topology\n\t// watcher, it means the keyspace is not fully consistent yet\n\tfor shard, sstate := range kss.shards {\n\t\tif sstate.serving && !activeShardsInPartition[shard] {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// clone the current moveTablesState, if any, to handle race conditions where it can get updated while we're broadcasting\n\tvar moveTablesState MoveTablesState\n\tif kss.moveTablesState != nil {\n\t\tmoveTablesState = *kss.moveTablesState\n\t}\n\n\tksevent := &KeyspaceEvent{\n\t\tCell: kss.kew.localCell,\n\t\tKeyspace: kss.keyspace,\n\t\tShards: make([]ShardEvent, 0, len(kss.shards)),\n\t\tMoveTablesState: moveTablesState,\n\t}\n\n\t// we haven't found any inconsistencies between the HealthCheck stream and the topology\n\t// watcher. this means the ongoing availability event has been resolved, so we can broadcast\n\t// a resolution event to all listeners\n\tkss.consistent = true\n\n\tkss.moveTablesState = nil\n\n\tfor shard, sstate := range kss.shards {\n\t\tksevent.Shards = append(ksevent.Shards, ShardEvent{\n\t\t\tTablet: sstate.currentPrimary,\n\t\t\tTarget: sstate.target,\n\t\t\tServing: sstate.serving,\n\t\t})\n\n\t\tlog.Infof(\"keyspace event resolved: %s/%s is now consistent (serving: %v)\",\n\t\t\tsstate.target.Keyspace, sstate.target.Keyspace,\n\t\t\tsstate.serving,\n\t\t)\n\n\t\tif !sstate.serving {\n\t\t\tdelete(kss.shards, shard)\n\t\t}\n\t}\n\n\tkss.kew.broadcast(ksevent)\n}", "func (a *ActStatus) updateLocked(address arry.Address) types.IAccount {\n\tact := a.db.Account(address)\n\tact.UpdateLocked(a.confirmed)\n\treturn act\n}", "func (lockedCtx *UserCtx) State() (aka.AkaState, time.Time) {\n\tif !lockedCtx.locked {\n\t\tpanic(\"Expected locked\")\n\t}\n\treturn lockedCtx.state, lockedCtx.stateTime\n}", "func (r *ResourceLock) init() bool {\n\tif r.listing == nil {\n\t\tr.masterLock.Lock()\n\t\tdefer r.masterLock.Unlock()\n\t\t// double check, per pattern\n\t\tif r.listing == nil {\n\t\t\tr.listing = make(map[interface{}]*sync.Mutex)\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *Player) lock() {\n\tp.chLock <- struct{}{}\n}", "func StateConnectorCall(blockTime *big.Int, checkRet []byte, availableLedger uint64) bool {\n\tif len(checkRet) != 96 {\n\t\treturn false\n\t}\n\tinstructions := ParseInstructions(checkRet, availableLedger)\n\tif instructions.InitialCommit {\n\t\tgo func() {\n\t\t\tacceptedPath, rejectedPath := GetVerificationPaths(checkRet[8:])\n\t\t\t_, errACCEPTED := os.Stat(acceptedPath)\n\t\t\tif errACCEPTED != nil {\n\t\t\t\tif ReadChainWithRetries(blockTime, instructions) {\n\t\t\t\t\tverificationHashStore, err := os.Create(acceptedPath)\n\t\t\t\t\tverificationHashStore.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Permissions problem\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tverificationHashStore, err := os.Create(rejectedPath)\n\t\t\t\t\tverificationHashStore.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Permissions problem\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\treturn true\n\t} else {\n\t\tacceptedPath, rejectedPath := GetVerificationPaths(checkRet[8:])\n\t\t_, errACCEPTED := os.Stat(acceptedPath)\n\t\t_, errREJECTED := os.Stat(rejectedPath)\n\t\tif errACCEPTED != nil && errREJECTED != nil {\n\t\t\tfor i := 0; i < 2*apiRetries; i++ {\n\t\t\t\t_, errACCEPTED = os.Stat(acceptedPath)\n\t\t\t\t_, errREJECTED = os.Stat(rejectedPath)\n\t\t\t\tif errACCEPTED == nil || errREJECTED == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(apiRetryDelay)\n\t\t\t}\n\t\t}\n\t\treturn errACCEPTED == nil\n\t}\n}", "func (tm *TabletManager) lock(ctx context.Context) error {\n\treturn tm.actionSema.Acquire(ctx, 1)\n}", "func (w *xcWallet) state() *WalletState {\n\twinfo := w.Info()\n\n\tw.mtx.RLock()\n\tvar peerCount uint32\n\tif w.peerCount > 0 { // initialized to -1 initially, means no count yet\n\t\tpeerCount = uint32(w.peerCount)\n\t}\n\n\tvar tokenApprovals map[uint32]asset.ApprovalStatus\n\tif w.connector.On() {\n\t\ttokenApprovals = w.ApprovalStatus()\n\t}\n\n\tstate := &WalletState{\n\t\tSymbol: unbip(w.AssetID),\n\t\tAssetID: w.AssetID,\n\t\tVersion: winfo.Version,\n\t\tOpen: len(w.encPass) == 0 || len(w.pw) > 0,\n\t\tRunning: w.connector.On(),\n\t\tBalance: w.balance,\n\t\tAddress: w.address,\n\t\tUnits: winfo.UnitInfo.AtomicUnit,\n\t\tEncrypted: len(w.encPass) > 0,\n\t\tPeerCount: peerCount,\n\t\tSynced: w.synced,\n\t\tSyncProgress: w.syncProgress,\n\t\tWalletType: w.walletType,\n\t\tTraits: w.traits,\n\t\tDisabled: w.disabled,\n\t\tApproved: tokenApprovals,\n\t}\n\tw.mtx.RUnlock()\n\n\tif w.parent != nil {\n\t\tw.parent.mtx.RLock()\n\t\tstate.Open = len(w.parent.encPass) == 0 || len(w.parent.pw) > 0\n\t\tw.parent.mtx.RUnlock()\n\t}\n\n\treturn state\n}", "func (self *Map) lock() {\n\tif self.atomic == nil {\n\t\tself.atomic = new(sync.Mutex)\n\t}\n\n\tself.atomic.Lock()\n}", "func (m *Mutex) AssertHeld() {\n}", "func event() {\n lock.Lock()\n defer lock.Unlock()\n if group != nil {\n group.Event()\n }\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (heap *SkewHeap) lock() { heap.mutex.Lock() }", "func (marketApp *MarketPlaceApp) LockUse() error {\n return marketApp.Lock(1)\n}", "func (marketApp *MarketPlaceApp) LockUse() error {\n return marketApp.Lock(1)\n}", "func process() *os.Process {\n lock.Lock()\n defer lock.Unlock()\n return proc\n}", "func (s *Stopper) refuseRLocked() bool {\n\treturn s.mu.stopping || s.mu.quiescing\n}", "func (txs *TxSerializer) lockLocked(ctx context.Context, key, table string) (bool, error) {\n\tq, ok := txs.queues[key]\n\tif !ok {\n\t\t// First transaction in the queue i.e. we don't wait and return immediately.\n\t\ttxs.queues[key] = newQueueForFirstTransaction(txs.concurrentTransactions)\n\t\ttxs.globalSize++\n\t\treturn false, nil\n\t}\n\n\tif txs.globalSize >= txs.maxGlobalQueueSize {\n\t\tif txs.dryRun {\n\t\t\ttxs.globalQueueExceededDryRun.Add(1)\n\t\t\ttxs.logGlobalQueueExceededDryRun.Warningf(\"Would have rejected BeginExecute RPC because there are too many queued transactions (%d >= %d)\", txs.globalSize, txs.maxGlobalQueueSize)\n\t\t} else {\n\t\t\ttxs.globalQueueExceeded.Add(1)\n\t\t\treturn false, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED,\n\t\t\t\t\"hot row protection: too many queued transactions (%d >= %d)\", txs.globalSize, txs.maxGlobalQueueSize)\n\t\t}\n\t}\n\n\tif q.size >= txs.maxQueueSize {\n\t\tif txs.dryRun {\n\t\t\ttxs.queueExceededDryRun.Add(table, 1)\n\t\t\tif txs.env.Config().SanitizeLogMessages {\n\t\t\t\ttxs.logQueueExceededDryRun.Warningf(\"Would have rejected BeginExecute RPC because there are too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')\", q.size, txs.maxQueueSize, txs.sanitizeKey(key))\n\t\t\t} else {\n\t\t\t\ttxs.logQueueExceededDryRun.Warningf(\"Would have rejected BeginExecute RPC because there are too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')\", q.size, txs.maxQueueSize, key)\n\t\t\t}\n\t\t} else {\n\t\t\ttxs.queueExceeded.Add(table, 1)\n\t\t\tif txs.env.Config().TerseErrors {\n\t\t\t\treturn false, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED,\n\t\t\t\t\t\"hot row protection: too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')\", q.size, txs.maxQueueSize, txs.sanitizeKey(key))\n\t\t\t}\n\t\t\treturn false, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED,\n\t\t\t\t\"hot row protection: too many queued transactions (%d >= %d) for the same row (table + WHERE clause: '%v')\", q.size, txs.maxQueueSize, key)\n\t\t}\n\t}\n\n\tif q.availableSlots == nil {\n\t\t// Hot row detected: A second, concurrent transaction is seen for the\n\t\t// first time.\n\n\t\t// As an optimization, we deferred the creation of the channel until now.\n\t\tq.availableSlots = make(chan struct{}, txs.concurrentTransactions)\n\t\tq.availableSlots <- struct{}{}\n\n\t\t// Include first transaction in the count at /debug/hotrows. (It was not\n\t\t// recorded on purpose because it did not wait.)\n\t\ttxs.Record(key)\n\t}\n\n\ttxs.globalSize++\n\tq.size++\n\tq.count++\n\tif q.size > q.max {\n\t\tq.max = q.size\n\t}\n\t// Publish the number of waits at /debug/hotrows.\n\ttxs.Record(key)\n\n\tif txs.dryRun {\n\t\ttxs.waitsDryRun.Add(table, 1)\n\t\tif txs.env.Config().SanitizeLogMessages {\n\t\t\ttxs.logWaitsDryRun.Warningf(\"Would have queued BeginExecute RPC for row (range): '%v' because another transaction to the same range is already in progress.\", txs.sanitizeKey(key))\n\t\t} else {\n\t\t\ttxs.logWaitsDryRun.Warningf(\"Would have queued BeginExecute RPC for row (range): '%v' because another transaction to the same range is already in progress.\", key)\n\t\t}\n\t\treturn false, nil\n\t}\n\n\t// Unlock before the wait and relock before returning because our caller\n\t// Wait() holds the lock and assumes it still has it.\n\ttxs.mu.Unlock()\n\tdefer txs.mu.Lock()\n\n\t// Non-blocking write attempt to get a slot.\n\tselect {\n\tcase q.availableSlots <- struct{}{}:\n\t\t// Return waited=false because a slot was immediately available.\n\t\treturn false, nil\n\tdefault:\n\t}\n\n\t// Blocking wait for the next available slot.\n\ttxs.waits.Add(table, 1)\n\tselect {\n\tcase q.availableSlots <- struct{}{}:\n\t\treturn true, nil\n\tcase <-ctx.Done():\n\t\treturn true, ctx.Err()\n\t}\n}", "func GetAndLockState(q sqlx.Ext, customerId, checkId string) (*State, error) {\n\tstate := &State{}\n\terr := sqlx.Get(q, state, \"SELECT states.state_id, states.customer_id, states.check_id, states.state_name, states.time_entered, states.last_updated, checks.min_failing_count, checks.min_failing_time, states.failing_count, states.response_count FROM check_states AS states JOIN checks ON (checks.id = states.check_id) WHERE states.customer_id = $1 AND checks.id = $2 FOR UPDATE OF states\", customerId, checkId)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn nil, err\n\t}\n\n\tif err == sql.ErrNoRows {\n\t\t// Get the check so that we can get MinFailingCount and MinFailingTime\n\t\t// Return an error if the check doesn't exist\n\t\t// check, err := store.GetCheck(customerId, checkId)\n\t\tcheck := &schema.Check{}\n\t\terr := sqlx.Get(q, check, \"SELECT id, customer_id, min_failing_count, min_failing_time FROM checks WHERE customer_id = $1 AND id = $2\", customerId, checkId)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstate = &State{\n\t\t\tCheckId: checkId,\n\t\t\tCustomerId: customerId,\n\t\t\tId: StateOK,\n\t\t\tState: StateOK.String(),\n\t\t\tTimeEntered: time.Now(),\n\t\t\tLastUpdated: time.Now(),\n\t\t\tMinFailingCount: check.MinFailingCount,\n\t\t\tMinFailingTime: time.Duration(check.MinFailingTime) * time.Second,\n\t\t\tFailingCount: 0,\n\t\t}\n\t}\n\n\tstate.MinFailingTime = state.MinFailingTime * time.Second\n\n\treturn state, nil\n}", "func (p *proxy) checkState() error {\n\tp.adminConn.writeCmd(\"CLUSTER INFO\")\n\treply, err := p.adminConn.readReply()\n\tif err != nil {\n\t\treturn err\n\t}\n\treply_body := reply.([]uint8)\n\tfor _, line := range strings.Split(string(reply_body), \"\\r\\n\") {\n\t\tline_arr := strings.Split(line, \":\")\n\t\tif line_arr[0] == \"cluster_state\" {\n\t\t\tif line_arr[1] != \"ok\" {\n\t\t\t\treturn protocolError(string(reply_body))\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn protocolError(\"checkState should never run up to here\")\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func writersLock() {\n\tlog.Info(\"Acquiring lock\")\n\tmutex.Lock()\n\tlog.Info(\"Acquired\")\n}", "func (r *ReceiveFuncState) Open() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tr.started = true\n\tr.running = true\n\tselfCheckLocked()\n}", "func (t *task) State() State {\n\tv := atomic.LoadInt32(&t.state)\n\treturn State(v)\n}", "func (g GoroutineLock) Check() {\n\tif getGoroutineID() != goroutineID(g) {\n\t\tpanic(\"running on the wrong goroutine\")\n\t}\n}", "func (g GoroutineLock) CheckNotOn() {\n\tif getGoroutineID() == goroutineID(g) {\n\t\tpanic(\"running on the wrong goroutine\")\n\t}\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func (c *ChannelBucket) Lock() {\n\tc.mutex.Lock()\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (w *Writer) lock() error {\n\tw.mutex.Lock()\n\tif w.tar == nil {\n\t\tw.mutex.Unlock()\n\t\treturn errors.New(\"Internal error: trying to use an already closed tarfile.Writer\")\n\t}\n\treturn nil\n}", "func (g *Github) modLock() {\n\tg.modMutex.Lock()\n\tshouldWait := time.Second - time.Since(g.lastModRequest)\n\tif shouldWait > 0 {\n\t\tlog.Debugf(\"Waiting %s to not hit GitHub ratelimit\", shouldWait)\n\t\ttime.Sleep(shouldWait)\n\t}\n}", "func (e *localfileExec) setState(state execState, err error) {\n\te.mu.Lock()\n\te.state = state\n\te.err = err\n\te.cond.Broadcast()\n\te.mu.Unlock()\n}", "func (mdl *Model) Lock() {\n\tmdl.locked = true\n}", "func (r *RedisDL) lock(ctx context.Context) error {\n\tr.m.Lock()\n\tdefer r.m.Unlock()\n\ttoken, err := randToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\tretry := time.NewTimer(r.opt.LockTimeout)\n\tatts := r.opt.RetryCount + 1\n\tfor {\n\t\tif err := r.storeToken(token); err == nil {\n\t\t\tr.currentToken = token\n\t\t\treturn nil\n\t\t}\n\t\tif atts--; atts <= 0 {\n\t\t\treturn fmt.Errorf(\"unable to generate token\")\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-retry.C:\n\t\t}\n\t}\n}", "func (c *Context) acquire() {\n\tc.world.acquire(&c.req)\n\tc.req.copy()\n}", "func (l *Lock) Lock() {\n\tl.ch <- struct{}{}\n}", "func entersyscallblock()", "func (rw *RWMutex) AssertRHeld() {\n}", "func (c *MockedHTTPContext) Lock() {\n\tif c.MockedLock != nil {\n\t\tc.MockedLock()\n\t}\n}", "func (s *Scheduler) lockService() {\n\ts.serviceLock.Lock()\n}", "func checkExistingState() error {\n\n\t// In case any previous volumes are present\n\t// clean up is needed\n\n\tvols, err := client.ListVolumes()\n\tif err != nil {\n\t\trwolog.Error(\"Error while listing volumes \", err)\n\t\treturn err\n\t}\n\n\tpeers, err := client.PeerStatus()\n\tif err != nil {\n\t\trwolog.Error(\"Error while checking gluster Pool list\", err.Error())\n\t\treturn err\n\t}\n\n\tif len(vols) >= 1 || len(peers) >= 1 {\n\t\t// check if the current member has any previous volumes/peers associated with it.\n\t\t// if yes, then check if the member is joining previous cluster,\n\t\t// else remove the volumes and join the cluster\n\t\terr = checkOldStateOfGluster()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (ts *trySet) state() trySetState {\n\tts.mu.Lock()\n\tdefer ts.mu.Unlock()\n\treturn ts.trySetState.clone()\n}", "func (t *TrudyPipe) Lock() {\n\tt.userMutex.Lock()\n}", "func (g *glock) Unlock() {\n\tdefer func() {\n\t\t// Cancel the context when this returns\n\t\tif g.cancel != nil {\n\t\t\tg.cancel()\n\t\t\tg.cancel = nil\n\t\t}\n\t}()\n\tif !g.locked {\n\t\t// Called Unlock without actually having the lock,\n\t\t// do nothing or risk overriding someone else's lock\n\t\treturn\n\t}\n\tdefer g.mt.Unlock()\n\tg.waiting = false\n\n\tfor {\n\t\t// ensure the lock is ours\n\t\tkv, err := g.gok.Get(context.Background(), g.key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sanity check, that the lock is ours\n\t\tif string(kv.Value) != \"locked_\"+g.processID {\n\t\t\treturn\n\t\t}\n\n\t\terr = g.gok.Set(context.Background(), g.key, []byte(\"unlocked\"))\n\t\tif err == nil {\n\t\t\tg.locked = false\n\t\t\treturn\n\t\t}\n\t}\n}", "func (*Item) Unlock() {}", "func (inst *Instancer) State() sd.Event {\n\treturn inst.cache.State()\n}", "func suspend() {}", "func (t *task) changeState(from, to State) bool {\n\treturn atomic.CompareAndSwapInt32(&t.state, int32(from), int32(to))\n}", "func (this *DeployLock) value() int {\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\treturn this.numStarted\n}" ]
[ "0.69092983", "0.6534878", "0.6440702", "0.6406376", "0.639457", "0.6273028", "0.6153657", "0.60759884", "0.60344356", "0.59434104", "0.5915108", "0.57914233", "0.5769212", "0.57299584", "0.5726385", "0.5710375", "0.5692428", "0.56667316", "0.56556684", "0.5642097", "0.5637544", "0.55404097", "0.55351746", "0.55319476", "0.55263895", "0.5496858", "0.54932106", "0.5490152", "0.5485245", "0.5483427", "0.5478078", "0.5475897", "0.5472066", "0.54708266", "0.54478455", "0.54475075", "0.544576", "0.5433832", "0.5424933", "0.54198694", "0.54140663", "0.54109764", "0.54041433", "0.54033315", "0.539963", "0.53952384", "0.5385889", "0.53808105", "0.53749937", "0.53632325", "0.5356716", "0.53516924", "0.5348977", "0.53485686", "0.5337693", "0.5334801", "0.53147894", "0.5311377", "0.53071964", "0.53041327", "0.5303549", "0.5291555", "0.52914447", "0.52815294", "0.52783895", "0.5258501", "0.5258501", "0.5256132", "0.5255924", "0.5246854", "0.52441686", "0.5238924", "0.5237694", "0.52371114", "0.523483", "0.5234678", "0.5231178", "0.52290875", "0.52283114", "0.52282757", "0.52208924", "0.52197695", "0.52191347", "0.5213923", "0.5211675", "0.5199266", "0.51990515", "0.51967794", "0.5192291", "0.5190707", "0.5189856", "0.5173715", "0.5173578", "0.5168025", "0.5166087", "0.5148213", "0.5145507", "0.5144572", "0.5144154", "0.51407003", "0.5139907" ]
0.0
-1
Destroy existing k8s containers
func (k *KubernetesExecutor) killKubeletContainers() { if containers, err := dockertools.GetKubeletDockerContainers(k.dockerClient, true); err == nil { opts := docker.RemoveContainerOptions{ RemoveVolumes: true, Force: true, } for _, container := range containers { opts.ID = container.ID log.V(2).Infof("Removing container: %v", opts.ID) if err := k.dockerClient.RemoveContainer(opts); err != nil { log.Warning(err) } } } else { log.Warningf("Failed to list kubelet docker containers: %v", err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Docker) Destroy(ctx context.Context, name string) error {\n\treturn d.localClient.ContainerStop(ctx, name, nil)\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 Clean(ctx context.Context, containerIDs []string, removeImages bool, removeVolumes bool, withNginx bool, cli *client.Client, logger *zap.Logger) error {\n\tlogger.Debug(\"down\", zap.Strings(\"ids\", containerIDs), zap.Bool(\"rmi\", removeImages), zap.Bool(\"rm -v\", removeVolumes), zap.Bool(\"with-nginx\", withNginx))\n\n\tcontainersInfo, err := GetContainersInfo(ctx, cli)\n\tif err != nil {\n\t\treturn errcode.ErrComposeGetContainersInfo.Wrap(err)\n\t}\n\n\ttoRemove := map[string]container{}\n\n\tif withNginx && containersInfo.NginxContainer.ID != \"\" {\n\t\ttoRemove[containersInfo.NginxContainer.ID] = containersInfo.NginxContainer\n\t}\n\n\tif len(containerIDs) == 0 { // all containers\n\t\tfor _, container := range containersInfo.RunningContainers {\n\t\t\ttoRemove[container.ID] = container\n\t\t}\n\t} else { // only specific ones\n\t\tfor _, id := range containerIDs {\n\t\t\tfor _, flavor := range containersInfo.RunningFlavors {\n\t\t\t\tif id == flavor.Name || id == flavor.ChallengeID() {\n\n\t\t\t\t\tfor _, container := range flavor.Containers {\n\t\t\t\t\t\ttoRemove[container.ID] = container\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, container := range containersInfo.RunningContainers {\n\t\t\t\tif id == container.ID || id == container.ID[0:7] {\n\t\t\t\t\ttoRemove[container.ID] = container\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, container := range toRemove {\n\t\terr := cli.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t\tRemoveVolumes: removeVolumes,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errcode.ErrDockerAPIContainerRemove.Wrap(err)\n\t\t}\n\t\tlogger.Debug(\"container removed\", zap.String(\"ID\", container.ID))\n\t\tif removeImages {\n\t\t\t_, err := cli.ImageRemove(ctx, container.ImageID, types.ImageRemoveOptions{\n\t\t\t\tForce: false,\n\t\t\t\tPruneChildren: true,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn errcode.ErrDockerAPIImageRemove.Wrap(err)\n\t\t\t}\n\t\t\tlogger.Debug(\"image removed\", zap.String(\"ID\", container.ImageID))\n\t\t}\n\t}\n\n\tif withNginx && containersInfo.NginxNetwork.ID != \"\" {\n\t\terr = cli.NetworkRemove(ctx, containersInfo.NginxNetwork.ID)\n\t\tif err != nil {\n\t\t\treturn errcode.ErrDockerAPINetworkRemove.Wrap(err)\n\t\t}\n\t\tlogger.Debug(\"network removed\", zap.String(\"ID\", containersInfo.NginxNetwork.ID))\n\t}\n\n\treturn nil\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 (c *Module) Delete(ns string, id pkg.ContainerID) error {\n\tlog.Debug().Str(\"id\", string(id)).Str(\"ns\", ns).Msg(\"delete container\")\n\n\tclient, err := containerd.New(c.containerd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\t// log.Debug().Msg(\"fetching namespace\")\n\tctx := namespaces.WithNamespace(context.Background(), ns)\n\n\t// log.Debug().Str(\"id\", string(id)).Msg(\"fetching container\")\n\tcontainer, err := client.LoadContainer(ctx, string(id))\n\tif err != nil {\n\t\treturn err\n\t}\n\tspec, err := container.Spec(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't load container spec\")\n\t}\n\tshutdownTimeout := defaultShutdownTimeout\n\tshutdownTimeoutStr, ok := spec.Annotations[\"shutdown_timeout\"]\n\tif ok {\n\t\tshutdownTimeoutUint64, err := strconv.ParseUint(shutdownTimeoutStr, 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"shutdown_timeout\", shutdownTimeoutStr).Err(err).Msg(\"couldn't parse shutdown timeout\")\n\t\t} else {\n\t\t\tshutdownTimeout = time.Duration(shutdownTimeoutUint64)\n\t\t}\n\t}\n\t// mark this container as perminant down. so the watcher\n\t// does not try to restart it again\n\tc.failures.Set(string(id), permanent, cache.DefaultExpiration)\n\n\ttask, err := container.Task(ctx, nil)\n\tif err == nil {\n\t\t// err == nil, there is a task running inside the container\n\t\texitC, err := task.Wait(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Debug().Str(\"id\", string(id)).Int(\"signal\", int(syscall.SIGTERM)).Msg(\"sending signal\")\n\t\t_ = task.Kill(ctx, syscall.SIGTERM)\n\t\tselect {\n\t\tcase <-exitC:\n\t\tcase <-time.After(time.Duration(shutdownTimeout)):\n\t\t\tlog.Debug().Str(\"id\", string(id)).Int(\"signal\", int(syscall.SIGKILL)).Msg(\"sending signal\")\n\t\t\t_ = task.Kill(ctx, syscall.SIGKILL)\n\t\t\tselect {\n\t\t\tcase <-exitC:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t\tlog.Warn().Str(\"id\", string(id)).Msg(\"didn't receive container exit signal after SIGKILLing\")\n\t\t\t}\n\t\t}\n\n\t\tif _, err := task.Delete(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn container.Delete(ctx)\n}", "func WhiskDestroy() error {\n\tSys(\"docker exec iosdk-openwhisk stop\")\n\tfmt.Println(\"Destroying Whisk: iosdk-openwhisk\")\n\treturn nil\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 killContainers(killCommand []string) {\n\n\tkilledContainersBytes, err := executer.GetCommandOutput(killCommand)\n\tif err != nil {\n\t\tlogger.Fatal(\"Error when trying to destroy container(s):\", utils.ExtractContainerMessage(killedContainersBytes, err))\n\t}\n\n\tkilledContainers := strings.TrimSpace(string(killedContainersBytes))\n\tlogger.Notice(\"Kill command output:\\n%v\", killedContainers)\n\n}", "func CleanupAllContainers() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// only grab the containers created by easycontainers\n\targs := filters.NewArgs()\n\targs.Add(\"name\", prefix)\n\n\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\tAll: true,\n\t\tFilters: args,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, container := range containers {\n\t\tfmt.Println(\"Killing and Removing Container\", container.ID[:10])\n\n\t\tif err := cli.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{\n\t\t\tForce: true,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}", "func (p Pipeline) KillContainers(preRun bool) error {\n\t_, _, _, err := p.runCommand(runConfig{\n\t\tselection: func(step Step) bool {\n\t\t\treturn !preRun || step.Meta.KeepAlive != KeepAliveReplace\n\t\t},\n\t\trun: func(runner Runner, step Step) func() error {\n\t\t\treturn func() error {\n\t\t\t\tif _, err := runner.ContainerKiller(step)(); err != nil {\n\t\t\t\t\tpipelineLogger.Printf(\"Error killing %s: %s\", step.ColoredName(), err)\n\t\t\t\t}\n\t\t\t\tif err := runner.ContainerRemover(step)(); err != nil {\n\t\t\t\t\tpipelineLogger.Printf(\"Error removing %s: %s\", step.ColoredName(), err)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t},\n\t})\n\treturn err\n}", "func (c *Container) Destroy() error {\n\treturn c.dockerClient.ForceRemove(c.id)\n}", "func RemoveLiveContainersFromPreviousRun() {\n\n\treadObj, err := mapsi2disk.ReadContainerPortsFromDisk(mapsi2disk.GobFilename)\n\treadBackOwnedContainers := readObj.(map[string]int)\n\n\tif err == nil {\n\t\tdefer mapsi2disk.DeleteFile(mapsi2disk.GobFilename)\n\n\t\tdockerClient := GetDockerClient()\n\n\t\tfor containerID := range readBackOwnedContainers {\n\t\t\tlog.Printf(\"Deleting container: %v from previous launch.\\n\", containerID)\n\t\t\terr = dockerClient.ContainerStop(context.Background(), containerID, nil)\n\t\t}\n\t}\n}", "func KillKubeletContainers(dockerClient dockertools.DockerInterface) {\n\tif containers, err := dockertools.GetKubeletDockerContainers(dockerClient, true); err == nil {\n\t\topts := docker.RemoveContainerOptions{\n\t\t\tRemoveVolumes: true,\n\t\t\tForce: true,\n\t\t}\n\t\tfor _, container := range containers {\n\t\t\topts.ID = container.ID\n\t\t\tlog.V(2).Infof(\"Removing container: %v\", opts.ID)\n\t\t\tif err := dockerClient.RemoveContainer(opts); err != nil {\n\t\t\t\tlog.Warning(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Warningf(\"Failed to list kubelet docker containers: %v\", err)\n\t}\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 Cleanup() {\n\tclient := DockerClient()\n\tif list, err := CleanupDockerImageList(); err == nil {\n\t\tfor _, i := range list {\n\t\t\tclient.RemoveImage(i.ID)\n\t\t}\n\t}\n\tif list, err := CleanupDockerContainersList(); err == nil {\n\t\tfor _, c := range list {\n\t\t\topts := dockerclient.RemoveContainerOptions{ID: c.ID}\n\t\t\tclient.RemoveContainer(opts)\n\t\t}\n\t}\n}", "func (c *K8sConfig) Destroy() error {\n\tc.log.Info(\"Destroy Kubernetes configuration\", \"ref\", c.config.Name, \"config\", c.config.Paths)\n\n\t// Not sure we should do this at the moment, since it is not possible to partially destroy.\n\t// Destruction of a K8s cluster will delete any config associated\n\t// When we implement the DAG for state re-imnplement this code\n\t/*\n\t\terr := c.setup()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.client.Delete(c.config.Paths)\n\t*/\n\n\treturn nil\n}", "func cleanUpCnsRegisterVolumeInstances(ctx context.Context, restClientConfig *rest.Config, timeInMin int) {\n\tlog := logger.GetLogger(ctx)\n\tlog.Infof(\"cleanUpCnsRegisterVolumeInstances: start\")\n\tcnsOperatorClient, err := k8s.NewClientForGroup(ctx, restClientConfig, cnsoperatorv1alpha1.GroupName)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to create CnsOperator client. Err: %+v\", err)\n\t\treturn\n\t}\n\n\t// Get list of CnsRegisterVolume instances from all namespaces\n\tcnsRegisterVolumesList := &cnsregistervolumev1alpha1.CnsRegisterVolumeList{}\n\terr = cnsOperatorClient.List(ctx, cnsRegisterVolumesList)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to get CnsRegisterVolumes from supervisor cluster. Err: %+v\", err)\n\t\treturn\n\t}\n\n\tcurrentTime := time.Now()\n\tfor _, cnsRegisterVolume := range cnsRegisterVolumesList.Items {\n\t\tvar elapsedMinutes float64 = currentTime.Sub(cnsRegisterVolume.CreationTimestamp.Time).Minutes()\n\t\tif cnsRegisterVolume.Status.Registered && int(elapsedMinutes)-timeInMin >= 0 {\n\t\t\terr = cnsOperatorClient.Delete(ctx, &cnsregistervolumev1alpha1.CnsRegisterVolume{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: cnsRegisterVolume.Name,\n\t\t\t\t\tNamespace: cnsRegisterVolume.Namespace,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Failed to delete CnsRegisterVolume: %s on namespace: %s. Error: %v\",\n\t\t\t\t\tcnsRegisterVolume.Name, cnsRegisterVolume.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Infof(\"Successfully deleted CnsRegisterVolume: %s on namespace: %s\",\n\t\t\t\tcnsRegisterVolume.Name, cnsRegisterVolume.Namespace)\n\t\t}\n\t}\n}", "func (r *Rkt) KillContainers(ids []string) error {\n\treturn killCRIContainers(r.Runner, ids)\n}", "func destroyContainer(id string) error {\n\tdisplay.StartTask(\"Destroying docker container\")\n\tdefer display.StopTask()\n\n\t// if i dont know the id then i cant remove it\n\tif id == \"\" {\n\t\treturn nil\n\t}\n\n\tif err := docker.ContainerRemove(id); err != nil {\n\t\tlumber.Error(\"component:Destroy:docker.ContainerRemove(%s): %s\", id, err.Error())\n\t\tdisplay.ErrorTask()\n\t\t// return util.ErrorAppend(err, \"failed to remove docker container\")\n\t}\n\n\treturn nil\n}", "func Teardown() {\n\tfmt.Println(\"====== Clean kubernetes testing pod ======\")\n\tres, err := kubeclient.ExecKubectl(\"kubectl delete pod -l app=nsenter\")\n\tfmt.Println(res)\n\tif err != nil {\n\t\tfmt.Println(\"Error: \" + err.Error())\n\t}\n}", "func containerGCTest(f *framework.Framework, test testRun) {\n\tvar runtime internalapi.RuntimeService\n\tginkgo.BeforeEach(func() {\n\t\tvar err error\n\t\truntime, _, err = getCRIClient()\n\t\tframework.ExpectNoError(err)\n\t})\n\tfor _, pod := range test.testPods {\n\t\t// Initialize the getContainerNames function to use CRI runtime client.\n\t\tpod.getContainerNames = func() ([]string, error) {\n\t\t\trelevantContainers := []string{}\n\t\t\tcontainers, err := runtime.ListContainers(context.Background(), &runtimeapi.ContainerFilter{\n\t\t\t\tLabelSelector: map[string]string{\n\t\t\t\t\ttypes.KubernetesPodNameLabel: pod.podName,\n\t\t\t\t\ttypes.KubernetesPodNamespaceLabel: f.Namespace.Name,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn relevantContainers, err\n\t\t\t}\n\t\t\tfor _, container := range containers {\n\t\t\t\trelevantContainers = append(relevantContainers, container.Labels[types.KubernetesContainerNameLabel])\n\t\t\t}\n\t\t\treturn relevantContainers, nil\n\t\t}\n\t}\n\n\tginkgo.Context(fmt.Sprintf(\"Garbage Collection Test: %s\", test.testName), func() {\n\t\tginkgo.BeforeEach(func(ctx context.Context) {\n\t\t\trealPods := getPods(test.testPods)\n\t\t\te2epod.NewPodClient(f).CreateBatch(ctx, realPods)\n\t\t\tginkgo.By(\"Making sure all containers restart the specified number of times\")\n\t\t\tgomega.Eventually(ctx, func(ctx context.Context) error {\n\t\t\t\tfor _, podSpec := range test.testPods {\n\t\t\t\t\terr := verifyPodRestartCount(ctx, f, podSpec.podName, podSpec.numContainers, podSpec.restartCount)\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}\n\t\t\t\treturn nil\n\t\t\t}, setupDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t})\n\n\t\tginkgo.It(\"Should eventually garbage collect containers when we exceed the number of dead containers per container\", func(ctx context.Context) {\n\t\t\ttotalContainers := 0\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\ttotalContainers += pod.numContainers*2 + 1\n\t\t\t}\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\ttotal := 0\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\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\ttotal += len(containerNames)\n\t\t\t\t\t// Check maxPerPodContainer for each container in the pod\n\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif containerCount > maxPerPodContainer+1 {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"expected number of copies of container: %s, to be <= maxPerPodContainer: %d; list of containers: %v\",\n\t\t\t\t\t\t\t\tpod.getContainerName(i), maxPerPodContainer, containerNames)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Check maxTotalContainers. Currently, the default is -1, so this will never happen until we can configure maxTotalContainers\n\t\t\t\tif maxTotalContainers > 0 && totalContainers <= maxTotalContainers && total > maxTotalContainers {\n\t\t\t\t\treturn fmt.Errorf(\"expected total number of containers: %v, to be <= maxTotalContainers: %v\", total, maxTotalContainers)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif maxPerPodContainer >= 2 && maxTotalContainers < 0 { // make sure constraints wouldn't make us gc old containers\n\t\t\t\tginkgo.By(\"Making sure the kubelet consistently keeps around an extra copy of each container.\")\n\t\t\t\tgomega.Consistently(ctx, func() error {\n\t\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif pod.restartCount > 0 && containerCount < maxPerPodContainer+1 {\n\t\t\t\t\t\t\t\treturn fmt.Errorf(\"expected pod %v to have extra copies of old containers\", pod.podName)\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\treturn nil\n\t\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t\t}\n\t\t})\n\n\t\tginkgo.AfterEach(func(ctx context.Context) {\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\tginkgo.By(fmt.Sprintf(\"Deleting Pod %v\", pod.podName))\n\t\t\t\te2epod.NewPodClient(f).DeleteSync(ctx, pod.podName, metav1.DeleteOptions{}, e2epod.DefaultPodDeletionTimeout)\n\t\t\t}\n\n\t\t\tginkgo.By(\"Making sure all containers get cleaned up\")\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\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 len(containerNames) > 0 {\n\t\t\t\t\t\treturn fmt.Errorf(\"%v containers still remain\", containerNames)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif ginkgo.CurrentSpecReport().Failed() && framework.TestContext.DumpLogsOnFailure {\n\t\t\t\tlogNodeEvents(ctx, f)\n\t\t\t\tlogPodEvents(ctx, f)\n\t\t\t}\n\t\t})\n\t})\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 (engine *EngineOperations) CleanupContainer() error {\n\treturn nil\n}", "func (e *ContainerService) Delete(name string) (err error) {\n\turl := fmt.Sprintf(\"containers/%s\", name)\n\terr = e.client.magicRequestDecoder(\"DELETE\", url, nil, nil)\n\treturn\n}", "func TeardownContainers(containers []*Container) {\n\tvar wg sync.WaitGroup\n\n\t// Add all the container names\n\twg.Add(len(containers))\n\n\tfor _, container := range containers {\n\t\tlog.Printf(\"Now tearing down container %v\\n\", container)\n\n\t\tgo teardownContainer(&wg, container)\n\t}\n\n\twg.Wait()\n}", "func Destroy(dev *model.Dev, c *kubernetes.Clientset) error {\n\tlog.Infof(\"deleting deployment '%s'\", dev.Name)\n\tdClient := c.AppsV1().Deployments(dev.Namespace)\n\terr := dClient.Delete(dev.Name, &metav1.DeleteOptions{GracePeriodSeconds: &devTerminationGracePeriodSeconds})\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"not found\") {\n\t\t\tlog.Infof(\"deployment '%s' was already deleted.\", dev.Name)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error deleting kubernetes deployment: %s\", err)\n\t}\n\tlog.Infof(\"deployment '%s' deleted\", dev.Name)\n\treturn nil\n}", "func ContainerCleanup(appName string) error {\n\terr := docker.DeleteContainer(appName)\n\tif err != nil {\n\t\tutils.LogError(err)\n\t}\n\treturn err\n}", "func (p *Provider) shutdown() error {\n\tcs, err := containersByLabels(map[string]string{\n\t\t\"convox.rack\": p.Name,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar wg sync.WaitGroup\n\n\tfor _, c := range cs {\n\t\twg.Add(1)\n\t\tgo p.containerStopAsync(c.Id, &wg)\n\t}\n\n\twg.Wait()\n\n\tos.Exit(0)\n\n\treturn nil\n}", "func execStopContainerOnGc(sshClientConfig *ssh.ClientConfig, svcMasterIP string, containerName string,\n\tgcMasterIP string, svcNamespace string) error {\n\tsshSecretName := GetAndExpectStringEnvVar(sshSecretName)\n\tcmdToGetPrivateKey := fmt.Sprintf(\"kubectl get secret %s -n %s -o\"+\n\t\t\"jsonpath={'.data.ssh-privatekey'} | base64 -d > key\", sshSecretName, svcNamespace)\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetPrivateKey,\n\t\tsvcMasterIP)\n\tcmdResult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetPrivateKey)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetPrivateKey, svcMasterIP, err)\n\t}\n\n\tenablePermissionCmd := \"chmod 600 key\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", enablePermissionCmd,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tenablePermissionCmd)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tenablePermissionCmd, svcMasterIP, err)\n\t}\n\n\tcmdToGetContainerInfo := fmt.Sprintf(\"ssh -o 'StrictHostKeyChecking=no' -i key %s@%s \"+\n\t\t\"'sudo -i crictl ps| grep %s' > container.log 2> /dev/null\", gcNodeUser, gcMasterIP, containerName)\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetContainerInfo,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetContainerInfo)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetContainerInfo, svcMasterIP, err)\n\t}\n\n\tcmdToGetContainerId := \"cat container.log | awk '{print $1}' | tr -d '\\n'\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetContainerInfo,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetContainerId)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetContainerId, svcMasterIP, err)\n\t}\n\tcontainerID := cmdResult.Stdout\n\n\tcontainerStopCmd := fmt.Sprintf(\"ssh -o 'StrictHostKeyChecking=no' -i key %s@%s \"+\n\t\t\"'sudo -i crictl stop %s' 2> /dev/null\", gcNodeUser, gcMasterIP, containerID)\n\tframework.Logf(\"Invoking command '%v' on host %v\", containerStopCmd,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcontainerStopCmd)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcontainerStopCmd, svcMasterIP, err)\n\t}\n\n\t// delete the temporary log file\n\tcmd := \"rm container.log\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\tsvcMasterIP)\n\tresult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\tcmd)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmd, svcMasterIP, err)\n\t}\n\treturn nil\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 (r *Rkt) StopContainers(ids []string) error {\n\treturn stopCRIContainers(r.Runner, ids)\n}", "func GenerateContainers(vmi *v1.VirtualMachineInstance, podVolumeName string, podVolumeMountDir string) []kubev1.Container {\n\tvar containers []kubev1.Container\n\n\tinitialDelaySeconds := 2\n\ttimeoutSeconds := 5\n\tperiodSeconds := 5\n\tsuccessThreshold := 2\n\tfailureThreshold := 5\n\n\t// Make VirtualMachineInstance Image Wrapper Containers\n\tfor _, volume := range vmi.Spec.Volumes {\n\t\tif volume.ContainerDisk != nil {\n\n\t\t\tvolumeMountDir := generateVolumeMountDir(vmi, volume.Name)\n\t\t\tdiskContainerName := fmt.Sprintf(\"volume%s\", volume.Name)\n\t\t\tdiskContainerImage := volume.ContainerDisk.Image\n\t\t\tresources := kubev1.ResourceRequirements{}\n\t\t\tif vmi.IsCPUDedicated() {\n\t\t\t\tresources.Limits = make(kubev1.ResourceList)\n\t\t\t\t// TODO(vladikr): adjust the correct cpu/mem values - this is mainly needed to allow QemuImg to run correctly\n\t\t\t\tresources.Limits[kubev1.ResourceCPU] = resource.MustParse(\"200m\")\n\t\t\t\t// k8s minimum memory reservation is linuxMinMemory = 4194304\n\t\t\t\tresources.Limits[kubev1.ResourceMemory] = resource.MustParse(\"64M\")\n\t\t\t}\n\t\t\tcontainers = append(containers, kubev1.Container{\n\t\t\t\tName: diskContainerName,\n\t\t\t\tImage: diskContainerImage,\n\t\t\t\tImagePullPolicy: kubev1.PullIfNotPresent,\n\t\t\t\tCommand: []string{\"/entry-point.sh\"},\n\t\t\t\tEnv: []kubev1.EnvVar{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"COPY_PATH\",\n\t\t\t\t\t\tValue: volumeMountDir + \"/\" + filePrefix,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"IMAGE_PATH\",\n\t\t\t\t\t\tValue: volume.ContainerDisk.Path,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tVolumeMounts: []kubev1.VolumeMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: podVolumeName,\n\t\t\t\t\t\tMountPath: podVolumeMountDir,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResources: resources,\n\n\t\t\t\t// The readiness probes ensure the volume coversion and copy finished\n\t\t\t\t// before the container is marked as \"Ready: True\"\n\t\t\t\tReadinessProbe: &kubev1.Probe{\n\t\t\t\t\tHandler: kubev1.Handler{\n\t\t\t\t\t\tExec: &kubev1.ExecAction{\n\t\t\t\t\t\t\tCommand: []string{\n\t\t\t\t\t\t\t\t\"cat\",\n\t\t\t\t\t\t\t\t\"/tmp/healthy\",\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\tInitialDelaySeconds: int32(initialDelaySeconds),\n\t\t\t\t\tPeriodSeconds: int32(periodSeconds),\n\t\t\t\t\tTimeoutSeconds: int32(timeoutSeconds),\n\t\t\t\t\tSuccessThreshold: int32(successThreshold),\n\t\t\t\t\tFailureThreshold: int32(failureThreshold),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn containers\n}", "func CleanupDockerContainersList() ([]dockerclient.APIContainers, error) {\n\tclient := DockerClient()\n\tlistOpts := dockerclient.ListContainersOptions{\n\t\tFilters: map[string][]string{\n\t\t\t\"status\": []string{\"exited\"},\n\t\t},\n\t}\n\n\treturn client.ListContainers(listOpts)\n}", "func (kr *KindRuntime) Destroy(ctx context.Context) error {\n\tkind, err := kr.ensureKind(kr.log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := exec.CommandContext(ctx, kind, \"delete\", \"cluster\", \"--name\", KindClusterName).CombinedOutput()\n\treturn errors.Wrapf(err, \"failed to run kind: %s\", b)\n}", "func (r *ReconcileAerospikeCluster) cleanupPods(aeroCluster *aerospikev1alpha1.AerospikeCluster, podNames []string, rackState RackState) error {\n\tlogger := pkglog.New(log.Ctx{\"AerospikeCluster\": utils.ClusterNamespacedName(aeroCluster)})\n\n\tlogger.Info(\"Removing pvc for removed pods\", log.Ctx{\"pods\": podNames})\n\n\t// Delete PVCs if cascadeDelete\n\tpvcItems, err := r.getPodsPVCList(aeroCluster, podNames, rackState.Rack.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find pvc for pods %v: %v\", podNames, err)\n\t}\n\tstorage := rackState.Rack.Storage\n\tif err := r.removePVCs(aeroCluster, &storage, pvcItems); err != nil {\n\t\treturn fmt.Errorf(\"Could not cleanup pod PVCs: %v\", err)\n\t}\n\n\tneedStatusCleanup := []string{}\n\n\tclusterPodList, err := r.getClusterPodList(aeroCluster)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not cleanup pod PVCs: %v\", err)\n\t}\n\n\tfor _, podName := range podNames {\n\t\t// Clear references to this pod in the running cluster.\n\t\tfor _, np := range clusterPodList.Items {\n\t\t\t// TODO: We remove node from the end. Nodes will not have seed of successive nodes\n\t\t\t// So this will be no op.\n\t\t\t// We should tip in all nodes the same seed list,\n\t\t\t// then only this will have any impact. Is it really necessary?\n\n\t\t\t// TODO: tip after scaleup and create\n\t\t\t// All nodes from other rack\n\t\t\tr.tipClearHostname(aeroCluster, &np, podName)\n\n\t\t\tr.alumniReset(aeroCluster, &np)\n\t\t}\n\n\t\tif aeroCluster.Spec.MultiPodPerHost {\n\t\t\t// Remove service for pod\n\t\t\t// TODO: make it more roboust, what if it fails\n\t\t\tif err := r.deleteServiceForPod(podName, aeroCluster.Namespace); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t_, ok := aeroCluster.Status.Pods[podName]\n\t\tif ok {\n\t\t\tneedStatusCleanup = append(needStatusCleanup, podName)\n\t\t}\n\t}\n\n\tif len(needStatusCleanup) > 0 {\n\t\tlogger.Info(\"Removing pod status for dangling pods\", log.Ctx{\"pods\": podNames})\n\n\t\tif err := r.removePodStatus(aeroCluster, needStatusCleanup); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not cleanup pod status: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *masterService) allocateContainers() {\n\tdefMap := m.db.ListDefinitions()\n\tcontMap := m.db.ListContainers()\n\tnodeMap := m.db.ListNodes()\n\n\t//\n\t// definition -> container map\n\t//\n\tdefContMapList := make(map[string][]*model.Container)\n\tfor _, cont := range contMap {\n\t\tconts := defContMapList[cont.DefinitionName]\n\t\tconts = append(conts, cont)\n\t\tdefContMapList[cont.DefinitionName] = conts\n\t}\n\n\t//\n\t// node -> container map\n\t//\n\tnodeContMap := make(map[string][]*model.Container)\n\tfor nodeName := range nodeMap {\n\t\tconts := make([]*model.Container, 0)\n\t\tfor _, cont := range contMap {\n\t\t\tif cont.NodeName == nodeName {\n\t\t\t\tconts = append(conts, cont)\n\t\t\t}\n\t\t}\n\t\tnodeContMap[nodeName] = conts\n\t}\n\n\t//\n\t// todo\n\t//\n\tfor k, def := range defMap {\n\t\tconts := defContMapList[k]\n\t\tn := len(conts)\n\t\tif def.Count < n {\n\t\t\t// deallocate some containers for definition\n\t\t\tdiff := n - def.Count\n\t\t\tlog.Info(\"Adjusting container count (%d delta)\", diff)\n\t\t\tfor i := 0; i < diff; i++ {\n\t\t\t\tidx := rand.Intn(len(conts))\n\t\t\t\tcont := conts[idx]\n\t\t\t\tconts = append(conts[:idx], conts[idx+1:]...)\n\t\t\t\tlog.Info(\"Deleting container id %s/%s\", cont.ContainerID, cont.Name)\n\t\t\t\tm.db.DeleteContainer(cont.ContainerID)\n\t\t\t}\n\t\t} else if def.Count > n {\n\t\t\t// allocate more containers for definition\n\t\t\tdiff := def.Count - n\n\t\t\tlog.Info(\"Adjusting container count (%d delta)\", diff)\n\t\t\tfor i := 0; i < diff; i++ {\n\t\t\t\tc := &model.Container{}\n\t\t\t\tc.Name = fmt.Sprintf(\"%s-%d\", def.Name, m.db.NextAutoIncrement(\"inc.container\", def.Name))\n\t\t\t\tc.DefinitionName = def.Name\n\n\t\t\t\t//\n\t\t\t\t// find node with least numbers of containers\n\t\t\t\t//\n\t\t\t\tcurrentN := 999999999\n\t\t\t\tvar currentNodeName string\n\t\t\t\tlog.Debug(\"nodeContMap: %s\", nodeContMap)\n\t\t\t\tfor nodeName, contSlice := range nodeContMap {\n\t\t\t\t\tn := len(contSlice)\n\t\t\t\t\tlog.Debug(\"checking node for number of containers (%d) less than %d\", n, currentN)\n\t\t\t\t\tif currentN > n {\n\t\t\t\t\t\tcurrentNodeName = nodeName\n\t\t\t\t\t\tcurrentN = n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tif currentNodeName == \"\" {\n\t\t\t\t\tlog.Warn(\"Not able to create node %s...no nodes available!\", c.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc.NodeName = currentNodeName\n\n\t\t\t\t//\n\t\t\t\tc.Image = def.Image\n\t\t\t\tc.Running = false\n\t\t\t\tc.HTTPPort = def.HTTPPort\n\t\t\t\t// generate a mapping nodeHttpPort -> httpPort\n\t\t\t\tif c.HTTPPort > 0 {\n\t\t\t\t\tc.NodeHTTPPort = minHTTPPort + m.db.NextAutoIncrement(\"http.port\", \"http.port\")\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Creating container id %s/%s\", c.ContainerID, c.Name)\n\t\t\t\tif err := m.db.SaveContainer(c); err != nil {\n\t\t\t\t\tlog.Error(\"Error saving container %s\", c.Name)\n\t\t\t\t} else {\n\t\t\t\t\tnodeContMap[c.NodeName] = append(nodeContMap[c.NodeName], c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (bc *BaseCluster) Destroy() {\n\tfor _, m := range bc.Machines() {\n\t\tbc.numMachines--\n\t\tm.Destroy()\n\t}\n}", "func GenerateContainers(vm *v1.VM) ([]kubev1.Container, error) {\n\tvar containers []kubev1.Container\n\n\tinitialDelaySeconds := 5\n\ttimeoutSeconds := 5\n\tperiodSeconds := 10\n\tsuccessThreshold := 2\n\tfailureThreshold := 5\n\n\t// Make VM Image Wrapper Containers\n\tdiskCount := 0\n\tfor _, disk := range vm.Spec.Domain.Devices.Disks {\n\t\tif disk.Type == registryDiskV1Alpha {\n\t\t\tdiskContainerName := fmt.Sprintf(\"disk%d\", diskCount)\n\t\t\t// container image is disk.Source.Name\n\t\t\tdiskContainerImage := disk.Source.Name\n\t\t\t// disk.Source.Host.Port has the port field expanded before templating.\n\t\t\tport := disk.Source.Host.Port\n\t\t\tportInt, err := strconv.Atoi(port)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontainers = append(containers, kubev1.Container{\n\t\t\t\tName: diskContainerName,\n\t\t\t\tImage: diskContainerImage,\n\t\t\t\tImagePullPolicy: kubev1.PullIfNotPresent,\n\t\t\t\tCommand: []string{\"/entry-point.sh\", port},\n\t\t\t\tPorts: []kubev1.ContainerPort{\n\t\t\t\t\tkubev1.ContainerPort{\n\t\t\t\t\t\tContainerPort: int32(portInt),\n\t\t\t\t\t\tProtocol: kubev1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tEnv: []kubev1.EnvVar{\n\t\t\t\t\tkubev1.EnvVar{\n\t\t\t\t\t\tName: \"PORT\",\n\t\t\t\t\t\tValue: port,\n\t\t\t\t\t},\n\t\t\t\t\t// TODO once dynamic auth is implemented, pass creds as\n\t\t\t\t\t// PASSWORD and USERNAME env vars. The registry disk base\n\t\t\t\t\t// container already knows how to enable authentication\n\t\t\t\t\t// when those env vars are present.\n\t\t\t\t},\n\t\t\t\t// The readiness probes ensure the ISCSI targets are available\n\t\t\t\t// before the container is marked as \"Ready: True\"\n\t\t\t\tReadinessProbe: &kubev1.Probe{\n\t\t\t\t\tHandler: kubev1.Handler{\n\t\t\t\t\t\tExec: &kubev1.ExecAction{\n\t\t\t\t\t\t\tCommand: []string{\n\t\t\t\t\t\t\t\t\"cat\",\n\t\t\t\t\t\t\t\t\"/tmp/healthy\",\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\tInitialDelaySeconds: int32(initialDelaySeconds),\n\t\t\t\t\tPeriodSeconds: int32(periodSeconds),\n\t\t\t\t\tTimeoutSeconds: int32(timeoutSeconds),\n\t\t\t\t\tSuccessThreshold: int32(successThreshold),\n\t\t\t\t\tFailureThreshold: int32(failureThreshold),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn containers, 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 (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 DelContainerForce(c *check.C, cname string) (*http.Response, error) {\n\tq := url.Values{}\n\tq.Add(\"force\", \"true\")\n\tq.Add(\"v\", \"true\")\n\treturn request.Delete(\"/containers/\"+cname, request.WithQuery(q))\n}", "func testAccContainerAttachedCluster_containerAttachedCluster_destroy(context map[string]interface{}) string {\n\treturn acctest.Nprintf(`\ndata \"google_project\" \"project\" {\n}\n\ndata \"google_container_attached_versions\" \"versions\" {\n\tlocation = \"us-west1\"\n\tproject = data.google_project.project.project_id\n}\n\nresource \"google_container_attached_cluster\" \"primary\" {\n name = \"update%{random_suffix}\"\n project = data.google_project.project.project_id\n location = \"us-west1\"\n description = \"Test cluster updated\"\n distribution = \"aks\"\n annotations = {\n label-one = \"value-one\"\n label-two = \"value-two\"\n }\n authorization {\n admin_users = [ \"[email protected]\", \"[email protected]\"]\n }\n oidc_config {\n issuer_url = \"https://oidc.issuer.url\"\n jwks = base64encode(\"{\\\"keys\\\":[{\\\"use\\\":\\\"sig\\\",\\\"kty\\\":\\\"RSA\\\",\\\"kid\\\":\\\"testid\\\",\\\"alg\\\":\\\"RS256\\\",\\\"n\\\":\\\"somedata\\\",\\\"e\\\":\\\"AQAB\\\"}]}\")\n }\n platform_version = data.google_container_attached_versions.versions.valid_versions[0]\n fleet {\n project = \"projects/${data.google_project.project.number}\"\n }\n monitoring_config {\n managed_prometheus_config {}\n }\n}\n`, context)\n}", "func TestDanglingContainerRemoval(t *testing.T) {\n\tci.Parallel(t)\n\ttestutil.DockerCompatible(t)\n\n\t// start two containers: one tracked nomad container, and one unrelated container\n\ttask, cfg, ports := dockerTask(t)\n\tdefer freeport.Return(ports)\n\trequire.NoError(t, task.EncodeConcreteDriverConfig(cfg))\n\n\tclient, d, handle, cleanup := dockerSetup(t, task, nil)\n\tdefer cleanup()\n\trequire.NoError(t, d.WaitUntilStarted(task.ID, 5*time.Second))\n\n\tnonNomadContainer, err := client.CreateContainer(docker.CreateContainerOptions{\n\t\tName: \"mytest-image-\" + uuid.Generate(),\n\t\tConfig: &docker.Config{\n\t\t\tImage: cfg.Image,\n\t\t\tCmd: append([]string{cfg.Command}, cfg.Args...),\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\tdefer client.RemoveContainer(docker.RemoveContainerOptions{\n\t\tID: nonNomadContainer.ID,\n\t\tForce: true,\n\t})\n\n\terr = client.StartContainer(nonNomadContainer.ID, nil)\n\trequire.NoError(t, err)\n\n\tuntrackedNomadContainer, err := client.CreateContainer(docker.CreateContainerOptions{\n\t\tName: \"mytest-image-\" + uuid.Generate(),\n\t\tConfig: &docker.Config{\n\t\t\tImage: cfg.Image,\n\t\t\tCmd: append([]string{cfg.Command}, cfg.Args...),\n\t\t\tLabels: map[string]string{\n\t\t\t\tdockerLabelAllocID: uuid.Generate(),\n\t\t\t},\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\tdefer client.RemoveContainer(docker.RemoveContainerOptions{\n\t\tID: untrackedNomadContainer.ID,\n\t\tForce: true,\n\t})\n\n\terr = client.StartContainer(untrackedNomadContainer.ID, nil)\n\trequire.NoError(t, err)\n\n\tdd := d.Impl().(*Driver)\n\n\treconciler := newReconciler(dd)\n\ttrackedContainers := map[string]bool{handle.containerID: true}\n\n\ttf := reconciler.trackedContainers()\n\trequire.Contains(t, tf, handle.containerID)\n\trequire.NotContains(t, tf, untrackedNomadContainer)\n\trequire.NotContains(t, tf, nonNomadContainer.ID)\n\n\t// assert tracked containers should never be untracked\n\tuntracked, err := reconciler.untrackedContainers(trackedContainers, time.Now())\n\trequire.NoError(t, err)\n\trequire.NotContains(t, untracked, handle.containerID)\n\trequire.NotContains(t, untracked, nonNomadContainer.ID)\n\trequire.Contains(t, untracked, untrackedNomadContainer.ID)\n\n\t// assert we recognize nomad containers with appropriate cutoff\n\tuntracked, err = reconciler.untrackedContainers(map[string]bool{}, time.Now())\n\trequire.NoError(t, err)\n\trequire.Contains(t, untracked, handle.containerID)\n\trequire.Contains(t, untracked, untrackedNomadContainer.ID)\n\trequire.NotContains(t, untracked, nonNomadContainer.ID)\n\n\t// but ignore if creation happened before cutoff\n\tuntracked, err = reconciler.untrackedContainers(map[string]bool{}, time.Now().Add(-1*time.Minute))\n\trequire.NoError(t, err)\n\trequire.NotContains(t, untracked, handle.containerID)\n\trequire.NotContains(t, untracked, untrackedNomadContainer.ID)\n\trequire.NotContains(t, untracked, nonNomadContainer.ID)\n\n\t// a full integration tests to assert that containers are removed\n\tprestineDriver := dockerDriverHarness(t, nil).Impl().(*Driver)\n\tprestineDriver.config.GC.DanglingContainers = ContainerGCConfig{\n\t\tEnabled: true,\n\t\tperiod: 1 * time.Second,\n\t\tCreationGrace: 0 * time.Second,\n\t}\n\tnReconciler := newReconciler(prestineDriver)\n\n\trequire.NoError(t, nReconciler.removeDanglingContainersIteration())\n\n\t_, err = client.InspectContainer(nonNomadContainer.ID)\n\trequire.NoError(t, err)\n\n\t_, err = client.InspectContainer(handle.containerID)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), NoSuchContainerError)\n\n\t_, err = client.InspectContainer(untrackedNomadContainer.ID)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), NoSuchContainerError)\n}", "func (d *DockerDriver) Clear() {\n\tlog.Println(\"Clearing containers containers\")\n\tcli := d.getClient()\n\n\ttimeout := time.Second * 30\n\n\t// Stop all containers\n\tcontainers, err := cli.ContainerList(context.TODO(), types.ContainerListOptions{})\n\tif err != nil {\n\t\tpanic(shadowerrors.ShadowError{\n\t\t\tOrigin: err,\n\t\t\tVisibleMessage: \"clear containers containers error\",\n\t\t})\n\t}\n\tfor _, container := range containers {\n\t\terr = cli.ContainerStop(context.TODO(), container.ID, &timeout)\n\t\tif err != nil {\n\t\t\tpanic(shadowerrors.ShadowError{\n\t\t\t\tOrigin: err,\n\t\t\t\tVisibleMessage: \"clear containers containers error\",\n\t\t\t})\n\t\t}\n\t}\n\n\t// Remove all containers\n\tcontainers, err = cli.ContainerList(context.TODO(), types.ContainerListOptions{})\n\tif err != nil {\n\t\tpanic(shadowerrors.ShadowError{\n\t\t\tOrigin: err,\n\t\t\tVisibleMessage: \"clear containers containers error\",\n\t\t})\n\t}\n\tfor _, container := range containers {\n\t\terr = cli.ContainerRemove(context.TODO(), container.ID, types.ContainerRemoveOptions{})\n\t\tif err != nil {\n\t\t\tpanic(shadowerrors.ShadowError{\n\t\t\t\tOrigin: err,\n\t\t\t\tVisibleMessage: \"clear containers containers error\",\n\t\t\t})\n\t\t}\n\t}\n}", "func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error {\n\tarmClient := meta.(*ArmClient)\n\tctx := armClient.StopContext\n\n\tresourceGroupName := d.Get(\"resource_group_name\").(string)\n\tstorageAccountName := d.Get(\"storage_account_name\").(string)\n\n\tblobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(ctx, resourceGroupName, storageAccountName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !accountExists {\n\t\tlog.Printf(\"[INFO]Storage Account %q doesn't exist so the container won't exist\", storageAccountName)\n\t\treturn nil\n\t}\n\n\tname := d.Get(\"name\").(string)\n\n\tlog.Printf(\"[INFO] Deleting storage container %q in account %q\", name, storageAccountName)\n\treference := blobClient.GetContainerReference(name)\n\tdeleteOptions := &storage.DeleteContainerOptions{}\n\tif _, err := reference.DeleteIfExists(deleteOptions); err != nil {\n\t\treturn fmt.Errorf(\"Error deleting storage container %q from storage account %q: %s\", name, storageAccountName, err)\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}", "func (e *dockerEngine) clean() {\n\tsss := map[string]map[string]attribute{}\n\tif e.LoadStats(&sss) {\n\t\tfor sn, instances := range sss {\n\t\t\tfor in, instance := range instances {\n\t\t\t\tid := instance.Container.ID\n\t\t\t\tif id == \"\" {\n\t\t\t\t\te.log.Warnf(\"[%s][%s] container id not found, maybe running mode changed\", sn, in)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terr := e.stopContainer(id)\n\t\t\t\tif err != nil {\n\t\t\t\t\te.log.Warnf(\"[%s][%s] failed to stop the old container (%s)\", sn, in, id[:12])\n\t\t\t\t} else {\n\t\t\t\t\te.log.Infof(\"[%s][%s] old container (%s) stopped\", sn, in, id[:12])\n\t\t\t\t}\n\t\t\t\terr = e.removeContainer(id)\n\t\t\t\tif err != nil {\n\t\t\t\t\te.log.Warnf(\"[%s][%s] failed to remove the old container (%s)\", sn, in, id[:12])\n\t\t\t\t} else {\n\t\t\t\t\te.log.Infof(\"[%s][%s] old container (%s) removed\", sn, in, id[:12])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func zombiecheck() error {\n\tlog.Println(\"Running zombiecheck\")\n\tctx := context.Background()\n\n\tdockercli, err := dockerclient.NewEnvClient()\n\tif err != nil {\n\t\tlog.Println(\"Unable to create docker client\")\n\t\treturn err\n\t}\n\n\tcontainers, err := dockercli.ContainerList(ctx, types.ContainerListOptions{\n\t\tAll: true,\n\t})\n\n\tstopContainers := []string{}\n\tremoveContainers := []string{}\n\tfor _, container := range containers {\n\t\tfor _, name := range container.Names {\n\t\t\t// FIXME - add name_version_uid_uid regex check as well\n\t\t\tif !strings.HasPrefix(name, \"/worker\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif container.State != \"running\" {\n\t\t\t\tremoveContainers = append(removeContainers, container.ID)\n\t\t\t}\n\n\t\t\t// stopcontainer & removecontainer\n\t\t\tcurrenttime := time.Now().Unix()\n\t\t\tif container.State == \"running\" && currenttime-container.Created > int64(workerTimeout) {\n\t\t\t\tstopContainers = append(stopContainers, container.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// FIXME - add killing of apps with same execution ID too\n\tfor _, containername := range stopContainers {\n\t\tif err := dockercli.ContainerStop(ctx, containername, nil); err != nil {\n\t\t\tlog.Printf(\"Unable to stop container: %s\", err)\n\t\t} else {\n\t\t\tlog.Printf(\"Stopped container %s\", containername)\n\t\t}\n\t}\n\n\tremoveOptions := types.ContainerRemoveOptions{\n\t\tRemoveVolumes: true,\n\t\tForce: true,\n\t}\n\n\tfor _, containername := range removeContainers {\n\t\tif err := dockercli.ContainerRemove(ctx, containername, removeOptions); err != nil {\n\t\t\tlog.Printf(\"Unable to remove container: %s\", err)\n\t\t} else {\n\t\t\tlog.Printf(\"Removed container %s\", containername)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *DestroyCommand) Run(arguments []string) int {\n\n\tvar (\n\t\tcontainersIdsToBeDestroyed []string\n\t\tcontainersNamesToBeDestroyed []string\n\t)\n\n\tlogger.Debug(\"Entered destroy command...\")\n\n\tcmdFlags := flag.NewFlagSet(\"destroy\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { c.Ui.Output(c.Help()) }\n\n\tdockerKillCommand := []string{constants.DOCKER, constants.KILL}\n\tdockerRemoveCommand := []string{constants.DOCKER, constants.REMOVE}\n\tkillThemAll := true //Kill all containers\n\n\tif len(arguments) > 0 { //kill only specified containers\n\t\tkillThemAll = false\n\t\tlogger.Debug(\"Only user provided containers will be destroyed:\\n%v\", arguments)\n\t}\n\n\tstateContainers := c.Config.CraneState.StateContainers\n\n\tif len(stateContainers) == 0 {\n\t\tlogger.Fatalf(\"There are no containers in the state file hence no containers will be destroyed.You can destroy only containers that were created by the crane.\")\n\t}\n\n\t//append containers ids to the docker kill command\n\tfor containerName, stateContainer := range stateContainers {\n\t\tif killThemAll { //Kill all\n\t\t\tcontainersIdsToBeDestroyed, containersNamesToBeDestroyed = addToBeDestroyedList(containerName, stateContainer.ID, containersIdsToBeDestroyed, containersNamesToBeDestroyed)\n\t\t} else { //Kill specific containers only\n\t\t\tfor _, containerToBeDeleted := range arguments {\n\t\t\t\tif containerToBeDeleted == containerName {\n\t\t\t\t\tcontainersIdsToBeDestroyed, containersNamesToBeDestroyed = addToBeDestroyedList(containerName, stateContainer.ID, containersIdsToBeDestroyed, containersNamesToBeDestroyed)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdockerKillCommand = append(dockerKillCommand, containersIdsToBeDestroyed...)\n\tdockerRemoveCommand = append(dockerRemoveCommand, containersIdsToBeDestroyed...)\n\n\tif len(containersIdsToBeDestroyed) == 0 {\n\t\tlogger.Fatal(\"No such containers were found in the state file hence they cannott be deleted.Please note that you can destroy only containers created by the crane.\")\n\t}\n\n\tlogger.Debug(\"Following containers will be destroyed:\\n%v\", containersNamesToBeDestroyed)\n\n\t//First Kill, then Remove\n\tkillContainers(dockerKillCommand)\n\tremoveContainers(dockerRemoveCommand)\n\n\t//Remove destroyed containers from the state file.\n\tio.RemoveStateContainers(containersNamesToBeDestroyed)\n\n\treturn 0\n}", "func (owned OwnedContainers)CleanLeftOverContainers(dockerClient *client.Client) {\n\n\tcontainers, err := getContainers(dockerClient)\n\tif err == nil {\n\t\tfor _, container := range containers {\n\t\t\tif _, ok := owned[container.ID]; ok {\n\t\t\t\terr = dockerClient.ContainerStop(context.Background(), container.ID, nil)\n\t\t\t}\n\t\t}\n\t}\n}", "func main() {\n\tapp := cdk8s.NewApp(&cdk8s.AppProps{\n\t\tOutdir: jsii.String(\"templates\"),\n\t\tYamlOutputType: cdk8s.YamlOutputType_FILE_PER_RESOURCE,\n\t})\n\n\tchart := cdk8s.NewChart(app, jsii.String(\"cdk8s-demo\"), &cdk8s.ChartProps{\n\t\tLabels: &map[string]*string{\n\t\t\t\"app\": jsii.String(\"cdk8s-demo\"),\n\t\t},\n\t})\n\n\t//deploy :=\n\tdeploy := cdk8splus20.NewDeployment(chart, jsii.String(\"deploy\"), &cdk8splus20.DeploymentProps{\n\t\tReplicas: jsii.Number(3),\n\t\t//\tDefaultSelector: jsii.Bool(false),\n\t\tContainers: &[]*cdk8splus20.ContainerProps{{\n\t\t\tImage: jsii.String(\"ubuntu\"),\n\t\t\tName: jsii.String(\"ubuntu\"),\n\t\t\tLiveness: cdk8splus20.Probe_FromHttpGet(jsii.String(\"/health\"),\n\t\t\t\t&cdk8splus20.HttpGetProbeOptions{\n\t\t\t\t\tInitialDelaySeconds: cdk8s.Duration_Seconds(jsii.Number(30)),\n\t\t\t\t},\n\t\t\t),\n\t\t\tPort: jsii.Number(8080),\n\t\t\tEnv: &map[string]cdk8splus20.EnvValue{\n\t\t\t\t\"env1\": cdk8splus20.EnvValue_FromValue(jsii.String(\"valone\")),\n\t\t\t\t\"env2\": cdk8splus20.EnvValue_FromValue(jsii.String(\"valtwo\")),\n\t\t\t},\n\t\t}},\n\t})\n\n\t//deploy.SelectByLabel(jsii.String(\"klaas\"), jsii.String(\"jan\"))\n\t//deploy.SelectByLabel(jsii.String(\"piet\"), jsii.String(\"karel\"))\n\n\tsvc := deploy.Expose(jsii.Number(883), &cdk8splus20.ExposeOptions{})\n\n\ting := cdk8splus20.NewIngressV1Beta1(chart, jsii.String(\"ing\"), &cdk8splus20.IngressV1Beta1Props{})\n\ting.AddHostDefaultBackend(\n\t\tjsii.String(\"host\"),\n\t\tcdk8splus20.IngressV1Beta1Backend_FromService(\n\t\t\tsvc,\n\t\t\t&cdk8splus20.ServiceIngressV1BetaBackendOptions{},\n\t\t))\n\n\tnetworkingistioio.NewVirtualService(chart, jsii.String(\"vs\"), &networkingistioio.VirtualServiceProps{\n\t\tMetadata: &cdk8s.ApiObjectMetadata{\n\t\t\tName: jsii.String(\"test-vs\"),\n\t\t},\n\t\tSpec: &networkingistioio.VirtualServiceSpec{\n\t\t\tGateways: jsii.Strings(\"test-gateway\"),\n\t\t\tHosts: jsii.Strings(\"bla.com\", \"boe.com\"),\n\t\t\tHttp: &[]*networkingistioio.VirtualServiceSpecHttp{\n\t\t\t\t{\n\t\t\t\t\tMatch: &[]*networkingistioio.VirtualServiceSpecHttpMatch{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUri: &networkingistioio.VirtualServiceSpecHttpMatchUri{\n\t\t\t\t\t\t\t\tPrefix: jsii.String(\"/test\"),\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\tRoute: &[]*networkingistioio.VirtualServiceSpecHttpRoute{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDestination: &networkingistioio.VirtualServiceSpecHttpRouteDestination{\n\t\t\t\t\t\t\t\tHost: svc.Name(),\n\t\t\t\t\t\t\t\tPort: &networkingistioio.VirtualServiceSpecHttpRouteDestinationPort{\n\t\t\t\t\t\t\t\t\t(*svc.Ports())[0].Port,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\n\tapp.Synth()\n}", "func (k *KubeletExecutor) Kill(containerIDs []string) error {\n\tfor _, containerID := range containerIDs {\n\t\terr := k.cli.KillGracefully(containerID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func removeContainers(ctx context.Context, cli *client.Client, containerIDs []string) error {\n\tfor _, cid := range containerIDs {\n\t\terr := cli.ContainerRemove(ctx, cid, types.ContainerRemoveOptions{Force: true})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Containers) Close() error {\n\t// if we are on cgroupv1 and previously executed cpuset mounting logic (see function initCgroupV1)\n\tif c.IsCgroupV1() && strings.HasPrefix(c.cgroupMP, \"/tmp\") {\n\t\t// first unmount the temporary cpuset mount\n\t\terr := syscall.Unmount(c.cgroupMP, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// then remove the dir\n\t\terr = os.RemoveAll(c.cgroupMP)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func toK8SContainerSpec(c *pbpod.ContainerSpec) corev1.Container {\n\t// TODO:\n\t// add ports, health check, readiness check, affinity\n\tvar kEnvs []corev1.EnvVar\n\tfor _, e := range c.GetEnvironment() {\n\t\tkEnvs = append(kEnvs, corev1.EnvVar{\n\t\t\tName: e.GetName(),\n\t\t\tValue: e.GetValue(),\n\t\t})\n\t}\n\n\tvar ports []corev1.ContainerPort\n\tfor _, p := range c.GetPorts() {\n\t\tports = append(ports, corev1.ContainerPort{\n\t\t\tName: p.GetName(),\n\t\t\tContainerPort: int32(p.GetValue()),\n\t\t})\n\t}\n\n\tcname := c.GetName()\n\tif cname == \"\" {\n\t\tcname = uuid.New()\n\t}\n\n\tcimage := c.GetImage()\n\tif cimage == \"\" {\n\t\tcimage = _defaultImageName\n\t}\n\n\tmemMb := c.GetResource().GetMemLimitMb()\n\tif memMb < _defaultMinMemMb {\n\t\tmemMb = _defaultMinMemMb\n\t}\n\n\tk8sSpec := corev1.Container{\n\t\tName: cname,\n\t\tImage: cimage,\n\t\tEnv: kEnvs,\n\t\tPorts: ports,\n\t\tResources: corev1.ResourceRequirements{\n\t\t\tLimits: corev1.ResourceList{\n\t\t\t\tcorev1.ResourceCPU: *resource.NewMilliQuantity(\n\t\t\t\t\tint64(c.GetResource().GetCpuLimit()*1000),\n\t\t\t\t\tresource.DecimalSI,\n\t\t\t\t),\n\t\t\t\tcorev1.ResourceMemory: *resource.NewMilliQuantity(\n\t\t\t\t\tint64(memMb*1000000000),\n\t\t\t\t\tresource.DecimalSI,\n\t\t\t\t),\n\t\t\t},\n\t\t\tRequests: corev1.ResourceList{\n\t\t\t\tcorev1.ResourceCPU: *resource.NewMilliQuantity(\n\t\t\t\t\tint64(c.GetResource().GetCpuLimit()*1000),\n\t\t\t\t\tresource.DecimalSI,\n\t\t\t\t),\n\t\t\t\tcorev1.ResourceMemory: *resource.NewMilliQuantity(\n\t\t\t\t\tint64(memMb*1000000000),\n\t\t\t\t\tresource.DecimalSI,\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t}\n\n\tif c.GetEntrypoint().GetValue() != \"\" {\n\t\tk8sSpec.Command = []string{c.GetEntrypoint().GetValue()}\n\t\tk8sSpec.Args = c.GetEntrypoint().GetArguments()\n\t}\n\n\treturn k8sSpec\n}", "func (dc *DockerContainer) Kill() error {\n\tcid, err := dc.ContainerName()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn docker(nil, \"kill\", cid)\n}", "func (s *Service) Delete(ctx context.Context, options options.Delete) error {\n\treturn s.collectContainersAndDo(ctx, func(c *container.Container) error {\n\t\trunning := c.IsRunning(ctx)\n\t\tif !running || options.RemoveRunning {\n\t\t\treturn c.Remove(ctx, options.RemoveVolume)\n\t\t}\n\t\treturn nil\n\t})\n}", "func CartsDestroy(c *cli.Context) {\n\tconf := config.GetConfig()\n\tdefer conf.Flush()\n\n\tcartName := conf.CartNameFromCache(c.Args().First())\n\n\tif cart, exists := conf.Carts[cartName]; exists {\n\t\tdelete(conf.Carts, cartName)\n\n\t\tfmt.Printf(\"Deleted cart %s\\n\", cart.Name)\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"Cart %s is unknown\\n\", cartName)\n\t\tos.Exit(1)\n\t}\n}", "func (t Test) K8s() error {\n\tmg.Deps(Tool{}.Kind)\n\n\terr := sh.RunWithV(ENV, \"kind\", \"create\", \"cluster\", \"--name\", \"kind-test\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = sh.RunWithV(ENV, \"kind\", \"delete\", \"cluster\", \"--name\", \"kind-test\")\n\t}()\n\terr = sh.RunWithV(ENV, \"kubectl\", \"apply\", \"-f\", \"./integration/testdata/fixtures/k8s/test_nginx.yaml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sh.RunWithV(ENV, \"go\", \"test\", \"-v\", \"-tags=k8s_integration\", \"./integration/...\")\n}", "func removeContainers(removeCommand []string) {\n\n\tremovedContainersBytes, err := executer.GetCommandOutput(removeCommand)\n\tif err != nil {\n\t\tlogger.Fatal(\"Error when trying to destroy container(s):\", utils.ExtractContainerMessage(removedContainersBytes, err))\n\t}\n\n\tremovedContainers := strings.TrimSpace(string(removedContainersBytes))\n\tlogger.Notice(\"Remove command output:\\n%v\", removedContainers)\n}", "func (m *podMetrics) Destroy() {\n}", "func cephOSDPoolDestroy(clusterName string, poolName string, userName string) error {\n\t_, err := shared.RunCommand(\"ceph\",\n\t\t\"--name\", fmt.Sprintf(\"client.%s\", userName),\n\t\t\"--cluster\", clusterName,\n\t\t\"osd\",\n\t\t\"pool\",\n\t\t\"delete\",\n\t\tpoolName,\n\t\tpoolName,\n\t\t\"--yes-i-really-really-mean-it\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\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 RemoveContainerRunningContainer(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ContainerController, id string, force bool) 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// Setup request context\n\trw := httptest.NewRecorder()\n\tquery := url.Values{}\n\t{\n\t\tsliceVal := []string{fmt.Sprintf(\"%v\", force)}\n\t\tquery[\"force\"] = sliceVal\n\t}\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/api/v2/container/%v/remove\", id),\n\t\tRawQuery: query.Encode(),\n\t}\n\treq, err := http.NewRequest(\"GET\", 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\t{\n\t\tsliceVal := []string{fmt.Sprintf(\"%v\", force)}\n\t\tprms[\"force\"] = sliceVal\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ContainerTest\"), rw, req, prms)\n\tremoveCtx, _err := app.NewRemoveContainerContext(goaCtx, req, service)\n\tif _err != nil {\n\t\te, 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\n\t// Perform action\n\t_err = ctrl.Remove(removeCtx)\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 != 409 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 409\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\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 (d *DockerDriver) Kill(containerId string) {\n\tlog.Println(\"Stopping container \" + containerId)\n\tcli := d.getClient()\n\n\ttimeout := time.Duration(30 * time.Second)\n\terr := cli.ContainerStop(context.TODO(), containerId, &timeout)\n\n\tif err != nil {\n\t\tpanic(shadowerrors.ShadowError{\n\t\t\tOrigin: err,\n\t\t\tVisibleMessage: \"kill containers container error\",\n\t\t})\n\t}\n}", "func (h *podDeletionHandler) deletePods(ctx context.Context, k8s corev1typed.CoreV1Interface, tag string) {\n\tpods := h.pods.get(tag)\n\tif len(pods) == 0 {\n\t\tlog.Printf(\"[noop] no pods registered with image=%s\", tag)\n\t\treturn\n\t}\n\tfor _, p := range pods {\n\t\tlog.Printf(\"[deleting_pod] %s/%s\", p.namespace, p.name)\n\t\tif err := k8s.Pods(p.namespace).Delete(ctx, p.name, metav1.DeleteOptions{}); err != nil {\n\t\t\tlog.Println(errors.Wrap(err, \"failed to delete pod\"))\n\t\t}\n\t\tlog.Printf(\"[deleted_pod] %s/%s\", p.namespace, p.name)\n\n\t\t// TODO(ahmetb) see if there's a better way of doing this: here we\n\t\t// unregister the pod directly, because we know we just deleted it. it's\n\t\t// faster than deletion to actually go through and come back via WATCH.\n\t\th.pods.del(p, tag)\n\t}\n}", "func (o *ClusterUninstaller) destroyDNS(ctx context.Context) error {\n\tprivateZone, publicZones, err := o.listDNSZones(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif privateZone == nil {\n\t\to.Logger.Debugf(\"Private DNS zone not found\")\n\t\treturn nil\n\t}\n\n\tzoneRecordSets, err := o.listDNSZoneRecordSets(ctx, privateZone)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparentZones := getParentDNSZones(privateZone.domain, publicZones, o.Logger)\n\tfor _, parentZone := range parentZones {\n\t\tparentRecordSets, err := o.listDNSZoneRecordSets(ctx, parentZone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmatchingRecordSets := o.getMatchingRecordSets(parentRecordSets, zoneRecordSets)\n\t\tif len(matchingRecordSets) > 0 {\n\t\t\terr = o.deleteDNSZoneRecordSets(ctx, parentZone, matchingRecordSets)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\terr = o.deleteDNSZoneRecordSets(ctx, privateZone, zoneRecordSets)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = o.deleteDNSZone(ctx, privateZone.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TestServiceCreateWithMultipleContainers(t *testing.T) {\n\tif test.ServingFlags.DisableOptionalAPI {\n\t\tt.Skip(\"Multiple containers support is not required by Knative Serving API Specification\")\n\t}\n\tif !test.ServingFlags.EnableBetaFeatures {\n\t\tt.Skip()\n\t}\n\tt.Parallel()\n\tclients := test.Setup(t)\n\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.ServingContainer,\n\t\tSidecars: []string{\n\t\t\ttest.SidecarContainer,\n\t\t},\n\t}\n\n\t// Clean up on test failure or interrupt\n\ttest.EnsureTearDown(t, clients, &names)\n\tcontainers := []corev1.Container{{\n\t\tImage: pkgtest.ImagePath(names.Image),\n\t\tPorts: []corev1.ContainerPort{{\n\t\t\tContainerPort: 8881,\n\t\t}},\n\t}, {\n\t\tImage: pkgtest.ImagePath(names.Sidecars[0]),\n\t}}\n\n\t// Setup initial Service\n\tif _, err := v1test.CreateServiceReady(t, clients, &names, func(svc *v1.Service) {\n\t\tsvc.Spec.Template.Spec.Containers = containers\n\t}); err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service %v: %v\", names.Service, err)\n\t}\n\n\t// Validate State after Creation\n\tif err := validateControlPlane(t, clients, names, \"1\" /*1 is the expected generation value*/); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif err := validateDataPlane(t, clients, names, test.MultiContainerResponse); err != nil {\n\t\tt.Error(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 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 DestroyTerraformStack(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n terraform.Destroy(t, terraformOptions)\n\n kubectlOptions := test_structure.LoadKubectlOptions(t, terraformDir)\n err := os.Remove(kubectlOptions.ConfigPath)\n require.NoError(t, err)\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 (c Cleaner) CleanUp() error {\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to docker client! %v\", err)\n\t}\n\tdefer cli.Close()\n\n\tvar SpaceReclaimed uint64\n\tSpaceReclaimed = 0\n\n\tif c.stoppedContainers {\n\t\tpruneFilter := filters.NewArgs()\n\t\tpruneFilter.Add(\"status\", \"exited\")\n\t\treport, err := cli.ContainersPrune(context.Background(), pruneFilter)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tif len(report.ContainersDeleted) >= 1 {\n\t\t\tfmt.Printf(\"%sRemoving containers %s\\n\", lightBlueColor, noColor)\n\t\t}\n\t\tfor _, containerID := range report.ContainersDeleted {\n\t\t\tfmt.Printf(\"%v\\n\", containerID[:10])\n\t\t}\n\t\tSpaceReclaimed += report.SpaceReclaimed\n\t}\n\n\tif c.unUsedImages {\n\t\tpruneFilter := filters.NewArgs()\n\t\tpruneFilter.Add(\"dangling\", \"false\")\n\t\treport, err := cli.ImagesPrune(context.Background(), pruneFilter)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tif len(report.ImagesDeleted) >= 1 {\n\t\t\tfmt.Printf(\"%sRemoving un used images %s\\n\", lightBlueColor, noColor)\n\t\t}\n\t\tfor _, image := range report.ImagesDeleted {\n\t\t\tfmt.Printf(\"%+v\\n\", image)\n\t\t}\n\t\tSpaceReclaimed += report.SpaceReclaimed\n\t}\n\n\tif c.unUsedVolumes {\n\t\tpruneFilter := filters.NewArgs()\n\t\treport, err := cli.VolumesPrune(context.Background(), pruneFilter)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tif len(report.VolumesDeleted) >= 1 {\n\t\t\tfmt.Printf(\"%sRemoving un used volumes %s\\n\", lightBlueColor, noColor)\n\t\t}\n\n\t\tfor _, volume := range report.VolumesDeleted {\n\t\t\tfmt.Printf(\"%+v\\n\", volume[:10])\n\t\t}\n\t\tSpaceReclaimed += report.SpaceReclaimed\n\t}\n\tif SpaceReclaimed >= 1 {\n\t\tfmt.Printf(\"Total reclaimed space: %v\\n\", units.HumanSize(float64(SpaceReclaimed)))\n\t}\n\treturn nil\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 (owned OwnedContainers) StopAllLiveContainers(terminatorGroup *sync.WaitGroup, dockerClient *client.Client) {\n\n\tcontainers, err := getContainers(dockerClient)\n\tif err == nil {\n\n\t\tfor _, container := range containers {\n\t\t\tif owned[container.ID] > 0 {\n\n\t\t\t\tcontID := container.ID\n\n\t\t\t\tterminatorGroup.Add(1)\n\n\t\t\t\tgo func() {\n\t\t\t\t\terr = dockerClient.ContainerStop(context.Background(), contID, nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"Stopping container failed: %v\\n\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"Stopped container with ID: %s\\n\", contID)\n\t\t\t\t\t}\n\t\t\t\t\tdefer terminatorGroup.Done()\n\t\t\t\t}()\n\t\t\t}\n\t\t}\n\t}\n}", "func (k *K8sutil) DeleteServices(clusterName, namespace string) error {\n\n\tfullDiscoveryServiceName := fmt.Sprintf(\"%s-%s\", discoveryServiceName, clusterName)\n\tif err := k.Kclient.CoreV1().Services(namespace).Delete(fullDiscoveryServiceName, &metav1.DeleteOptions{}); err != nil {\n\t\tlogrus.Error(\"Could not delete service \"+fullDiscoveryServiceName+\":\", err)\n\t}\n\tlogrus.Infof(\"Deleted service: %s\", fullDiscoveryServiceName)\n\n\tfullDataServiceName := dataServiceName + \"-\" + clusterName\n\tif err := k.Kclient.CoreV1().Services(namespace).Delete(fullDataServiceName, &metav1.DeleteOptions{}); err != nil {\n\t\tlogrus.Error(\"Could not delete service \"+fullDataServiceName+\":\", err)\n\t}\n\tlogrus.Infof(\"Deleted service: %s\", fullDataServiceName)\n\n\tfullClientServiceName := clientServiceName + \"-\" + clusterName\n\tif err := k.Kclient.CoreV1().Services(namespace).Delete(fullClientServiceName, &metav1.DeleteOptions{}); err != nil {\n\t\tlogrus.Error(\"Could not delete service \"+fullClientServiceName+\":\", err)\n\t}\n\tlogrus.Infof(\"Deleted service: %s\", fullClientServiceName)\n\n\tfor component, _ := range mgmtServices {\n\n\t\t// Check if service exists\n\t\ts, _ := k.Kclient.CoreV1().Services(namespace).Get(component, metav1.GetOptions{})\n\n\t\t// Service exists, delete\n\t\tif len(s.Name) >= 1 {\n\t\t\tfullClientServiceName := fmt.Sprintf(\"%s-%s\", component, clusterName)\n\n\t\t\tif err := k.Kclient.CoreV1().Services(namespace).Delete(fullClientServiceName, &metav1.DeleteOptions{}); err != nil {\n\t\t\t\tlogrus.Error(\"Could not delete service \"+fullClientServiceName+\":\", err)\n\t\t\t}\n\t\t\tlogrus.Infof(\"Deleted service: %s\", fullClientServiceName)\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func removeContainer(t *testing.T, c *Container) {\n\tif err := c.pool.Purge(c.resource); err != nil {\n\t\tt.Error(\"could not remove container:\", err)\n\t}\n}", "func TestDanglingContainerRemoval_Stopped(t *testing.T) {\n\tci.Parallel(t)\n\ttestutil.DockerCompatible(t)\n\n\t_, cfg, ports := dockerTask(t)\n\tdefer freeport.Return(ports)\n\n\tclient := newTestDockerClient(t)\n\tcontainer, err := client.CreateContainer(docker.CreateContainerOptions{\n\t\tName: \"mytest-image-\" + uuid.Generate(),\n\t\tConfig: &docker.Config{\n\t\t\tImage: cfg.Image,\n\t\t\tCmd: append([]string{cfg.Command}, cfg.Args...),\n\t\t\tLabels: map[string]string{\n\t\t\t\tdockerLabelAllocID: uuid.Generate(),\n\t\t\t},\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\tdefer client.RemoveContainer(docker.RemoveContainerOptions{\n\t\tID: container.ID,\n\t\tForce: true,\n\t})\n\n\terr = client.StartContainer(container.ID, nil)\n\trequire.NoError(t, err)\n\n\terr = client.StopContainer(container.ID, 60)\n\trequire.NoError(t, err)\n\n\tdd := dockerDriverHarness(t, nil).Impl().(*Driver)\n\treconciler := newReconciler(dd)\n\n\t// assert nomad container is tracked, and we ignore stopped one\n\ttf := reconciler.trackedContainers()\n\trequire.NotContains(t, tf, container.ID)\n\n\tuntracked, err := reconciler.untrackedContainers(map[string]bool{}, time.Now())\n\trequire.NoError(t, err)\n\trequire.NotContains(t, untracked, container.ID)\n\n\t// if we start container again, it'll be marked as untracked\n\trequire.NoError(t, client.StartContainer(container.ID, nil))\n\n\tuntracked, err = reconciler.untrackedContainers(map[string]bool{}, time.Now())\n\trequire.NoError(t, err)\n\trequire.Contains(t, untracked, container.ID)\n}", "func destroyDeployment(toRemove string) {\n\tlog.Debug(\"Destroying deployment %s\", toRemove)\n\toldPwd := sh.Pwd()\n\ttoRemoveRepo := path.Join(toRemove, sh.Basename(repoURL))\n\tsh.Cd(toRemoveRepo)\n\n\tlog.Debugf(\"Actually destroying resources now\")\n\tcloudRe := regexp.MustCompile(`(gce|aws|digitalocean|openstack|softlayer)`)\n\tif cloudRe.MatchString(toRemove) {\n\t\tlog.Debug(\"Destroying terraformed resources in %s\", toRemoveRepo)\n\t\tterraformDestroy(toRemoveRepo)\n\t} else {\n\t\tlog.Debug(\"Destroying vagrant box in %s\", toRemoveRepo)\n\t\tsh.SetE(exec.Command(\"vagrant\", \"destroy\", \"-f\"))\n\t}\n\n\tsh.Cd(oldPwd)\n\tlog.Debugf(\"Removing leftovers in %s\", toRemove)\n\tsh.RmR(toRemove)\n\tlog.Debug(\"Finished destruction process\")\n}", "func Kill(args ...string) {\n runInstances(\"Killing\", func(i int, id string) error {\n defer os.Remove(pidFileName(i))\n return run(\"kill\", id)\n })\n}", "func (k *kubernetes) Delete(s *runtime.Service) error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// create new kubernetes micro service\n\tservice := newService(s, runtime.CreateOptions{\n\t\tType: k.options.Type,\n\t})\n\n\tlog.Debugf(\"Runtime queueing service %s for delete action\", service.Name)\n\n\t// queue service for removal\n\tk.queue <- &task{\n\t\taction: stop,\n\t\tservice: service,\n\t}\n\n\treturn nil\n}", "func (i *Docker) Delete(assembly *global.AssemblyWithComponents, id string) (string, error) {\n\n\tpair_endpoint, perrscm := global.ParseKeyValuePair(assembly.Inputs, \"endpoint\")\n\tif perrscm != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", perrscm)\n\t}\n\n\tpair_id, iderr := global.ParseKeyValuePair(assembly.Components[0].Outputs, \"id\")\n\tif iderr != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", iderr)\n\t}\n\n\tvar endpoint string\n\tif pair_endpoint.Value == BAREMETAL {\n\n\t\tapi_host, _ := config.GetString(\"docker:swarm_host\")\n\t\tendpoint = api_host\n\n\t} else {\n\t\tendpoint = pair_endpoint.Value\n\t}\n\n\tclient, _ := docker.NewClient(endpoint)\n\tkerr := client.KillContainer(docker.KillContainerOptions{ID: pair_id.Value})\n\tif kerr != nil {\n\t\tlog.Error(\"Failed to kill the container : %s\", kerr)\n\t\treturn \"\", kerr\n\t}\n\tlog.Info(\"Container is killed\")\n\treturn \"\", nil\n}", "func (e *dockerExec) Kill(ctx context.Context) error {\n\tname := e.containerName()\n\tif err := e.client.ContainerKill(ctx, name, \"KILL\"); err != nil {\n\t\treturn errors.E(\"ContainerKill\", name, err)\n\t}\n\tif err := e.Wait(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn os.RemoveAll(e.path())\n}", "func cleanupClusterResources(ctx context.Context, clientset kubernetes.Interface, clusterName, namespace string) error {\n\tlistOpts := metav1.ListOptions{\n\t\tLabelSelector: \"multi-cluster=true\",\n\t}\n\n\t// clean up secrets\n\tsecretList, err := clientset.CoreV1().Secrets(namespace).List(ctx, listOpts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif secretList != nil {\n\t\tfor _, s := range secretList.Items {\n\t\t\tfmt.Printf(\"Deleting Secret: %s in cluster %s\\n\", s.Name, clusterName)\n\t\t\tif err := clientset.CoreV1().Secrets(namespace).Delete(ctx, s.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up service accounts\n\tserviceAccountList, err := clientset.CoreV1().ServiceAccounts(namespace).List(ctx, listOpts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif serviceAccountList != nil {\n\t\tfor _, sa := range serviceAccountList.Items {\n\t\t\tfmt.Printf(\"Deleting ServiceAccount: %s in cluster %s\\n\", sa.Name, clusterName)\n\t\t\tif err := clientset.CoreV1().ServiceAccounts(namespace).Delete(ctx, sa.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up roles\n\troleList, err := clientset.RbacV1().Roles(namespace).List(ctx, listOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, r := range roleList.Items {\n\t\tfmt.Printf(\"Deleting Role: %s in cluster %s\\n\", r.Name, clusterName)\n\t\tif err := clientset.RbacV1().Roles(namespace).Delete(ctx, r.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// clean up roles\n\troles, err := clientset.RbacV1().Roles(namespace).List(ctx, listOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif roles != nil {\n\t\tfor _, r := range roles.Items {\n\t\t\tfmt.Printf(\"Deleting Role: %s in cluster %s\\n\", r.Name, clusterName)\n\t\t\tif err := clientset.RbacV1().Roles(namespace).Delete(ctx, r.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up role bindings\n\troleBindings, err := clientset.RbacV1().RoleBindings(namespace).List(ctx, listOpts)\n\tif !errors.IsNotFound(err) && err != nil {\n\t\treturn err\n\t}\n\n\tif roleBindings != nil {\n\t\tfor _, crb := range roleBindings.Items {\n\t\t\tfmt.Printf(\"Deleting RoleBinding: %s in cluster %s\\n\", crb.Name, clusterName)\n\t\t\tif err := clientset.RbacV1().RoleBindings(namespace).Delete(ctx, crb.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up cluster role bindings\n\tclusterRoleBindings, err := clientset.RbacV1().ClusterRoleBindings().List(ctx, listOpts)\n\tif !errors.IsNotFound(err) && err != nil {\n\t\treturn err\n\t}\n\n\tif clusterRoleBindings != nil {\n\t\tfor _, crb := range clusterRoleBindings.Items {\n\t\t\tfmt.Printf(\"Deleting ClusterRoleBinding: %s in cluster %s\\n\", crb.Name, clusterName)\n\t\t\tif err := clientset.RbacV1().ClusterRoleBindings().Delete(ctx, crb.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up cluster roles\n\tclusterRoles, err := clientset.RbacV1().ClusterRoles().List(ctx, listOpts)\n\tif !errors.IsNotFound(err) && err != nil {\n\t\treturn err\n\t}\n\n\tif clusterRoles != nil {\n\t\tfor _, cr := range clusterRoles.Items {\n\t\t\tfmt.Printf(\"Deleting ClusterRole: %s in cluster %s\\n\", cr.Name, clusterName)\n\t\t\tif err := clientset.RbacV1().ClusterRoles().Delete(ctx, cr.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Botanist) DeleteAllContainerRuntimeResources(ctx context.Context) error {\n\treturn b.deleteContainerRuntimeResources(ctx, sets.NewString())\n}", "func (runtime DockerRuntime) KillContainer(ctx context.Context, id string) error {\n\treturn runtime.client.ContainerKill(ctx, id, \"KILL\")\n}", "func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts os.DeleteOptsBuilder) os.DeleteResult {\n\treturn os.Delete(c, containerName, objectName, nil)\n}", "func (p Pipeline) RemoveContainers(preRun bool) error {\n\t_, _, _, err := p.runCommand(runConfig{\n\t\tselection: func(step Step) bool {\n\t\t\treturn !preRun || step.Meta.KeepAlive != KeepAliveReplace\n\t\t},\n\t\trun: func(runner Runner, step Step) func() error {\n\t\t\treturn func() error {\n\t\t\t\tif err := p.GetRunnerForMeta(step.Meta).ContainerRemover(step)(); err != nil {\n\t\t\t\t\tpipelineLogger.Printf(\"Error removing %s: %s\", step.ColoredName(), err)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t},\n\t})\n\treturn err\n}", "func cephContainerDelete(clusterName string, poolName string, volumeName string,\n\tvolumeType string, userName string) int {\n\tlogEntry := fmt.Sprintf(\"%s/%s_%s\", poolName, volumeType, volumeName)\n\n\tsnaps, err := cephRBDVolumeListSnapshots(clusterName, poolName,\n\t\tvolumeName, volumeType, userName)\n\tif err == nil {\n\t\tvar zombies int\n\t\tfor _, snap := range snaps {\n\t\t\tlogEntry := fmt.Sprintf(\"%s/%s_%s@%s\", poolName,\n\t\t\t\tvolumeType, volumeName, snap)\n\n\t\t\tret := cephContainerSnapshotDelete(clusterName,\n\t\t\t\tpoolName, volumeName, volumeType, snap, userName)\n\t\t\tif ret < 0 {\n\t\t\t\tlogger.Errorf(`Failed to delete RBD storage volume \"%s\"`, logEntry)\n\t\t\t\treturn -1\n\t\t\t} else if ret == 1 {\n\t\t\t\tlogger.Debugf(`Marked RBD storage volume \"%s\" as zombie`, logEntry)\n\t\t\t\tzombies++\n\t\t\t} else {\n\t\t\t\tlogger.Debugf(`Deleted RBD storage volume \"%s\"`, logEntry)\n\t\t\t}\n\t\t}\n\n\t\tif zombies > 0 {\n\t\t\t// unmap\n\t\t\terr = cephRBDVolumeUnmap(clusterName, poolName,\n\t\t\t\tvolumeName, volumeType, userName, true)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to unmap RBD storage volume \"%s\": %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Unmapped RBD storage volume \"%s\"`, logEntry)\n\n\t\t\tif strings.HasPrefix(volumeType, \"zombie_\") {\n\t\t\t\tlogger.Debugf(`RBD storage volume \"%s\" already marked as zombie`, logEntry)\n\t\t\t\treturn 1\n\t\t\t}\n\n\t\t\tnewVolumeName := fmt.Sprintf(\"%s_%s\", volumeName,\n\t\t\t\tuuid.NewRandom().String())\n\t\t\terr := cephRBDVolumeMarkDeleted(clusterName, poolName,\n\t\t\t\tvolumeType, volumeName, newVolumeName, userName,\n\t\t\t\t\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to mark RBD storage volume \"%s\" as zombie: %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Marked RBD storage volume \"%s\" as zombie`, logEntry)\n\n\t\t\treturn 1\n\t\t}\n\t} else {\n\t\tif err != db.ErrNoSuchObject {\n\t\t\tlogger.Errorf(`Failed to retrieve snapshots of RBD storage volume: %s`, err)\n\t\t\treturn -1\n\t\t}\n\n\t\tparent, err := cephRBDVolumeGetParent(clusterName, poolName,\n\t\t\tvolumeName, volumeType, userName)\n\t\tif err == nil {\n\t\t\tlogger.Debugf(`Detected \"%s\" as parent of RBD storage volume \"%s\"`, parent, logEntry)\n\t\t\t_, parentVolumeType, parentVolumeName,\n\t\t\t\tparentSnapshotName, err := parseParent(parent)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to parse parent \"%s\" of RBD storage volume \"%s\"`, parent, logEntry)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Split parent \"%s\" of RBD storage volume \"%s\" into volume type \"%s\", volume name \"%s\", and snapshot name \"%s\"`, parent, logEntry, parentVolumeType,\n\t\t\t\tparentVolumeName, parentSnapshotName)\n\n\t\t\t// unmap\n\t\t\terr = cephRBDVolumeUnmap(clusterName, poolName,\n\t\t\t\tvolumeName, volumeType, userName, true)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to unmap RBD storage volume \"%s\": %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Unmapped RBD storage volume \"%s\"`, logEntry)\n\n\t\t\t// delete\n\t\t\terr = cephRBDVolumeDelete(clusterName, poolName,\n\t\t\t\tvolumeName, volumeType, userName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to delete RBD storage volume \"%s\": %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Deleted RBD storage volume \"%s\"`, logEntry)\n\n\t\t\t// Only delete the parent snapshot of the container if\n\t\t\t// it is a zombie. If it is not we know that LXD is\n\t\t\t// still using it.\n\t\t\tif strings.HasPrefix(parentVolumeType, \"zombie_\") ||\n\t\t\t\tstrings.HasPrefix(parentSnapshotName, \"zombie_\") {\n\t\t\t\tret := cephContainerSnapshotDelete(clusterName,\n\t\t\t\t\tpoolName, parentVolumeName,\n\t\t\t\t\tparentVolumeType, parentSnapshotName,\n\t\t\t\t\tuserName)\n\t\t\t\tif ret < 0 {\n\t\t\t\t\tlogger.Errorf(`Failed to delete snapshot \"%s\" of RBD storage volume \"%s\"`, parentSnapshotName, logEntry)\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\t\t\t\tlogger.Debugf(`Deleteed snapshot \"%s\" of RBD storage volume \"%s\"`, parentSnapshotName, logEntry)\n\t\t\t}\n\n\t\t\treturn 0\n\t\t} else {\n\t\t\tif err != db.ErrNoSuchObject {\n\t\t\t\tlogger.Errorf(`Failed to retrieve parent of RBD storage volume \"%s\"`, logEntry)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`RBD storage volume \"%s\" does not have parent`, logEntry)\n\n\t\t\t// unmap\n\t\t\terr = cephRBDVolumeUnmap(clusterName, poolName,\n\t\t\t\tvolumeName, volumeType, userName, true)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to unmap RBD storage volume \"%s\": %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Unmapped RBD storage volume \"%s\"`, logEntry)\n\n\t\t\t// delete\n\t\t\terr = cephRBDVolumeDelete(clusterName, poolName,\n\t\t\t\tvolumeName, volumeType, userName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(`Failed to delete RBD storage volume \"%s\": %s`, logEntry, err)\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tlogger.Debugf(`Deleted RBD storage volume \"%s\"`, logEntry)\n\n\t\t}\n\t}\n\n\treturn 0\n}", "func deleteAllStsAndPodsPVCsInNamespace(ctx context.Context, c clientset.Interface, ns string) {\n\tStatefulSetPoll := 10 * time.Second\n\tStatefulSetTimeout := 10 * time.Minute\n\tssList, err := c.AppsV1().StatefulSets(ns).List(context.TODO(),\n\t\tmetav1.ListOptions{LabelSelector: labels.Everything().String()})\n\tframework.ExpectNoError(err)\n\terrList := []string{}\n\tfor i := range ssList.Items {\n\t\tss := &ssList.Items[i]\n\t\tvar err error\n\t\tif ss, err = scaleStatefulSetPods(c, ss, 0); err != nil {\n\t\t\terrList = append(errList, fmt.Sprintf(\"%v\", err))\n\t\t}\n\t\tfss.WaitForStatusReplicas(c, ss, 0)\n\t\tframework.Logf(\"Deleting statefulset %v\", ss.Name)\n\t\tif err := c.AppsV1().StatefulSets(ss.Namespace).Delete(context.TODO(), ss.Name,\n\t\t\tmetav1.DeleteOptions{OrphanDependents: new(bool)}); err != nil {\n\t\t\terrList = append(errList, fmt.Sprintf(\"%v\", err))\n\t\t}\n\t}\n\tpvNames := sets.NewString()\n\tpvcPollErr := wait.PollImmediate(StatefulSetPoll, StatefulSetTimeout, func() (bool, error) {\n\t\tpvcList, err := c.CoreV1().PersistentVolumeClaims(ns).List(context.TODO(),\n\t\t\tmetav1.ListOptions{LabelSelector: labels.Everything().String()})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"WARNING: Failed to list pvcs, retrying %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tfor _, pvc := range pvcList.Items {\n\t\t\tpvNames.Insert(pvc.Spec.VolumeName)\n\t\t\tframework.Logf(\"Deleting pvc: %v with volume %v\", pvc.Name, pvc.Spec.VolumeName)\n\t\t\tif err := c.CoreV1().PersistentVolumeClaims(ns).Delete(context.TODO(), pvc.Name,\n\t\t\t\tmetav1.DeleteOptions{}); err != nil {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\tif pvcPollErr != nil {\n\t\terrList = append(errList, \"Timeout waiting for pvc deletion.\")\n\t}\n\n\tpollErr := wait.PollImmediate(StatefulSetPoll, StatefulSetTimeout, func() (bool, error) {\n\t\tpvList, err := c.CoreV1().PersistentVolumes().List(context.TODO(),\n\t\t\tmetav1.ListOptions{LabelSelector: labels.Everything().String()})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"WARNING: Failed to list pvs, retrying %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\twaitingFor := []string{}\n\t\tfor _, pv := range pvList.Items {\n\t\t\tif pvNames.Has(pv.Name) {\n\t\t\t\twaitingFor = append(waitingFor, fmt.Sprintf(\"%v: %+v\", pv.Name, pv.Status))\n\t\t\t}\n\t\t}\n\t\tif len(waitingFor) == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tframework.Logf(\"Still waiting for pvs of statefulset to disappear:\\n%v\", strings.Join(waitingFor, \"\\n\"))\n\t\treturn false, nil\n\t})\n\tif pollErr != nil {\n\t\terrList = append(errList, \"Timeout waiting for pv provisioner to delete pvs, this might mean the test leaked pvs.\")\n\n\t}\n\tif len(errList) != 0 {\n\t\tframework.ExpectNoError(fmt.Errorf(\"%v\", strings.Join(errList, \"\\n\")))\n\t}\n\n\tframework.Logf(\"Deleting Deployment Pods and its PVCs\")\n\tdepList, err := c.AppsV1().Deployments(ns).List(\n\t\tctx, metav1.ListOptions{LabelSelector: labels.Everything().String()})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tfor _, deployment := range depList.Items {\n\t\tdep := &deployment\n\t\terr = updateDeploymentReplicawithWait(c, 0, dep.Name, ns)\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tdeletePolicy := metav1.DeletePropagationForeground\n\t\terr = c.AppsV1().Deployments(ns).Delete(ctx, dep.Name, metav1.DeleteOptions{PropagationPolicy: &deletePolicy})\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Controller) Delete(ctx context.Context, name string) error {\n\tregistry, err := c.Get(ctx, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcID := registry.Status.ContainerID\n\tif cID == \"\" {\n\t\treturn fmt.Errorf(\"container not running registry: %s\", name)\n\t}\n\n\treturn c.dockerClient.ContainerRemove(ctx, registry.Status.ContainerID, types.ContainerRemoveOptions{\n\t\tForce: true,\n\t})\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 *Client) CleanUp(imagename, tagname string) error {\n\timageName := imagename + \":\" + tagname\n\tglog.Infof(\"About to clean up docker image:%s.\", imageName)\n\n\terr := c.RemoveImage(imageName)\n\tif err == nil {\n\t\tglog.Infof(\"Successfully remove docker image:%s.\", imageName)\n\t} else {\n\t\tglog.Errorf(\"Remove docker image:%s failed.\", imageName)\n\t}\n\n\treturn err\n}", "func (c *Containers) Close() error {\n\treturn nil\n}", "func Delete(k8sClient client.Client, obj client.Object) error {\n\treturn k8sClient.Delete(context.TODO(), obj)\n}", "func DeleteAKSCluster(client autorest.Client, urlParameters map[string]interface{}, apiVersion string) {\r\n\r\n\tqueryParameters := map[string]interface{}{\r\n\t\t\"api-version\": apiVersion,\r\n\t}\r\n\tpreparerDecorators := []autorest.PrepareDecorator{\r\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\r\n\t\tautorest.WithMethod(\"DELETE\"),\r\n\t\tautorest.WithBaseURL(azure.PublicCloud.ResourceManagerEndpoint),\r\n\t\tautorest.WithPathParameters(\r\n\t\t\t\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.containerservice/managedclusters/{resourceName}\",\r\n\t\t\turlParameters,\r\n\t\t),\r\n\t\tautorest.WithQueryParameters(queryParameters),\r\n\t}\r\n\r\n\tpreparer := autorest.CreatePreparer(preparerDecorators...)\r\n\treq, err := preparer.Prepare((&http.Request{}).WithContext(context.Background()))\r\n\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tfmt.Println(req.URL)\r\n\r\n\tresp, err := client.Do(req)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\terr = autorest.Respond(\r\n\t\tresp,\r\n\t\tclient.ByInspecting(),\r\n\t)\r\n\r\n\tfmt.Println(resp.Status)\r\n}", "func Delete(name string) error {\n\tinstance, err := Get(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find a cluster named '%s': %s\", name, err.Error())\n\t}\n\terr = instance.Delete()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete infrastructure of cluster '%s': %s\", name, err.Error())\n\t}\n\n\t// Deletes the network and related stuff\n\tutils.DeleteNetwork(instance.GetNetworkID())\n\n\t// Cleanup Object Storage data\n\treturn instance.RemoveDefinition()\n}", "func makeZookeeperContainers(z *bkcmdbv1.Bkcmdb) []v1.Container {\n\treturn []v1.Container{\n\t\t{\n\t\t\tName: z.GetName() + \"-zookeeper\",\n\t\t\tImage: \"gcr.io/google_samples/k8szk:v3\",\n\t\t\tImagePullPolicy: \"IfNotPresent\",\n\t\t\tCommand: []string{\"/bin/bash\", \"-xec\", \"zkGenConfig.sh && exec zkServer.sh start-foreground\"},\n\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_REPLICAS\",\n\t\t\t\t\tValue: \"1\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"JMXAUTH\",\n\t\t\t\t\tValue: \"false\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"JMXDISABLE\",\n\t\t\t\t\tValue: \"false\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"JMXPORT\",\n\t\t\t\t\tValue: \"1099\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"JMXSSL\",\n\t\t\t\t\tValue: \"false\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_CLIENT_PORT\",\n\t\t\t\t\tValue: \"2181\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_ELECTION_PORT\",\n\t\t\t\t\tValue: \"3888\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_HEAP_SIZE\",\n\t\t\t\t\tValue: \"2G\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_INIT_LIMIT\",\n\t\t\t\t\tValue: \"5\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_LOG_LEVEL\",\n\t\t\t\t\tValue: \"INFO\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_MAX_CLIENT_CNXNS\",\n\t\t\t\t\tValue: \"60\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_MAX_SESSION_TIMEOUT\",\n\t\t\t\t\tValue: \"40000\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_MIN_SESSION_TIMEOUT\",\n\t\t\t\t\tValue: \"4000\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_PURGE_INTERVAL\",\n\t\t\t\t\tValue: \"0\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_SERVER_PORT\",\n\t\t\t\t\tValue: \"2888\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_SNAP_RETAIN_COUNT\",\n\t\t\t\t\tValue: \"3\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_SYNC_LIMIT\",\n\t\t\t\t\tValue: \"10\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"ZK_TICK_TIME\",\n\t\t\t\t\tValue: \"2000\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t{\n\t\t\t\t\tName: \"client\",\n\t\t\t\t\tContainerPort: 2181,\n\t\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"election\",\n\t\t\t\t\tContainerPort: 3888,\n\t\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"server\",\n\t\t\t\t\tContainerPort: 2888,\n\t\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLivenessProbe: &v1.Probe{\n\t\t\t\tHandler: v1.Handler{\n\t\t\t\t\tExec: &v1.ExecAction{\n\t\t\t\t\t\tCommand: []string{\"zkOk.sh\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tInitialDelaySeconds: 20,\n\t\t\t},\n\t\t\tReadinessProbe: &v1.Probe{\n\t\t\t\tHandler: v1.Handler{\n\t\t\t\t\tExec: &v1.ExecAction{\n\t\t\t\t\t\tCommand: []string{\"zkOk.sh\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tInitialDelaySeconds: 20,\n\t\t\t},\n\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t{\n\t\t\t\t\tName: \"data\",\n\t\t\t\t\tMountPath: \"/var/lib/zookeeper\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func createContainers(ctx context.Context, cli *client.Client, containerNames []string) ([]string, error) {\n\tcntrIDs := make([]string, len(containerNames))\n\n\tfor idx, cname := range containerNames {\n\t\t// create the docker container\n\t\tcbody, err := cli.ContainerCreate(ctx, &cn.Config{Image: \"ubuntu\", Tty: true}, &cn.HostConfig{},\n\t\t\t&nw.NetworkingConfig{}, &specs.Platform{}, cname)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// start the docker container\n\t\terr = cli.ContainerStart(ctx, cbody.ID, types.ContainerStartOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcntrIDs[idx] = cbody.ID\n\t}\n\n\treturn cntrIDs, nil\n}", "func (c *Container) Kill(ctx context.Context) error {\n\tdefer c.stopProfiling()\n\treturn c.client.ContainerKill(ctx, c.id, \"\")\n}" ]
[ "0.63340247", "0.6316679", "0.63003445", "0.61168224", "0.60297364", "0.602845", "0.6010872", "0.5956652", "0.59419936", "0.59391356", "0.59131247", "0.5894728", "0.58919394", "0.58671063", "0.5793185", "0.57930833", "0.57607406", "0.57445747", "0.5731923", "0.5720401", "0.56616384", "0.56140196", "0.56060606", "0.5598637", "0.55850685", "0.55805063", "0.5565991", "0.55573326", "0.55299383", "0.5501759", "0.5495042", "0.54842675", "0.5451483", "0.5442371", "0.54410154", "0.542452", "0.54005563", "0.5400006", "0.5385813", "0.5375701", "0.5368435", "0.53310096", "0.5306443", "0.5291768", "0.5289236", "0.52888453", "0.528103", "0.5280907", "0.52807605", "0.5277934", "0.52757347", "0.5267875", "0.52675235", "0.5263268", "0.5255224", "0.5251131", "0.52450037", "0.52365774", "0.5234664", "0.52311903", "0.5223143", "0.52167386", "0.52110404", "0.52023065", "0.5202233", "0.51956147", "0.51922435", "0.5174499", "0.5172767", "0.5168511", "0.5164335", "0.5161378", "0.5161158", "0.51535374", "0.5152409", "0.5148315", "0.5147159", "0.51349634", "0.513245", "0.51279044", "0.5126452", "0.5120785", "0.5119725", "0.5101501", "0.5100414", "0.5095564", "0.5092022", "0.5085441", "0.5074609", "0.5074037", "0.5065608", "0.50586885", "0.5052977", "0.5048019", "0.5039578", "0.5037666", "0.5021538", "0.502037", "0.50196695", "0.5017805" ]
0.6113355
4
Start will start the provided command and return a Session that can be used to await completion or signal the process. The provided logger is used log stderr from the running process.
func Start(logger *flogging.FabricLogger, cmd *exec.Cmd, exitFuncs ...ExitFunc) (*Session, error) { logger = logger.With("command", filepath.Base(cmd.Path)) stderr, err := cmd.StderrPipe() if err != nil { return nil, err } err = cmd.Start() if err != nil { return nil, err } sess := &Session{ command: cmd, exitFuncs: exitFuncs, exited: make(chan struct{}), } go sess.waitForExit(logger, stderr) return sess, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Start(t *testing.T, cmd *exec.Cmd) (*StartSession, error) {\n\tt.Helper()\n\tt.Logf(\"(dbg) daemon: %v\", cmd.Args)\n\n\tstdoutPipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tt.Fatalf(\"stdout pipe failed: %v %v\", cmd.Args, err)\n\t}\n\tstderrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tt.Fatalf(\"stderr pipe failed: %v %v\", cmd.Args, err)\n\t}\n\n\tsr := &StartSession{Stdout: bufio.NewReader(stdoutPipe), Stderr: bufio.NewReader(stderrPipe), cmd: cmd}\n\treturn sr, cmd.Start()\n}", "func (c *Cmd) Start() error {\n\tif c.Process != nil {\n\t\treturn errAlreadyStarted\n\t}\n\n\t// Return early if deadline is already expired.\n\tselect {\n\tcase <-c.ctx.Done():\n\t\treturn c.ctx.Err()\n\tdefault:\n\t}\n\n\t// Collect stdout/stderr to log by default.\n\tif c.Stdout == nil {\n\t\tc.Stdout = &c.log\n\t}\n\tif c.Stderr == nil {\n\t\tc.Stderr = &c.log\n\t}\n\n\tif err := c.Cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t// Watchdog goroutine to terminate the process on timeout.\n\tgo func() {\n\t\t// TODO(nya): Avoid the race condition between reaping the child process\n\t\t// and sending a signal.\n\t\tselect {\n\t\tcase <-c.ctx.Done():\n\t\t\tc.Kill()\n\t\tcase <-c.watchdogStop:\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (cmd Cmd) Start(ctx context.Context) (Process, error) {\n\t// Deliberately a value receiver so the cmd object can be updated prior to execution\n\tif cmd.Target == nil {\n\t\tcmd.Target = LocalTarget\n\t} else if cmd.Target != LocalTarget {\n\t\tctx = log.V{\"On\": cmd.Target}.Bind(ctx)\n\t}\n\n\tif cmd.Dir != \"\" {\n\t\tctx = log.V{\"Dir\": cmd.Dir}.Bind(ctx)\n\t}\n\t// build our stdout and stderr handling\n\tvar logStdout, logStderr io.WriteCloser\n\tif cmd.Verbosity {\n\t\tctx := log.PutProcess(ctx, filepath.Base(cmd.Name))\n\t\tlogStdout = log.From(ctx).Writer(log.Info)\n\t\tdefer logStdout.Close()\n\t\tif cmd.Stdout != nil {\n\t\t\tcmd.Stdout = io.MultiWriter(cmd.Stdout, logStdout)\n\t\t} else {\n\t\t\tcmd.Stdout = logStdout\n\t\t}\n\t\tlogStderr = log.From(ctx).Writer(log.Error)\n\t\tdefer logStderr.Close()\n\t\tif cmd.Stderr != nil {\n\t\t\tcmd.Stderr = io.MultiWriter(cmd.Stderr, logStderr)\n\t\t} else {\n\t\t\tcmd.Stderr = logStderr\n\t\t}\n\t}\n\t// Ready to start\n\tif cmd.Verbosity {\n\t\textra := \"\"\n\t\tif cmd.Dir != \"\" {\n\t\t\textra = fmt.Sprintf(\" In %v\", cmd.Dir)\n\t\t}\n\t\tlog.I(ctx, \"Exec: %v%s\", cmd, extra)\n\t}\n\treturn cmd.Target.Start(cmd)\n}", "func (c *Cmd) Start() error", "func Start() Command {\n\treturn &startCommand{}\n}", "func (client *NativeClient) Start(command string) (io.ReadCloser, io.ReadCloser, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := session.Start(command); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient.openSession = session\n\treturn ioutil.NopCloser(stdout), ioutil.NopCloser(stderr), nil\n}", "func (c *Cmd) Start() error {\n\treturn c.start()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {// {{{\n //fmt.Println(\"Start a command\")\n index := -1\n term, isLeader := rf.GetState()\n if isLeader {\n rf.mu.Lock()\n\t index = len(rf.log)\n rf.log = append(rf.log, LogEntry{Term: term, Cmd: command})\n //rf.matchIdx[rf.me] = len(rf.log) - 1\n rf.persist()\n rf.debug(\"Command appended to Log: idx=%v, cmd=%v\\n\", index, command)\n rf.mu.Unlock()\n }\n //fmt.Println(\"Start a command return\")\n\treturn index, term, isLeader\n}", "func (a *ExternalAgentProcess) Start() error {\n\treturn a.cmd.Start()\n}", "func (c *SSHCommand) Start() error {\n\treturn c.cmd.Start()\n}", "func (execution *Execution) Start() error {\n\tif execution.logger != nil {\n\t\texecution.logger(\n\t\t\texecution.command.GetArgs(),\n\t\t\tLaunch,\n\t\t\t[]byte(`launch`),\n\t\t)\n\t}\n\n\terr := execution.setupStreams()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := execution.command.Start(); err != nil {\n\t\treturn karma.Format(\n\t\t\terr,\n\t\t\t`can't start command: %s`,\n\t\t\texecution.String(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (c *Cmd) Start() error {\n\t// go routines to scan command out and err\n\tif c.ShowOutput {\n\t\terr := c.createPipeScanners()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.Cmd.Start()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tif !rf.IsLeader() {\n\t\treturn -1, -1, false\n\t}\n\n\t// incrementing logIndex should be execute with adding entry atomically\n\t// entry needs to be added in order\n\trf.mu.Lock()\n\trf.logIndex += 1\n\tentry := LogEntry{\n\t\tCommand: command,\n\t\tIndex: rf.logIndex,\n\t\tTerm: rf.currentTerm,\n\t}\n\t// append locally\n\trf.logs[entry.Index] = entry\n\trf.matchIndex[rf.me] = rf.logIndex\n\t_, _ = rf.dprintf(\"Term_%-4d [%d]:%-9s start to replicate a log at %d:%v\\n\", rf.currentTerm, rf.me, rf.getRole(), rf.logIndex, entry)\n\trf.persist()\n\trf.mu.Unlock()\n\n\treturn int(entry.Index), int(entry.Term), true\n}", "func StartCommand() {\n\tlog.Info(\"Do something\")\n\n\tlog.Debug(\"Debug\")\n\tlog.Info(\"Info\")\n\tlog.Warn(\"Warn\")\n\tlog.Error(\"Error\")\n\tlog.Fatal(\"Fatal\")\n}", "func (c *Command) Start() error {\n\tif c.timeout > 0 {\n\t\t// Setpgid: true creates a new process group for cmd and its subprocesses\n\t\t// this way we can kill the whole process group\n\t\tc.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\t}\n\n\tif err := c.cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tif c.timeout > 0 {\n\t\t// terminate the process after the given timeout\n\t\tc.timeoutTimer = time.AfterFunc(c.timeout, func() {\n\t\t\tif err := c.Stop(); err != nil {\n\t\t\t\tlog.Warnf(\"Failed to kill the process, error: %s\", err)\n\t\t\t}\n\t\t})\n\n\t\t// Setpgid: true creates a new process group for cmd and its subprocesses\n\t\t// this way cmd will not belong to its parent process group,\n\t\t// cmd will not be killed when you hit ^C in your terminal\n\t\t// to fix this, we listen and handle Interrupt signal manually\n\t\tc.interruptChan = make(chan os.Signal, 1)\n\t\tsignal.Notify(c.interruptChan, os.Interrupt)\n\t\tgo func() {\n\t\t\t<-c.interruptChan\n\t\t\tsignal.Stop(c.interruptChan)\n\t\t\tif err := c.Stop(); err != nil {\n\t\t\t\tlog.Warnf(\"Failed to kill the process, error: %s\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn c.cmd.Wait()\n}", "func New(logger Logger, cmd Command) *Execution {\n\tif logger == nil {\n\t\tlogger = Loggerf(func(string, ...interface{}) {})\n\t}\n\n\texecution := &Execution{\n\t\tcommand: cmd,\n\t\tlogger: logger,\n\t}\n\n\texecution.stdout = &bytes.Buffer{}\n\texecution.stderr = &bytes.Buffer{}\n\n\texecution.combinedStreams = []StreamData{}\n\n\treturn execution\n}", "func StartLogger(name, filename string, verbose bool) *logger.Logger {\n\tlogPath := \"/var/log/gogios/\" + filename + \".log\"\n\n\tfile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Failed to open log file: %v\", err)\n\t}\n\tdefer file.Close()\n\n\tgoglog := logger.Init(name, verbose, true, file)\n\n\treturn goglog\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tterm, isLeader := rf.GetState()\n\tif isLeader {\n\t\tentry := &LogEntry{\n\t\t\tTerm: term,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.logs = append(rf.logs, entry)\n\t\trf.replicateCount = append(rf.replicateCount, 1)\n\t\tDPrintf(\"Peer %d: New command %v, index is %d\", rf.me, command, len(rf.logs))\n\t\treturn len(rf.logs), term, true\n\t} else {\n\t\treturn -1, -1, false\n\t}\n}", "func (l *Logger) StartLogger() {\n\tfor {\n\t\tselect {\n\t\tcase bm := <-l.msg:\n\t\t\tfor _, l := range l.outputs {\n\t\t\t\tif err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {\n\t\t\t\t\tfmt.Println(\"ERROR, unable to WriteMsg:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-l.quit:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Process) Start() error {\n\t// See if we have a PID.\n\tif p.PID > 0 {\n\t\t// See if there is still a process with that PID.\n\t\t_, err := process.NewProcess(p.PID)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"process with PID %d already started\", p.PID)\n\t\t}\n\t\t// Process for this PID no longer running so clear the PID and start\n\t\t// new process.\n\t\tp.PID = 0\n\t}\n\n\tif p.Cmdline == \"\" {\n\t\treturn errors.New(\"no Cmdline set\")\n\t}\n\n\tp2, err := p.Pane.StartProcess(p.Cmdline)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*p = *p2\n\n\treturn nil\n}", "func (c Command) Start(args ...string) error {\n\treturn c.builder().Start(args...)\n}", "func (bot *DiscordBot) Start(ctx context.Context) (<-chan struct{}, error) {\n\tbot.logger.Info(\"starting bot\")\n\n\tif err := bot.addHandlers(bot.session); err != nil {\n\t\treturn nil, fmt.Errorf(\"add handlers for session :%w\", err)\n\t}\n\n\tif err := bot.session.Open(); err != nil {\n\t\treturn nil, fmt.Errorf(\"open session: %w\", err)\n\t}\n\n\tch := make(chan struct{}, 1)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tbot.logger.Info(\"closing discord session\")\n\n\t\tif cErr := bot.session.Close(); cErr != nil {\n\t\t\tbot.logger.Error(cErr, \"close discord session\")\n\t\t}\n\n\t\tbot.logger.Info(\"session has closed\")\n\t\tclose(ch)\n\t}()\n\n\treturn ch, nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == Leader\n\t//If command received from client: append entry to local log, respond after entry applied to state machine (§5.3)\n\tif isLeader {\n\t\tindex = rf.GetLastLogIndex() + 1\n\t\tnewLog := LogEntry{\n\t\t\trf.currentTerm,\n\t\t\tcommand,\n\t\t}\n\t\trf.logEntries = append(rf.logEntries,newLog)\n\t}\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tisLeader = rf.role == LEADER\n\tterm = rf.currentTerm\n\n\tif isLeader {\n\t\tindex = rf.getLastLogIndex() + 1\n\t\tlog := LogEntry{\n\t\t\tIndex: index,\n\t\t\tTerm: rf.currentTerm,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.log = append(rf.log, log)\n\n\t\trf.persist()\n\t}\n\n\treturn index, term, isLeader\n}", "func (p *adapter) Start() error {\n\tif err := p.cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"error starting process: %s\", err.Error())\n\t}\n\tgo p.startWait()\n\treturn nil\n}", "func (c *Command) Start() error {\n\tif utils.StringInSlice(command, configuration.Config.Commands) {\n\t\tc.Started = true\n\t}\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == Leader\n\n\tif isLeader {\n\t\tindex = rf.getLastLogIdx() + 1\n\t\tnewLog := Log{\n\t\t\trf.currentTerm,\n\t\t\tcommand,\n\t\t}\n\t\trf.logs = append(rf.logs, newLog)\n\t\trf.persist()\n\t\trf.broadcastHeartbeat()\n\t}\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tdefer rf.persist()\n\n\tindex := -1\n\tterm := -1\n\tisLeader := false\n\n\tif rf.role != LEADER {\n\t\treturn index, term, isLeader\n\t}\n\n\t_, idx := rf.getLastLogTermAndIdx()\n\tentry := LogEntry{Index: idx + 1, Term: rf.currentTerm, Command: command}\n\trf.logEntries = append(rf.logEntries, entry)\n\trf.matchIndex[rf.me] = idx + 1\n\n\tindex = idx + 1\n\tterm = rf.currentTerm\n\tisLeader = true\n\t// Your code here (2B).\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.killed() || rf.state != LEADER {\n\t\treturn len(rf.log), rf.currentTerm, false\n\t}\n\n\trf.log = append(rf.log, Log{rf.currentTerm, command})\n\trf.persist()\n\n\treturn len(rf.log) - 1, rf.currentTerm, true\n}", "func (cmd *Command) Start() error {\n\terr := cmd.c.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Get the command's PGID for logging. If this fails, we'll try\n\t// again in cmd.signal() when it is needed.\n\tpgid, err := syscall.Getpgid(cmd.c.Process.Pid)\n\tif err != nil {\n\t\tactivity.Record(cmd.ctx, \"%v: could not get pgid: %v\", cmd, err)\n\t} else {\n\t\tcmd.pgid = pgid\n\t}\n\t// Setup the context-cancellation cleanup\n\tgo func() {\n\t\tselect {\n\t\tcase <-cmd.waitDoneCh:\n\t\t\treturn\n\t\tcase <-cmd.ctx.Done():\n\t\t\t// Pass-thru\n\t\t}\n\t\tactivity.Record(cmd.ctx, \"%v: Context cancelled. Sending SIGTERM signal\", cmd)\n\t\tif err := cmd.signal(syscall.SIGTERM); err != nil {\n\t\t\tactivity.Record(cmd.ctx, \"%v: Failed to send SIGTERM signal: %v\", cmd, err)\n\t\t} else {\n\t\t\t// SIGTERM was sent. Send SIGKILL after five seconds if the command failed\n\t\t\t// to terminate.\n\t\t\ttime.AfterFunc(5 * time.Second, func() {\n\t\t\t\tselect {\n\t\t\t\tcase <-cmd.waitDoneCh:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\t// Pass-thru\n\t\t\t\t}\n\t\t\t\tactivity.Record(cmd.ctx, \"%v: Did not terminate after five seconds. Sending SIGKILL signal\", cmd)\n\t\t\t\tif err := cmd.signal(syscall.SIGKILL); err != nil {\n\t\t\t\t\tactivity.Record(cmd.ctx, \"%v: Failed to send SIGKILL signal: %v\", cmd, err)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\t// Call Wait() to release cmd's resources. Leave error-logging up to the\n\t\t// callers\n\t\t_ = cmd.Wait()\n\t}()\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (index int, term int, isLeader bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tisLeader = rf.state.Load() == leader\n\tif !isLeader {\n\t\treturn\n\t}\n\n\tterm = rf.currentTerm.Load().(int)\n\tindex = rf.logsLen()\n\trf.logs = append(rf.logs, Log{\n\t\tTerm: term,\n\t\tData: command,\n\t})\n\n\trf.nextIndex[rf.me] = index + 1\n\trf.matchIndex[rf.me] = index\n\trf.persist()\n\n\t// log.Printf(\"append log: new log %v\\n\", rf.logs)\n\n\treturn index + 1, term, isLeader\n}", "func Start(command string, args []string, w io.Writer) (\n\tstop context.CancelFunc,\n\twait WaitFunc,\n) {\n\tctx, stop := context.WithCancel(context.Background())\n\tstatus := make(chan error)\n\twait = func() error {\n\t\treturn <-status\n\t}\n\tgo run(ctx, command, args, w, status)\n\treturn\n}", "func (a *LogAgent) Start(persister operator.Persister) (err error) {\n\ta.startOnce.Do(func() {\n\t\terr = a.pipeline.Start(persister)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn\n}", "func (t *Transaction) Start(ctx context.Context) error {\n\tcmd := fmt.Sprintf(\"%s transaction %s\", t.Binary, t.Repo)\n\tres := shell.Run(cmd, shell.Context(ctx))\n\tt.log.InfoL(res.Stdout().Lines())\n\tt.log.ErrorL(res.Stderr().Lines())\n\treturn res.Err()\n}", "func (s *Scheduler) Start() error {\n\tif s.h == nil {\n\t\treturn fmt.Errorf(\"command handler not set\")\n\t}\n\n\ts.cctx, s.cancel = context.WithCancel(context.Background())\n\ts.done = make(chan struct{})\n\n\tgo s.run()\n\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mtx.Lock()\n\tdefer rf.mtx.Unlock()\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == STATE_LEADER\n\tif isLeader {\n\t\tindex = rf.log[len(rf.log)-1].LogIndex + 1\n\t\trf.log = append(rf.log, logEntries{Term: term, Log: command, LogIndex: index}) // append new entry from client\n\t\trf.persist()\n\t}\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.role != Leader {\n\t\treturn -1, -1, false\n\t}\n\n\t// DPrintf(\"Leader %d receive new command %v\", rf.me, command)\n\n\trf.log = append(rf.log, LogEntry{\n\t\tTerm: rf.currentTerm,\n\t\tCommand: command,\n\t})\n\trf.matchIndex[rf.me] = len(rf.log) + rf.compactIndex\n\n\treturn len(rf.log) + rf.compactIndex, rf.currentTerm, true\n}", "func (r *Runtime) Start() (e error) {\n\tstdout, e := r.cmd.StdoutPipe()\n\tif e != nil {\n\t\treturn\n\t}\n\tstderr, e := r.cmd.StderrPipe()\n\tif e != nil {\n\t\treturn\n\t}\n\n\tgo io.Copy(os.Stdout, stdout)\n\tgo io.Copy(os.Stdout, stderr)\n\n\tif e = r.cmd.Start(); e != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := -1\n\tterm := -1\n\tisLeader := false\n\n\tif rf.state == LEADER {\n\t\tterm = rf.currentTerm\n\t\tisLeader = true\n\t\trf.log = append(\n\t\t\trf.log,\n\t\t\tLogEntry{\n\t\t\t\tIndex: index,\n\t\t\t\tTerm: term,\n\t\t\t\tCommand: command,\n\t\t\t})\n\t\tindex = len(rf.log)\n\t\trf.persist()\n\t}\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tstate := rf.state\n\trf.mu.Unlock()\n\tif state != LEADER {\n\t\treturn -1, -1, false\n\t}\n\tDPrintf(\"[START COMMAND] %d ON NODE %d TERM %d\", command, rf.me, rf.currentTerm)\n\n\tindex := -1\n\tterm, isLeader := rf.GetState()\n\n\t// Your code here (2B).\n\n\tlog := Log{rf.currentTerm, command}\n\n\n\trf.mu.Lock()\n\tindex = len(rf.logs)\n\trf.logs = append(rf.logs, log)\n\trf.matchIndex[rf.me] += 1\n\trf.nextIndex[rf.me] += 1\n\trf.mu.Unlock()\n\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == Leader\n\n\t// Your code here (2B).\n\tif isLeader {\n\n\t\tDPrintf(\"i am leader %v, and i send command %v\", rf.me, command)\n\n\t\tindex = rf.getLastLogIndex() + 1\n\t\tnewLog := Log{\n\t\t\tTerm: rf.currentTerm,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.log = append(rf.log, newLog)\n\t\trf.persist()\n\t\t//fmt.Println(\"i am leader,\", rf.me)\n\t}\n\treturn index, term, isLeader\n}", "func (m *mware) Start() error {\n\tif err := m.cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start middleware command: %w\", err)\n\t}\n\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tisLeader := rf.IsLeader()\n\tif !isLeader {\n\t\trf.debug(\"Rejecting new command.\\n\")\n\t\treturn -1, -1, false\n\t}\n\n\tindex := rf.lastEntryIndex() + 1\n\tterm := rf.currentTerm\n\n\trf.log = append(rf.log, JobEntry{Job: command, Term: term})\n\trf.matchIndex[rf.me]++ // This is needed for the commit check\n\n\trf.debug(\"Adding new command at term %v, at index %v, content=%v\\n\", rf.currentTerm, index, command)\n\n\t// save state\n\trf.persist(false)\n\trf.canSend = true\n\n\treturn index, term, isLeader\n}", "func (p *spaDevProxy) Start(ctx context.Context) error {\n\tif _, err := os.Stat(p.options.Dir); err != nil {\n\t\treturn err\n\t}\n\tpath, args := prepareRunner(p.options.RunnerType, p.options.ScriptName, p.options.Args...)\n\tp.cmd = newCommand(ctx, path, args...)\n\tp.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\tp.cmd.Env = append(p.options.Env, fmt.Sprintf(\"PATH=%s\", os.Getenv(\"PATH\")))\n\tp.cmd.Dir = p.options.Dir\n\n\tstdout, err := p.cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := p.cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdone := p.forwardOutput(stdout, stderr)\n\n\terr = p.cmd.Start()\n\n\t<-done\n\n\treturn err\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tif rf.state != LEADER {\n\t\treturn -1, -1, false\n\t}\n\n\tindex := len(rf.logs)\n\trf.logs = append(rf.logs, command)\n\trf.logs_term = append(rf.logs_term, rf.currentTerm)\n\trf.persist()\n\n\trf.logger.Printf(\"New command, append at %v with term = %v\\n\", index, rf.currentTerm)\n\n\t// in the paper, index starts from 1\n\treturn index + 1, rf.currentTerm, rf.state == LEADER\n}", "func (s *RunnableCmd) Start() error {\n\treturn errors.WithMessage(s.cmd.Start(), \"failed to start RunnableCmd: \"+s.Args())\n}", "func (cmd *PortCommand) Start() error {\n\tif err := cmd.init(); err != nil {\n\t\treturn err\n\t}\n\treturn cmd.BaseCommand.Start()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := false\n\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tif !rf.killed() && rf.getState() == Leader {\n\t\tisLeader = true\n\t\tlastEntry := rf.getLastLog()\n\t\tindex = lastEntry.Index + 1\n\t\tterm = rf.currentTerm\n\t\tnewEntry := LogEntry{\n\t\t\tTerm: term,\n\t\t\tIndex: index,\n\t\t\tCommand: command,\n\t\t}\n\t\t//DPrintf(\"peer=%v start command=%+v\", rf.me, newEntry)\n\t\trf.logEntries = append(rf.logEntries, newEntry)\n\t}\n\trf.mu.Unlock()\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (idx int, currentTerm int, isLeader bool) {\n\tif rf.state != StateLeader {\n\t\treturn -1, rf.currentTerm, false\n\t}\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tlogEntry := &LogEntry{rf.currentTerm, command}\n\trf.logs = append(rf.logs, logEntry)\n\tlog.Info(\"start\", logEntry, \"leader\", rf.me, \"index\", rf.getLastLogIndex())\n\treturn rf.getLastLogIndex(), rf.currentTerm, true\n}", "func (inst *Instance) Start() error {\n\t// pre-check\n\tgo func() {\n\t\tvar err error\n\t\t// create inst.command first\n\t\tinst.createProcess()\n\t\tif err = inst.start(); err != nil {\n\t\t\treturn\n\t\t}\n\t\t// wait for process finish\n\t\terr = inst.wait()\n\t\tinst.afterWait(err)\n\t\t// close event handle\n\t\tinst.eventHandle.close()\n\t}()\n\treturn nil\n}", "func (p *process) Start() error {\n\tif p.ID() == InitProcessID {\n\t\tvar (\n\t\t\terrC = make(chan error, 1)\n\t\t\targs = append(p.container.runtimeArgs, \"start\", p.container.id)\n\t\t\tcmd = exec.Command(p.container.runtime, args...)\n\t\t)\n\t\tgo func() {\n\t\t\tout, err := cmd.CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\terrC <- fmt.Errorf(\"%s: %q\", err.Error(), out)\n\t\t\t}\n\t\t\terrC <- nil\n\t\t}()\n\t\tselect {\n\t\tcase err := <-errC:\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-p.cmdDoneCh:\n\t\t\tif !p.cmdSuccess {\n\t\t\t\tif cmd.Process != nil {\n\t\t\t\t\tcmd.Process.Kill()\n\t\t\t\t}\n\t\t\t\tcmd.Wait()\n\t\t\t\treturn ErrShimExited\n\t\t\t}\n\t\t\terr := <-errC\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 (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state == Leader {\n\t\tisLeader = true\n\t\tindex = len(rf.log)\n\t\tterm = rf.currentTerm\n\t\trf.log = append(rf.log, LogEntry{term, command})\n\t\trf.persist()\n\t\tgo rf.BroadcastAppendEntries()\n\t} else {\n\t\tisLeader = false\n\t}\n\n\treturn index, term, isLeader\n}", "func (c *Communicator) Start(rc *remote.Cmd) error {\n\trc.Init()\n\tlog.Printf(\"[DEBUG] starting remote command: %s\", rc.Command)\n\n\t// TODO: make sure communicators always connect first, so we can get output\n\t// from the connection.\n\tif c.client == nil {\n\t\tlog.Println(\"[WARN] winrm client not connected, attempting to connect\")\n\t\tif err := c.Connect(nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatus, err := c.client.Run(rc.Command, rc.Stdout, rc.Stderr)\n\trc.SetExitStatus(status, err)\n\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tindex := rf.Log.Length() + 1\n\tterm := rf.CurrentTerm\n\tisLeader := rf.isLeader\n\trf.mu.Unlock()\n\tif isLeader {\n\t\t// Start the agreement now for this entry.\n\t\trf.mu.Lock()\n\t\tindex = rf.Log.Length() + 1\n\t\trf.Log.Entries = append(rf.Log.Entries, LogEntry{Command: command, Term: rf.CurrentTerm})\n\t\trf.mu.Unlock()\n\t\trf.persist()\n\t\tgo rf.startAgreement()\n\t}\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\t// Your code here (2B).\n\n\tif rf.leader == rf.me {\n\t\trf.mu.Lock()\n\t\tdefer rf.mu.Unlock()\n\n\t\t// Append log to master\n\t\tlog.Println(\"Raft \", rf.me, \" add command \", command)\n\t\tnewLog := logItem{rf.currentTerm, command.(int)}\n\t\trf.log = append(rf.log, newLog)\n\t\tindex = len(rf.log) - 1\n\t\tterm = rf.currentTerm\n\t} else {\n\t\tisLeader = false\n\t}\n\n\treturn index, term, isLeader\n}", "func (s *DefaultServer) Start() error {\n\n\tstdout, _ := s.cmd.StdoutPipe()\n\tstderr, _ := s.cmd.StderrPipe()\n\n\tgo scanStream(stdout, &s.stdout, &s.lock)\n\tgo scanStream(stderr, &s.stderr, &s.lock)\n\n\treturn s.cmd.Start()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.serverState != Leader {\n\t\treturn -1, rf.currentTerm, false\n\t}\n\tentryIndex := rf.lastIncludedIndex + len(rf.log)\n\tentry := LogEntry{\n\t\tTerm: rf.currentTerm,\n\t\tCommand: command}\n\trf.log = append(rf.log, entry)\n\trf.nextIndex[rf.me] = entryIndex + 1\n\trf.matchIndex[rf.me] = entryIndex\n\treturn entryIndex, rf.currentTerm, rf.serverState == Leader\n}", "func StartCommand(ctx context.Context, cmd string, args ...string) Fixer {\n\treturn func() (string, error) {\n\t\tcmd := exec.CommandContext(ctx, cmd, args...)\n\t\terr := cmd.Start()\n\t\tif err != nil {\n\t\t\treturn \"command did not start successfully.\", err\n\t\t}\n\t\treturn \"command started successfully.\", nil\n\t}\n}", "func (s *SSHRunner) StartCmd(cmd *exec.Cmd) (*StartedCmd, error) {\n\tif cmd.Stdin != nil {\n\t\treturn nil, fmt.Errorf(\"SSHRunner does not support stdin - you could be the first to add it\")\n\t}\n\n\tif s.s != nil {\n\t\treturn nil, fmt.Errorf(\"another SSH command has been started and is currently running\")\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\trr := &RunResult{Args: cmd.Args}\n\tsc := &StartedCmd{cmd: cmd, rr: rr, wg: &wg}\n\tklog.Infof(\"Start: %v\", rr.Command())\n\n\tvar outb, errb io.Writer\n\n\tif cmd.Stdout == nil {\n\t\tvar so bytes.Buffer\n\t\toutb = io.MultiWriter(&so, &rr.Stdout)\n\t} else {\n\t\toutb = io.MultiWriter(cmd.Stdout, &rr.Stdout)\n\t}\n\n\tif cmd.Stderr == nil {\n\t\tvar se bytes.Buffer\n\t\terrb = io.MultiWriter(&se, &rr.Stderr)\n\t} else {\n\t\terrb = io.MultiWriter(cmd.Stderr, &rr.Stderr)\n\t}\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn sc, errors.Wrap(err, \"NewSession\")\n\t}\n\n\ts.s = sess\n\n\terr = teeSSHStart(s.s, shellquote.Join(cmd.Args...), outb, errb, &wg)\n\n\treturn sc, err\n}", "func (r *Runsc) Start(context context.Context, id string, cio runc.IO) error {\n\tcmd := r.command(context, \"start\", id)\n\tif cio != nil {\n\t\tcio.Set(cmd)\n\t}\n\n\tif cmd.Stdout == nil && cmd.Stderr == nil {\n\t\tout, _, err := cmdOutput(cmd, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %s\", err, out)\n\t\t}\n\t\treturn nil\n\t}\n\n\tec, err := Monitor.Start(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cio != nil {\n\t\tif c, ok := cio.(runc.StartCloser); ok {\n\t\t\tif err := c.CloseAfterStart(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tstatus, err := Monitor.Wait(cmd, ec)\n\tif err == nil && status != 0 {\n\t\terr = fmt.Errorf(\"%s did not terminate sucessfully\", cmd.Args[0])\n\t}\n\n\treturn err\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t// Your code here (2B).\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == LEADER\n\tif isLeader {\n\t\tindex = rf.getLastLogIndex() + 1\n\t\tDPrintf(\"=================== leader server %v start command: %v ====================\", rf.me, command)\n\t\trf.logs = append(rf.logs, LogEntry{Term: term, Command: command, Index: index})\n\t\trf.persist()\n\t}\n\treturn index, term, isLeader\n}", "func (c *CmdReal) Start() error {\n\treturn c.cmd.Start()\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := (rf.state == Leader)\n\n\t// Your code here (2B).\n\tif isLeader {\n\t\t//fmt.Printf(\"Leader %d: got a new Start task, command: %v\\n\", rf.me, command)\n\n\t\tindex = len(rf.log)\n\t\trf.log = append(rf.log, LogEntry{command, rf.currentTerm})\n\t\trf.persist()\n\t}\n\n\t//fmt.Printf(\"%d %d %v\\n\", index, term, isLeader)\n\n\treturn index, term, isLeader\n}", "func (j *JournalTailer) StartTail() error {\n\tvar err error\n\n\tj.mu.Lock()\n\tdefer j.mu.Unlock()\n\n\tglog.V(3).Infof(\"Starting command %s ...\", j.cmdLineStr)\n\tj.cmd = exec.Command(j.cmdLine[0], j.cmdLine[1:]...)\n\n\t// stdout logging\n\tj.stdoutPipe, err = j.cmd.StdoutPipe()\n\tif err != nil {\n\t\tglog.Errorf(\"Unexpected error during pipe: %v\", err)\n\t\treturn err\n\t}\n\tj.stdoutScanner = bufio.NewScanner(bufio.NewReader(j.stdoutPipe))\n\tgo j.display()\n\n\t// exec\n\terr = j.cmd.Start()\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot start the command %s: %v\", j.cmdLineStr, err)\n\t\treturn err\n\t}\n\n\tj.running = true\n\tglog.V(3).Infof(\"Command %s started as pid %d\", j.cmdLineStr, j.cmd.Process.Pid)\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tindex := -1\n\tterm := -1\n\tisLeader := rf.electionState == leader\n\n\tif isLeader {\n\t\tindex = len(rf.log)\n\t\tif index <= 0 {\n\t\t\tindex = 1\n\t\t}\n\t\tterm = rf.currentTerm\n\t\tnewEntry := LogEntry{\n\t\t\tCommand: command,\n\t\t\tTerm: term,\n\t\t}\n\t\trf.log = append(rf.log, newEntry)\n\t\trf.nextIndex[rf.me] = len(rf.log)\n\t\trf.persist()\n\t\trf.startLogConsensus(index, term)\n\t}\n\n\treturn index, term, isLeader\n}", "func (m *Master) Start(procSign string, out *StartRsp) error {\n\t// TODO\n\tfflags := NewFFlags(m.rootPath)\n\tcmd, err := m.StartInstance(procSign)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// when cmd is not nil, the process is starting for the first time\n\tif cmd != nil {\n\t\t// wait 3 secs to see if process still exists, if so\n\t\trunOK := waitForRunning(procSign, cmd)\n\t\tif runOK {\n\t\t\tfflags.SetForRunning(procSign, cmd.Process.Pid)\n\t\t\t*out = StartRsp{\n\t\t\t\tProcSign: procSign,\n\t\t\t\tPid: cmd.Process.Pid,\n\t\t\t\tHasRunning: false,\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"process: %s exits too quickly\", procSign)\n\t}\n\n\tf := NewFFlags(m.rootPath)\n\tpid := f.ReadPid(procSign)\n\t*out = StartRsp{\n\t\tProcSign: procSign,\n\t\tPid: pid,\n\t\tHasRunning: true,\n\t}\n\treturn nil\n}", "func (p *procBase) start(args ...string) error {\n\tif p.Running() {\n\t\treturn fmt.Errorf(\"Process %s is running\", p.Name())\n\t}\n\n\t// Always log to stderr, we'll capture and process logs.\n\targs = append(args, \"-logtostderr\", \"-v=1\")\n\n\tp.cmd = exec.Command(p.bin, args...)\n\tp.cmd.Stdout = NewLogDemuxer(p.name, p.loggers)\n\tp.cmd.Stderr = p.cmd.Stdout\n\treturn p.cmd.Start()\n}", "func (s *sshSessionExternal) Start(cmd string) error {\n\tif s.startCalled {\n\t\treturn errors.New(\"internal error: ssh external: command already running\")\n\t}\n\ts.startCalled = true\n\n\t// Adjust the args\n\tif strings.HasPrefix(cmd, requestSubsystem) {\n\t\ts.cmd.Args = append(s.cmd.Args, \"-s\", cmd[len(requestSubsystem):])\n\t\ts.runningSFTP = true\n\t} else {\n\t\ts.cmd.Args = append(s.cmd.Args, cmd)\n\t\ts.runningSFTP = false\n\t}\n\n\tfs.Debugf(s.f, \"ssh external: running: %v\", fs.SpaceSepList(s.cmd.Args))\n\n\t// start the process\n\terr := s.cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ssh external: start process: %w\", err)\n\t}\n\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tindex := 1\n\tll, exists := rf.lastLog()\n\tif exists {\n\t\tindex = ll.Index + 1\n\t}\n\n\tterm := rf.currentTerm\n\tisLeader := rf.currentRole == Leader\n\n\tif !isLeader {\n\t\trf.mu.Unlock()\n\t\treturn index, term, false\n\t}\n\tlogEntry := LogEntry{\n\t\tIndex: index,\n\t\tTerm: term,\n\t\tCommand: command,\n\t}\n\trf.Debug(dCommit, \"starting agreement for new log entry:%v\", logEntry)\n\trf.logs = append(rf.logs, logEntry)\n\trf.persist()\n\trf.mu.Unlock()\n\n\trf.sendEntries()\n\n\treturn index, term, true\n}", "func (runc RuncBinary) StartCommand(path, id string, detach bool, log string) *exec.Cmd {\n\targs := runc.addRootFlagIfNeeded(runc.addGlobalFlags([]string{\"start\"}, log))\n\tif detach {\n\t\targs = append(args, \"-d\")\n\t}\n\n\targs = append(args, id)\n\n\tcmd := exec.Command(runc.Path, args...)\n\tcmd.Dir = path\n\treturn cmd\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\t// server is not the leader, return false immediately\n\tif rf.state != Leader {\n\t\treturn -1, -1, false\n\t}\n\n\t// new index is set based on past snapshot and current log\n\tidx := 1\n\tif len(rf.log) == 0 {\n\t\tidx = rf.lastIncludedIndex + 1\n\t} else {\n\t\tidx = rf.log[len(rf.log)-1].Index + 1\n\t}\n\n\t// heartbeat routine will pick this up and send appropriate requests\n\tentry := LogEntry{\n\t\tIndex: idx,\n\t\tTerm: rf.currentTerm,\n\t\tCommand: command,\n\t}\n\trf.log = append(rf.log, entry)\n\trf.Log(LogDebug, \"Start called, current log:\", rf.log, \"\\n - rf.matchIndex: \", rf.matchIndex)\n\n\t// persist - we may have changed rf.log\n\tdata := rf.GetStateBytes(false)\n\trf.persister.SaveRaftState(data)\n\n\treturn entry.Index, entry.Term, true\n}", "func New(progressAction string, logger slog.Logger) *Logger {\n\treturn &Logger{\n\t\tlastLogTime: time.Now(),\n\t\tprogressAction: progressAction,\n\t\tsubsystemLogger: logger,\n\t}\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := len(rf.log)\n\tterm := rf.currentTerm\n\n\tisLeader := (rf.role == Leader)\n\tif isLeader {\n\t\t// fmt.Printf(\"APPEND : Leader %v append %v with %v\\n\", rf.me, command, term)\n\t\tlog := Log{term, command}\n\t\trf.log = append(rf.log, log)\n\t\trf.persist()\n\t}\n\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := 0\n\tisLeader := false //假定当前不是leader\n\tselect {\n\tcase <-rf.shutDown:\n\t\treturn index, term, isLeader\n\tdefault:\n\n\t}\n\n\t// Your code here (2B).\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\t// 判断当前节点是否是leader,如果是leader,从client中添加日志\n\tif rf.IsLeader {\n\t\tlog := LogEntry{\n\t\t\tTerm: rf.CurrentTerm,\n\t\t\tCommand: command,\n\t\t}\n\t\trf.Logs = append(rf.Logs, log)\n\t\tindex = len(rf.Logs) - 1\n\t\tterm = rf.CurrentTerm\n\t\tisLeader = true\n\t\trf.NextIndex[rf.me] = index + 1\n\t\trf.MatchIndex[rf.me] = index\n\t\t// client日志添加到leader成功,进行一致性检查\n\t\tgo rf.consistencyCheckDaemon()\n\t}\n\n\treturn index, term, isLeader\n}", "func Start(logDir string, driver db.DB) error {\n\te := echo.New()\n\te.SetDebug(viper.GetBool(\"debug\"))\n\n\t// Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\t// setup access logger\n\tlogPath := filepath.Join(logDir, \"access.log\")\n\tif _, err := os.Stat(logPath); os.IsNotExist(err) {\n\t\tif _, err := os.Create(logPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tf, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\te.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{\n\t\tOutput: f,\n\t}))\n\n\t// Routes\n\te.Get(\"/health\", health())\n\te.Get(\"/redhat/cves/:id\", getRedhatCve(driver))\n\te.Get(\"/debian/cves/:id\", getDebianCve(driver))\n\n\tbindURL := fmt.Sprintf(\"%s:%s\", viper.GetString(\"bind\"), viper.GetString(\"port\"))\n\tlog.Infof(\"Listening on %s\", bindURL)\n\n\te.Run(standard.New(bindURL))\n\treturn nil\n}", "func Start(logDir string, driver db.DB) error {\n\te := echo.New()\n\te.Debug = viper.GetBool(\"debug\")\n\n\t// Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\t// setup access logger\n\tlogPath := filepath.Join(logDir, \"access.log\")\n\tif _, err := os.Stat(logPath); os.IsNotExist(err) {\n\t\tif _, err := os.Create(logPath); err != nil {\n\t\t\tlog15.Error(\"Failed to create log dir\", logPath, err)\n\t\t}\n\t}\n\tf, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tlog15.Error(\"Failed to open log file\", logPath, err)\n\t}\n\tdefer f.Close()\n\te.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{\n\t\tOutput: f,\n\t}))\n\n\t// Routes\n\te.GET(\"/health\", health())\n\te.GET(\"/products\", getVendorProducts(driver))\n\te.GET(\"/cpes/:vendor/:product\", getCpesByVendorProduct(driver))\n\n\tbindURL := fmt.Sprintf(\"%s:%s\", viper.GetString(\"bind\"), viper.GetString(\"port\"))\n\tlog15.Info(\"Listening...\", \"URL\", bindURL)\n\treturn e.Start(bindURL)\n}", "func startSynchronous(command string, directory string, logger *zap.SugaredLogger) {\r\n\tresult := RunCommandSync(command, directory, logger)\r\n\r\n\tswitch result.Status {\r\n\r\n\tcase Failed:\r\n\t\tlogger.Errorf(\"[Failed] command %s \\n\", command)\r\n\r\n\tcase Success:\r\n\t\tlogger.Infof(\"[success] command %s finished in [%s] \\n\", command, result.Duration)\r\n\r\n\tcase Error:\r\n\t\tlogger.Errorf(\"[Error] command %s encountered errors \\n\", command)\r\n\r\n\t}\r\n\r\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state!=LEADER {\n\t\treturn 0,0,false\n\t}\n\trf.log = append(rf.log,LogEntry{Term:rf.currentTerm, Command:command})\n\trf.persist()\n\tindex = len(rf.log)-1\n\tterm = rf.log[index].Term\n\tisLeader = true\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tterm := -1\n\tisLeader := true\n\n\t// Your code here (2B).\n\tterm, isLeader = rf.GetState()\n\n\tif !isLeader {\n\t\treturn -1, term, isLeader\n\t}\n\n\trf.Lock()\n\tdefer rf.Unlock()\n\tnextIndex := func() int {\n\t\tif len(rf.log) > 0 {\n\t\t\treturn rf.log[len(rf.log)-1].Index + 1\n\t\t}\n\t\treturn Max(1, rf.lastSnapshotIndex+1)\n\t}()\n\n\tentry := LogEntry{Index: nextIndex, Term: rf.currentTerm, Command: command}\n\trf.log = append(rf.log, entry)\n\t//RaftInfo(\"New entry appended to leader's log: %s\", rf, entry)\n\n\treturn nextIndex, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\trf.lock()\n\tdefer rf.unlock()\n\n\tif rf.CurrentElectionState != Leader {\n\t\tad.DebugObj(rf, ad.TRACE, \"Rejecting Start(%+v) because I am not the leader\", command)\n\t\treturn 0, 0, false\n\t}\n\tad.DebugObj(rf, ad.TRACE, \"Received Start(%+v)\", command)\n\n\t// +1 because it will go after the current last entry\n\tentry := LogEntry{rf.CurrentTerm, command, rf.Log.length() + 1}\n\trf.Log.append(entry)\n\tif rf.CurrentElectionState == Leader {\n\t\trf.matchIndex[rf.me] = rf.Log.length()\n\t}\n\trf.writePersist()\n\n\tad.DebugObj(rf, ad.TRACE, \"Sending new Log message to peers\")\n\tfor peerNum, _ := range rf.peers {\n\t\tgo rf.sendAppendEntries(peerNum, true)\n\t}\n\n\tindex := rf.lastLogIndex()\n\tterm := rf.CurrentTerm\n\tisLeader := true\n\n\tad.DebugObj(rf, ad.RPC, \"returning (%d, %d, %t) from Start(%+v)\", index, term, isLeader, command)\n\tad.DebugObj(rf, ad.TRACE, \"Log=%+v\", rf.Log)\n\n\treturn index, term, isLeader\n}", "func (logger *Logger) Start(level int, writer io.Writer, fileName string) (err error) {\n\tlogger.level = level\n\tlogger.flags = log.Ldate | log.Ltime\n\tlogger.Logger = log.New(os.Stdout, logger.prefix, logger.flags)\n\tif len(fileName) > 0 {\n\t\tlogger.file, err = os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tlogger.Logger.Println(err)\n\t\t} else {\n\t\t\tlogger.Logger.SetOutput(logger.file)\n\t\t}\n\t} else if writer != nil {\n\t\tlogger.Logger.SetOutput(writer)\n\t}\n\treturn\n}", "func Start(debugMode bool) error {\n\tvar err error\n\n\t// since init has been done in cmd init\n\tconfigN := config.Get()\n\tlog := logger.Get()\n\n\t// fetch globalDir\n\tvar globalDir string\n\tif globalDir, err = configN.FindString(\"global.dir\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\n\t// make directory\n\tif err = os.MkdirAll(globalDir, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\t// init logFile & pidFile\n\tvar pidFile, logFile string\n\tif pidFile, err = configN.FindString(\"global.pidFile\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\tif logFile, err = configN.FindString(\"global.logFile\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\n\t// init context\n\tcntxt := &daemon.Context{\n\t\tPidFileName: pidFile,\n\t\tPidFilePerm: 0644,\n\t\tLogFileName: logFile,\n\t\tLogFilePerm: 0640,\n\t\tWorkDir: \"./\",\n\t\tUmask: 027,\n\t\tArgs: []string{},\n\t}\n\n\tvar p *os.Process\n\tp, err = cntxt.Reborn()\n\tif err != nil {\n\t\tlog.Debugf(\"[apm] daemon has started\")\n\t\treturn nil\n\t}\n\t// if fork process succeed, let the parent process\n\t// go and run the folllowing logic in the child process\n\tif p != nil {\n\t\treturn nil\n\t}\n\tdefer cntxt.Release()\n\n\t// CHILD PROCESS\n\treturn daemonHandler(debugMode)\n}", "func LaunchDockerLogger(logger hclog.Logger) (DockerLogger, *plugin.Client, error) {\n\tlogger = logger.Named(PluginName)\n\tbin, err := os.Executable()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient := plugin.NewClient(&plugin.ClientConfig{\n\t\tHandshakeConfig: base.Handshake,\n\t\tPlugins: map[string]plugin.Plugin{\n\t\t\tPluginName: &Plugin{impl: NewDockerLogger(logger)},\n\t\t},\n\t\tCmd: exec.Command(bin, PluginName),\n\t\tAllowedProtocols: []plugin.Protocol{\n\t\t\tplugin.ProtocolGRPC,\n\t\t},\n\t\tLogger: logger,\n\t})\n\n\trpcClient, err := client.Client()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\traw, err := rpcClient.Dispense(PluginName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tl := raw.(DockerLogger)\n\treturn l, client, nil\n\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := false\n\n\t// Your code here (2B).\n\trf.lock(\"Start\")\n\t// term, isLeader = rf.GetState()\n\tisLeader = rf.state == LEADER\n\tterm = rf.currentTerm\n\tif isLeader {\n\t\t// rf.lock(\"Start\")\n\t\tindex = len(rf.log)\n\t\trf.log = append(rf.log, LogEntry{LogTerm: term, Command: command})\n\n\t\trf.matchIndex[rf.me] = index\n\t\trf.nextIndex[rf.me] = index + 1\n\n\t\trf.persist()\n\t\t// rf.unlock(\"Start\")\n\t\tDPrintf(\"Leader[%v]提交Start日志,它的LogTerm是[%v]和LogCommand[%v]\\n\", rf.me,\n\t\t\tterm, command)\n\t}\n\trf.unlock(\"Start\")\n\treturn index, term, isLeader\n}", "func (m *DomainMonitor) Start() error {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tif m.closed {\n\t\treturn ErrClosed\n\t}\n\tif m.instance != nil {\n\t\treturn nil // Already running\n\t}\n\n\tclient, err := adsi.NewClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif m.domain == \"\" {\n\t\tm.domain, err = dnc(client)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif m.domain == \"\" {\n\t\t\treturn ErrDomainLookupFailed\n\t\t}\n\t}\n\n\tm.instance = poller.New(&domainSource{\n\t\tclient: client,\n\t\tdomain: m.domain,\n\t\tsink: &m.sink,\n\t\tbc: &m.bc,\n\t}, m.interval, m.timeout)\n\n\treturn nil\n}", "func (c *Cmd) StartWithTimeout(to time.Duration, exp *regexp.Regexp) error {\n\tc.startInNewGroup()\n\n\tvar err error\n\tvar opipe io.Reader\n\tif c.Stdout != nil {\n\t\tvar w io.Writer\n\t\topipe, w = io.Pipe()\n\n\t\tc.Stdout = io.MultiWriter(w, c.Stdout)\n\t} else {\n\t\topipe, err = c.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar epipe io.Reader\n\tif c.Stderr != nil {\n\t\tvar w io.Writer\n\t\tepipe, w = io.Pipe()\n\n\t\tc.Stderr = io.MultiWriter(w, c.Stderr)\n\t} else {\n\t\tepipe, err = c.StderrPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.Start()\n\n\treturn iowait.WaitForRegexp(io.MultiReader(epipe, opipe), exp, to)\n}", "func (ts *TaskService) Start(ctx context.Context, req *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {\n\tdefer logPanicAndDie(log.G(ctx))\n\n\tlog.G(ctx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"start\")\n\ttask, err := ts.taskManager.Task(req.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = namespaces.WithNamespace(ctx, defaultNamespace)\n\tresp, err := task.Start(ctx, req)\n\tif err != nil {\n\t\tlog.G(ctx).WithError(err).Error(\"start failed\")\n\t\treturn nil, err\n\t}\n\n\tlog.G(ctx).WithField(\"pid\", resp.Pid).Debug(\"start succeeded\")\n\treturn resp, nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\t// Your code here (2B).\n\trf.lock(\"Start\")\n\tdefer rf.unlock(\"Start\")\n\tisLeader = rf.state == Leader\n\tterm = rf.currentTerm\n\tif isLeader {\n\t\trf.logs = append(rf.logs, LogEntry{\n\t\t\tTerm: rf.currentTerm,\n\t\t\tIndex: rf.getAbsoluteLogIndex(len(rf.logs)),\n\t\t\tCommand: command,\n\t\t})\n\t\tindex = rf.getAbsoluteLogIndex(len(rf.logs) - 1)\n\t\trf.matchIndex[rf.me] = index\n\t\trf.nextIndex[rf.me] = index + 1\n\t\trf.persist()\n\t\tDPrintf(\"Server %v start an command to be appended to Raft's log, log's last term is %v, index is %v, log length is %v\",\n\t\t\trf.me, rf.logs[len(rf.logs) - 1].Term, rf.logs[len(rf.logs) - 1].Index, len(rf.logs))\n\t}\n\n\treturn index, term, isLeader\n}", "func attachLogger(cmd *exec.Cmd, pfx string, stream int) (*logger, error) {\n\tdir, base := filepath.Split(pfx)\n\tstreamName, ok := streamNames[stream]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid stream %v\", stream)\n\t}\n\tvar w io.Writer\n\tif stream == syscall.Stdout {\n\t\tw = cmd.Stdout\n\t} else if stream == syscall.Stderr {\n\t\tw = cmd.Stderr\n\t}\n\tfn := filepath.Join(dir, fmt.Sprintf(\"%v%v.%v.log\", base, cmd.Args[0], streamName))\n\tf, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not open %v\", fn)\n\t}\n\twriters := []io.Writer{f}\n\tif w != nil {\n\t\twriters = append(writers, w)\n\t}\n\tl := &logger{\n\t\tcmd: cmd,\n\t\tstartTime: time.Now(),\n\t\tf: f,\n\t\tWriter: io.MultiWriter(writers...),\n\t}\n\tl.intro()\n\tif stream == syscall.Stdout {\n\t\tcmd.Stdout = l\n\t} else if stream == syscall.Stderr {\n\t\tcmd.Stderr = l\n\t}\n\treturn l, nil\n}", "func (r *Reporter) Start(ctx context.Context) error {\n\tif r.Errors != nil {\n\t\tr.D.Debug(\"starting errors reporter\")\n\t\tif err := r.Errors.Start(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.D.Debug(\"errors reporter started\")\n\t}\n\n\tif r.Logging != nil {\n\t\tr.D.Debug(\"starting logging reporter\")\n\t\tif err := r.Logging.Start(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.D.Debug(\"logging reporter started\")\n\t}\n\n\tif r.Metrics != nil {\n\t\tr.D.Debug(\"starting metrics reporter\")\n\t\tif err := r.Metrics.Start(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.D.Debug(\"metrics reporter started\")\n\t}\n\n\treturn nil\n}", "func (s *ServiceHandler) startLogger(loggerDone chan error, stdout io.ReadCloser) {\n\ts.mutex.Lock()\n\ts.service.LogCmd = exec.Command(\"./../multilog/multilog\", \"-path\", \"/\"+s.service.Value)\n\n\t//@TODO rewrite multilog so that it can take stderr and stdout separately\n\tstdOutBuff := bufio.NewScanner(stdout)\n\tstdin, err := s.service.LogCmd.StdinPipe()\n\tif err != nil {\n\t\tLOGGER.Crit(fmt.Sprintf(\"Error while catching stdinpipe of %s, %s\", s.service.Value, err))\n\t\ts.mutex.Unlock()\n\t\treturn\n\t}\n\tdefer stdin.Close()\n\terr = s.service.LogCmd.Start()\n\tif err != nil {\n\t\tLOGGER.Crit(fmt.Sprintf(\"Error while starting logger %s\", err))\n\t\ts.mutex.Unlock()\n\t\treturn\n\t}\n\ts.mutex.Unlock()\n\n\tif len(s.service.LogBuffer) > 0 {\n\t\tLOGGER.Crit(fmt.Sprintf(\"found unhandled log lines for %s, writing those first\", s.service.Value))\n\t\tfor _, line := range s.service.LogBuffer {\n\t\t\terr := s.writeLine(stdin, line)\n\t\t\tif err != nil {\n\t\t\t\tLOGGER.Crit(fmt.Sprintf(\"Could not write buffered log for %s. error: %s\", s.service.Value, err))\n\t\t\t\tLOGGER.Crit(fmt.Sprintf(\"%s - %s\", s.service.Value, line))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ts.service.LogBuffer = nil\n\t}\n\n\tfor stdOutBuff.Scan() {\n\t\terr := s.writeLine(stdin, stdOutBuff.Text())\n\t\tif err != nil {\n\t\t\tLOGGER.Crit(fmt.Sprintf(\"IO gone away for %s, %s\", s.service.Value, s.service.LogCmd.Process))\n\t\t\ts.service.LogBuffer = append(s.service.LogBuffer, stdOutBuff.Text()+\"\\n\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\tloggerDone <- s.service.LogCmd.Wait()\n\n\tselect {\n\tcase <-loggerDone:\n\t\tLOGGER.Warning(fmt.Sprintf(\"logger %s done without errors\", s.service.Value))\n\t\tif len(s.service.LogBuffer) > 0 {\n\t\t\ts.startLogger(loggerDone, stdout)\n\t\t}\n\t\tbreak\n\tcase err := <-loggerDone:\n\t\tLOGGER.Warning(fmt.Sprintf(\"logger %s done with error = %v\\n\", s.service.Value, err))\n\t\ts.startLogger(loggerDone, stdout)\n\t\tbreak\n\t}\n}", "func Start(logger *zap.Logger, message string, fields ...zap.Field) Timer {\n\tif checkedEntry := logger.Check(zap.DebugLevel, message); checkedEntry != nil {\n\t\treturn newTimer(checkedEntry, fields...)\n\t}\n\treturn nopTimer{}\n}", "func Start(container string) error {\n\tcmd := exec.Command(\"docker\", \"start\", container)\n\treturn runWithLogging(cmd)\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tDPrintf(1, \"RaftServer[%d] received start[%+v], state: %v\\n\", rf.me, command, rf.state)\n\tif rf.killed() {\n\t\tDPrintf(1, \"RaftServer[%d] is killed.\\n\", rf.me)\n\t\treturn -1, -1, false\n\t}\n\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\tif rf.state != Leader {\n\t\treturn -1, -1, false\n\t}\n\n\trf.lastLogIndex++\n\tnewLog := Log{rf.CurrentTerm, command}\n\trf.appendLogEntry(newLog, rf.lastLogIndex)\n\trf.persist()\n\n\tindex := rf.lastLogIndex\n\tterm := rf.CurrentTerm\n\tisLeader := true\n\treturn index, term, isLeader\n}", "func (l *LogAdapter) Start() error {\n\treturn nil\n}", "func (s *Server) Start(name string, arg ...string) error {\n\ts.cmd = exec.Command(name, arg...)\n\ts.cmd.Stdout = os.Stdout\n\ts.cmd.Stderr = os.Stderr\n\ts.cmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\n\terr := s.cmd.Start()\n\n\t// TODO: check that the server is ready (read stdout?)\n\ttime.Sleep(1 * time.Second)\n\n\treturn err\n}", "func (container *ContainerLog) StartLogging() error {\n\tloggers, err := container.startLogger()\n\tif err != nil {\n\t\tif err == ErrNeglectedContainer {\n\t\t\tlogrus.Warnf(\"find a container %s that do not define kato logger.\", container.Name)\n\t\t\treturn ErrNeglectedContainer\n\t\t}\n\t\treturn fmt.Errorf(\"failed to initialize logging driver: %v\", err)\n\t}\n\tcopier := NewCopier(container.reader, loggers, container.since)\n\tcontainer.LogCopier = copier\n\tcopier.Run()\n\tcontainer.LogDriver = loggers\n\treturn nil\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\n\t//Check if I am the leader\n\t//if false --> return\n\t//If true -->\n\t// 1. Add to my log\n\t// 2. Send heart beat/Append entries to other peers\n\t//Check your own last log index and 1 to it.\n\t//Let other peers know that this is the log index for new entry.\n\n\t// we need to modify the heart beat mechanism such that it sends entries if any.\n\tindex := -1\n\tterm := -1\n\t//Otherwise prepare the log entry from the given command.\n\t// Your code here (2B).\n\t///////\n\tterm, isLeader :=rf.GetState()\n\tif isLeader == false {\n\t\treturn index,term,isLeader\n\t}\n\tterm = rf.currentTerm\n\tindex = rf.commitIndex\n\trf.sendAppendLogEntries(command)\n\treturn index, term, isLeader\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\t//rf.mu.Lock()\n\t//defer rf.mu.Unlock()\n\t//index := -1\n\t//term := rf.currentTerm\n\t//isLeader := (rf.state == leader)\n\t////If command received from client: append entry to local log, respond after entry applied to state machine (§5.3)\n\t//if isLeader {\n\t//\tindex = rf.getLastLogIndex() + 1\n\t//\tnewLog := LogEntry{\n\t//\t\tcommand,\n\t//\t\trf.currentTerm,\n\t//\t}\n\t//\trf.log = append(rf.log, newLog)\n\t//\trf.persist()\n\t////\trf.Leader(rf.me, rf.peers, rf.currentTerm)\n\t//}\n\t//return index, term, isLeader\n\n\t// Your code here (2B).\n\trf.mu.Lock()\n\tdefer rf.mu.Unlock()\n\n\tindex := -1\n\tterm := rf.currentTerm\n\tisLeader := rf.state == leader\n\n\tme := rf.me\n\tDPrintln(\"!!!!!!!\")\n\n\tif rf.state != leader || rf.killed() {\n\t\tDPrintln(\"server \", me, \"fail to receive the command\", command, \" because it is killed or not leader\")\n\t\treturn index, term, isLeader\n\t}\n\n\trf.log = append(rf.log, LogEntry{\n\t\tEntry: command,\n\t\tTerm: rf.currentTerm,\n\t})\n\trf.persist()\n\trf.Leader(rf.me, rf.peers, rf.currentTerm)\n\n\tindex = rf.getLastLogIndex()\n\n\tDPrintln(\"client send to leader \", me, \"command\", command, \"commandIndex\", index, \"term\", term)\n\treturn index, term, isLeader\n}", "func (c *Console) Start(group string) (err error) {\n\t_, err = fmt.Fprintf(c.conn, \"%v\\n\", toJSON([]string{\"start\", group}))\n\tif err == nil {\n\t\terr = <-c.Waiter\n\t}\n\treturn\n}" ]
[ "0.66363233", "0.5773775", "0.5744883", "0.5383558", "0.5373031", "0.5363997", "0.53256774", "0.5283025", "0.5241867", "0.5202267", "0.5201847", "0.5199594", "0.5198676", "0.51582026", "0.5126679", "0.50996524", "0.50755686", "0.507384", "0.5072129", "0.50489205", "0.5045449", "0.5025949", "0.50230116", "0.50089765", "0.50034356", "0.49558946", "0.4949202", "0.49453342", "0.4942696", "0.4938341", "0.49328825", "0.49314693", "0.49253225", "0.49196982", "0.4889441", "0.48857456", "0.48777822", "0.48754779", "0.48703933", "0.4864291", "0.48611167", "0.4848824", "0.48468772", "0.4846587", "0.48446658", "0.4840604", "0.48378703", "0.48299026", "0.48287868", "0.48275006", "0.48226973", "0.48138493", "0.48074415", "0.47906128", "0.47811848", "0.47758925", "0.47731733", "0.4764316", "0.4764212", "0.47568518", "0.47545052", "0.47526026", "0.47496772", "0.4743566", "0.47412294", "0.4740813", "0.47299677", "0.47263402", "0.47092712", "0.47009242", "0.4691874", "0.46918106", "0.46905404", "0.46653593", "0.4649613", "0.46481875", "0.4645228", "0.46401948", "0.46357942", "0.46241146", "0.46229565", "0.46196172", "0.46167144", "0.46158218", "0.4589244", "0.45856056", "0.45846725", "0.45793995", "0.45602772", "0.45588925", "0.45575106", "0.45522454", "0.45354742", "0.45339137", "0.45315933", "0.45159924", "0.4515639", "0.45085132", "0.4507969", "0.4507773" ]
0.69417846
0
Wait waits for the running command to terminate and returns the exit error from the command. If the command has already exited, the exit err will be returned immediately.
func (s *Session) Wait() error { <-s.exited return s.exitErr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *qemuCmd) Wait() (int, error) {\n\terr := c.cmd.Wait()\n\n\texitStatus := -1\n\topAPI := c.cmd.Get()\n\tif opAPI.Metadata != nil {\n\t\texitStatusRaw, ok := opAPI.Metadata[\"return\"].(float64)\n\t\tif ok {\n\t\t\texitStatus = int(exitStatusRaw)\n\n\t\t\t// Convert special exit statuses into errors.\n\t\t\tswitch exitStatus {\n\t\t\tcase 127:\n\t\t\t\terr = ErrExecCommandNotFound\n\t\t\tcase 126:\n\t\t\t\terr = ErrExecCommandNotExecutable\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn exitStatus, err\n\t}\n\n\t<-c.dataDone\n\n\tif c.cleanupFunc != nil {\n\t\tdefer c.cleanupFunc()\n\t}\n\n\treturn exitStatus, nil\n}", "func (cmd *Command) Wait() error {\n\t// According to https://github.com/golang/go/issues/28461,\n\t// exec.Cmd#Wait is not thread-safe, so we need to implement\n\t// our own version.\n\tcmd.waitOnce.Do(func() {\n\t\tcmd.waitResult = cmd.c.Wait()\n\t\tclose(cmd.waitDoneCh)\n\t})\n\treturn cmd.waitResult\n}", "func (c *Cmd) CmdWait() {\n\tc.Wg.Wait()\n\tc.ExitError = c.Cmd.Wait()\n\tc.GetExitCode()\n}", "func wait(s *suite.Suite, data *runData, expectedExitStatus int) {\n\terr := data.cmd.Wait()\n\tif expectedExitStatus == 0 {\n\t\ts.NoError(err)\n\t} else {\n\t\tstatus := err.(*exec.ExitError).ProcessState.Sys().(syscall.WaitStatus)\n\t\ts.Equal(expectedExitStatus, status.ExitStatus())\n\t}\n}", "func (s *sshSessionExternal) Wait() error {\n\tif s.exited() {\n\t\treturn nil\n\t}\n\terr := s.cmd.Wait()\n\tif err == nil {\n\t\tfs.Debugf(s.f, \"ssh external: command exited OK\")\n\t} else {\n\t\tfs.Debugf(s.f, \"ssh external: command exited with error: %v\", err)\n\t}\n\treturn err\n}", "func (c *Cmd) Wait() error {\n\treturn c.cmd.Wait()\n}", "func (c *Cmd) Wait() error {\n\treturn c.Cmd.Wait()\n}", "func (cli *DockerCli) CmdWait(args ...string) error {\n\tcmd := cli.Subcmd(\"wait\", \"CONTAINER [CONTAINER...]\", \"Block until a container stops, then print its exit code.\", true)\n\tcmd.Require(flag.Min, 1)\n\n\tutils.ParseFlags(cmd, args, true)\n\n\tvar encounteredError error\n\tfor _, name := range cmd.Args() {\n\t\tstatus, err := waitForExit(cli, name)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\tencounteredError = fmt.Errorf(\"Error: failed to wait one or more containers\")\n\t\t} else {\n\t\t\tfmt.Fprintf(cli.out, \"%d\\n\", status)\n\t\t}\n\t}\n\treturn encounteredError\n}", "func (s *SSHRunner) WaitCmd(sc *StartedCmd) (*RunResult, error) {\n\tif s.s == nil {\n\t\treturn nil, fmt.Errorf(\"there is no SSH command started\")\n\t}\n\n\trr := sc.rr\n\n\terr := s.s.Wait()\n\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\trr.ExitCode = exitError.ExitCode()\n\t}\n\n\tsc.wg.Wait()\n\n\tif err := s.s.Close(); err != io.EOF {\n\t\tklog.Errorf(\"session close: %v\", err)\n\t}\n\n\ts.s = nil\n\n\tif err == nil {\n\t\treturn rr, nil\n\t}\n\n\treturn rr, fmt.Errorf(\"%s: %v\\nstdout:\\n%s\\nstderr:\\n%s\", rr.Command(), err, rr.Stdout.String(), rr.Stderr.String())\n}", "func (e *dockerExec) Wait(ctx context.Context) error {\n\treturn e.WaitUntil(execComplete)\n}", "func (container *container) Wait() error {\r\n\terr := container.system.Wait()\r\n\tif err == nil {\r\n\t\terr = container.system.ExitError()\r\n\t}\r\n\treturn convertSystemError(err, container)\r\n}", "func (r *Runsc) Wait(context context.Context, id string) (int, error) {\n\tdata, stderr, err := cmdOutput(r.command(context, \"wait\", id), false)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"%w: %s\", err, stderr)\n\t}\n\tvar res waitResult\n\tif err := json.Unmarshal(data, &res); err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.ExitStatus, nil\n}", "func (e *Executor) Wait() { <-e.exit }", "func (p *process) Wait(ctx context.Context) error {\n\treturn WaitContext(ctx, p.cmd)\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func (p *process) Wait(ctx context.Context) error {\n\tselect {\n\tcase err, ok := <-p.waitC:\n\t\t// Process exited\n\t\tif ok {\n\t\t\treturn err\n\t\t}\n\t\treturn errWaitAlreadyCalled\n\tcase <-ctx.Done():\n\t\t// Timed out. Send a kill signal and release our handle to it.\n\t\treturn multierr.Combine(ctx.Err(), p.cmd.Process.Kill())\n\t}\n}", "func (a *ExternalAgentProcess) Wait() error {\n\treturn a.cmd.Wait()\n}", "func (c *Cmd) Wait(opts ...RunOption) error {\n\tif c.Process == nil {\n\t\treturn errNotStarted\n\t}\n\tif c.ProcessState != nil {\n\t\treturn errAlreadyWaited\n\t}\n\n\twerr := c.Cmd.Wait()\n\tcerr := c.ctx.Err()\n\n\tc.watchdogStop <- true\n\n\tif (werr != nil || cerr != nil) && hasOpt(DumpLogOnError, opts) {\n\t\t// Ignore the DumpLog intentionally, because the primary error\n\t\t// here is either werr or cerr. Note that, practically, the\n\t\t// error from DumpLog is returned when ProcessState is nil,\n\t\t// so it shouldn't happen here, because it should be assigned\n\t\t// in Wait() above.\n\t\tc.DumpLog(c.ctx)\n\t}\n\n\tif cerr != nil {\n\t\tc.timedOut = true\n\t\treturn cerr\n\t}\n\treturn werr\n}", "func WaitTimeout(c *exec.Cmd, timeout time.Duration) error {\n\ttimer := time.AfterFunc(timeout, func() {\n\t\terr := c.Process.Kill()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error killing process: %s\", err)\n\t\t\treturn\n\t\t}\n\t})\n\n\terr := c.Wait()\n\n\t// Shutdown all timers\n\ttermSent := !timer.Stop()\n\n\t// If the process exited without error treat it as success. This allows a\n\t// process to do a clean shutdown on signal.\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// If SIGTERM was sent then treat any process error as a timeout.\n\tif termSent {\n\t\treturn ErrTimeout\n\t}\n\n\t// Otherwise there was an error unrelated to termination.\n\treturn err\n}", "func (c *CmdReal) Wait() error {\n\treturn c.cmd.Wait()\n}", "func execAndWaitForStderr(wg *sync.WaitGroup, stderrMatch *regexp.Regexp, timeout time.Duration, name string, args ...string) (context.CancelFunc, <-chan error, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\terrChan := make(chan error, 1)\n\n\t// Set up the command and stderr pipe.\n\tcommand := exec.CommandContext(ctx, name, args...) // #nosec\n\tstderr, err := command.StderrPipe()\n\tif err != nil {\n\t\treturn cancel, errChan, errors.Wrap(err, \"creating stderr pipe\")\n\t}\n\n\t// Start the command in the background. This will only return error if the\n\t// command is not executable.\n\terr = command.Start()\n\tif err != nil {\n\t\treturn cancel, errChan, fmt.Errorf(\"starting command: %v\", err)\n\t}\n\n\t// Wait until we see the desired output or time out.\n\tfoundLine := make(chan bool, 1)\n\tscanner := bufio.NewScanner(stderr)\n\tvar log string\n\n\t// This goroutine watches the process stderr and sends true along the\n\t// foundLine channel if a line matches.\n\tgo func() {\n\t\tfor scanner.Scan() {\n\t\t\ttext := scanner.Text()\n\t\t\tlog += text + \"\\n\"\n\t\t\tif stderrMatch.MatchString(text) {\n\t\t\t\tfoundLine <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Block on either finding a matching line or timeout.\n\tselect {\n\tcase <-foundLine:\n\t\t// If we find the line, continue.\n\tcase <-time.After(timeout):\n\t\t// If it's a timeout we cancel the command ourselves.\n\t\tcancel()\n\t\t// We still need to wait for the command to finish.\n\t\tcommand.Wait() // nolint: errcheck\n\t\treturn cancel, errChan, fmt.Errorf(\"timeout, logs:\\n%s\\n\", log) // nolint: staticcheck, revive\n\t}\n\n\t// Increment the wait group so callers can wait for the command to finish.\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := command.Wait()\n\t\terrChan <- err\n\t}()\n\n\treturn cancel, errChan, nil\n}", "func (proc *Process) Wait() {\n\terr := proc.Cmd.Wait()\n\tif err != nil {\n\t\t// fmt.Printf(\"Process exit: %v\\n\", err)\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\tproc.ExitState = exitError.ProcessState\n\t\t}\n\t}\n\tproc.ExitState = proc.Cmd.ProcessState\n\tproc.EndTime = time.Now() // TODO make this goroutine-safe\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 (dbg *Debug) cmdWait(cs cmdStatus, to time.Duration) error {\n\t// wait for the command to complete\n\tt := time.Now().Add(to)\n\tfor t.After(time.Now()) {\n\t\t// is the command complete?\n\t\tif cs.isDone() {\n\t\t\t// check for command error\n\t\t\tce := cs.getError()\n\t\t\tif ce != errOk {\n\t\t\t\t// clear the error\n\t\t\t\terr := dbg.cmdErrorClr()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"error: %s(%d)\", ce, ce)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\t// wait a while\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\t// read the command status\n\t\tx, err := dbg.rdDmi(abstractcs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcs = cmdStatus(x)\n\t}\n\t// timeout\n\t// reset the hart\n\terr := dbg.ndmResetPulse()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// reset the debug module\n\terr = dbg.dmActivePulse()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn errors.New(\"command timeout\")\n}", "func (r *reaper) wait(pid int, proc waitProcess) (int, error) {\n\texitCodeCh, err := r.getExitCodeCh(pid)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\t// Wait for the subreaper to receive the SIGCHLD signal. Once it gets\n\t// it, this channel will be notified by receiving the exit code of the\n\t// corresponding process.\n\texitCode := <-exitCodeCh\n\n\t// Ignore errors since the process has already been reaped by the\n\t// subreaping loop. This call is only used to make sure libcontainer\n\t// properly cleans up its internal structures and pipes.\n\tproc.wait()\n\n\tr.deleteExitCodeCh(pid)\n\n\treturn exitCode, nil\n}", "func (w *CommandExecutedWaiter) Wait(ctx context.Context, params *GetCommandInvocationInput, maxWaitDur time.Duration, optFns ...func(*CommandExecutedWaiterOptions)) error {\n\t_, err := w.WaitForOutput(ctx, params, maxWaitDur, optFns...)\n\treturn err\n}", "func (muxer *Muxer) Wait() error {\n\tif muxer.cmd == nil {\n\t\treturn errors.New(\"ffmpeg dash: not started\")\n\t}\n\n\terr := muxer.cmd.Wait()\n\n\t// Ignore 255 status -- just indicates that we exited early\n\tif err != nil && err.Error() == \"exit status 255\" {\n\t\terr = nil\n\t}\n\n\treturn err\n}", "func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {\n\tcmd := rcli.Subcmd(stdout, \"wait\", \"[OPTIONS] NAME\", \"Block until a container stops, then print its exit code.\")\n\tif err := cmd.Parse(args); err != nil {\n\t\treturn nil\n\t}\n\tif cmd.NArg() < 1 {\n\t\tcmd.Usage()\n\t\treturn nil\n\t}\n\tfor _, name := range cmd.Args() {\n\t\tif container := srv.runtime.Get(name); container != nil {\n\t\t\tfmt.Fprintln(stdout, container.Wait())\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"No such container: %s\", name)\n\t\t}\n\t}\n\treturn nil\n}", "func (k *KubeletExecutor) Wait(containerID string) error {\n\treturn k.cli.WaitForTermination(containerID, 0)\n}", "func (g *errGroup) wait() error {\n\tg.wg.Wait()\n\tif g.cancel != nil {\n\t\tg.cancel()\n\t}\n\treturn g.err\n}", "func (d *dockerWaiter) wait(ctx context.Context, containerID string, stopFn func()) error {\n\tstatusCh, errCh := d.client.ContainerWait(ctx, containerID, container.WaitConditionNotRunning)\n\n\tif stopFn != nil {\n\t\tstopFn()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(time.Second):\n\t\t\tif stopFn != nil {\n\t\t\t\tstopFn()\n\t\t\t}\n\n\t\tcase err := <-errCh:\n\t\t\treturn err\n\n\t\tcase status := <-statusCh:\n\t\t\tif status.StatusCode != 0 {\n\t\t\t\treturn &common.BuildError{\n\t\t\t\t\tInner: fmt.Errorf(\"exit code %d\", status.StatusCode),\n\t\t\t\t\tExitCode: int(status.StatusCode),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *Cmd) Wait(timeout time.Duration) error {\n\tc.once.Do(func() {\n\t\tc.waitCh = make(chan error)\n\t\tgo func() {\n\t\t\tc.waitCh <- c.wait()\n\t\t\tclose(c.waitCh)\n\t\t}()\n\t})\n\n\tselect {\n\tcase <-time.After(timeout):\n\t\treturn ErrTimeout\n\tcase err := <-c.waitCh:\n\t\treturn err\n\t}\n}", "func (m *Machine) Wait(ctx context.Context) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-m.exitCh:\n\t\treturn m.fatalErr\n\t}\n}", "func (c *Client) Wait(containerId, execId string, noHang bool) (int32, error) {\n\tctx, cancel := getContextWithTimeout(hyperContextTimeout)\n\tdefer cancel()\n\n\treq := types.WaitRequest{\n\t\tContainer: containerId,\n\t\tProcessId: execId,\n\t\tNoHang: noHang,\n\t}\n\n\tresp, err := c.client.Wait(ctx, &req)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn resp.ExitCode, nil\n}", "func (c *Config) Wait(cErr chan error) error {\n\t// Exec should not return until the process is actually running\n\tselect {\n\tcase <-c.waitStart:\n\tcase err := <-cErr:\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *DockerSuite) TestWaitBlockedExitRandom(c *check.C) {\n\t// Cannot run on Windows as trap in Windows busybox does not support trap in this way.\n\ttestRequires(c, DaemonIsLinux)\n\tout, _ := dockerCmd(c, \"run\", \"-d\", \"busybox\", \"/bin/sh\", \"-c\", \"trap 'exit 99' TERM; while true; do usleep 10; done\")\n\tcontainerID := strings.TrimSpace(out)\n\tc.Assert(waitRun(containerID), checker.IsNil)\n\n\tchWait := make(chan error)\n\twaitCmd := exec.Command(dockerBinary, \"wait\", containerID)\n\twaitCmdOut := bytes.NewBuffer(nil)\n\twaitCmd.Stdout = waitCmdOut\n\tc.Assert(waitCmd.Start(), checker.IsNil)\n\tgo func() {\n\t\tchWait <- waitCmd.Wait()\n\t}()\n\n\tdockerCmd(c, \"stop\", containerID)\n\n\tselect {\n\tcase err := <-chWait:\n\t\tc.Assert(err, checker.IsNil, check.Commentf(waitCmdOut.String()))\n\t\tstatus, err := waitCmdOut.ReadString('\\n')\n\t\tc.Assert(err, checker.IsNil)\n\t\tc.Assert(strings.TrimSpace(status), checker.Equals, \"99\", check.Commentf(\"expected exit 99, got %s\", status))\n\tcase <-time.After(2 * time.Second):\n\t\twaitCmd.Process.Kill()\n\t\tc.Fatal(\"timeout waiting for `docker wait` to exit\")\n\t}\n}", "func WaitForCmdOut(program string, args []string, timeout int, errOnFail bool, check func(output string) bool) bool {\n\tpingTimeout := time.After(time.Duration(timeout) * time.Minute)\n\ttick := time.Tick(time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-pingTimeout:\n\t\t\tFail(fmt.Sprintf(\"Timeout out after %v minutes\", timeout))\n\n\t\tcase <-tick:\n\t\t\tstdOut, err := exec.Command(program, args...).Output()\n\t\t\tif err != nil && errOnFail {\n\t\t\t\tfmt.Fprintf(GinkgoWriter, \"Command (%s) output: %s\\n\", args, stdOut)\n\t\t\t\tFail(err.Error())\n\t\t\t}\n\t\t\tif check(strings.TrimSpace(string(stdOut))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *BoatHandle) Wait() (*os.ProcessState, error) { return b.cmd.Process.Wait() }", "func Wait(exitChannel chan error, cancel context.CancelFunc) error {\n\terr := <-exitChannel\n\t// cancel the context\n\tcancel()\n\treturn err\n}", "func (g *ErrGroup) Wait() error {\n\tg.wg.Wait()\n\tg.cancel()\n\treturn g.err\n}", "func WaitStatusExit(status int32) WaitStatus {\n\treturn WaitStatus(uint32(status) << 8)\n}", "func (bl *BuildLog) Wait() error {\n\tvar errors []error\n\tfor err := range bl.errCh {\n\t\terrors = append(errors, err)\n\t}\n\tif len(errors) > 0 {\n\t\treturn errors[0]\n\t}\n\treturn nil\n}", "func (r *reaper) wait(exitCodeCh <-chan int, proc waitProcess) (int, error) {\n\t// Wait for the subreaper to receive the SIGCHLD signal. Once it gets\n\t// it, this channel will be notified by receiving the exit code of the\n\t// corresponding process.\n\texitCode := <-exitCodeCh\n\n\t// Ignore errors since the process has already been reaped by the\n\t// subreaping loop. This call is only used to make sure libcontainer\n\t// properly cleans up its internal structures and pipes.\n\tproc.wait()\n\n\treturn exitCode, nil\n}", "func (m *mware) Wait() error {\n\treturn m.cmd.Wait()\n}", "func (w *InstanceTerminatedWaiter) Wait(ctx context.Context, params *DescribeInstancesInput, maxWaitDur time.Duration, optFns ...func(*InstanceTerminatedWaiterOptions)) error {\n\t_, err := w.WaitForOutput(ctx, params, maxWaitDur, optFns...)\n\treturn err\n}", "func GetWaitStatus(err error) (status syscall.WaitStatus, ok bool) {\n\tif err == nil {\n\t\treturn 0, true\n\t}\n\terrExit, ok := err.(*exec.ExitError)\n\tif !ok {\n\t\treturn 0, false\n\t}\n\tstatus, ok = errExit.Sys().(syscall.WaitStatus)\n\treturn status, ok\n}", "func (wt *Wait) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcommands.ExitStatus {\n\tif f.NArg() != 1 {\n\t\tf.Usage()\n\t\treturn subcommands.ExitUsageError\n\t}\n\t// You can't specify both -pid and -rootpid.\n\tif wt.rootPID != unsetPID && wt.pid != unsetPID {\n\t\tutil.Fatalf(\"only one of -pid and -rootPid can be set\")\n\t}\n\n\tid := f.Arg(0)\n\tconf := args[0].(*config.Config)\n\n\tc, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n\tif err != nil {\n\t\tutil.Fatalf(\"loading container: %v\", err)\n\t}\n\n\tvar waitStatus unix.WaitStatus\n\tswitch {\n\t// Wait on the whole container.\n\tcase wt.rootPID == unsetPID && wt.pid == unsetPID:\n\t\tws, err := c.Wait()\n\t\tif err != nil {\n\t\t\tutil.Fatalf(\"waiting on container %q: %v\", c.ID, err)\n\t\t}\n\t\twaitStatus = ws\n\t// Wait on a PID in the root PID namespace.\n\tcase wt.rootPID != unsetPID:\n\t\tws, err := c.WaitRootPID(int32(wt.rootPID))\n\t\tif err != nil {\n\t\t\tutil.Fatalf(\"waiting on PID in root PID namespace %d in container %q: %v\", wt.rootPID, c.ID, err)\n\t\t}\n\t\twaitStatus = ws\n\t// Wait on a PID in the container's PID namespace.\n\tcase wt.pid != unsetPID:\n\t\tws, err := c.WaitPID(int32(wt.pid))\n\t\tif err != nil {\n\t\t\tutil.Fatalf(\"waiting on PID %d in container %q: %v\", wt.pid, c.ID, err)\n\t\t}\n\t\twaitStatus = ws\n\t}\n\tresult := waitResult{\n\t\tID: id,\n\t\tExitStatus: exitStatus(waitStatus),\n\t}\n\t// Write json-encoded wait result directly to stdout.\n\tif err := json.NewEncoder(os.Stdout).Encode(result); err != nil {\n\t\tutil.Fatalf(\"marshaling wait result: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}", "func ProcessWait(p *os.Process,) (*os.ProcessState, error)", "func (g *ErrGroup) Wait() *Errors {\n\t_ = g.Group.Wait()\n\treturn &g.err\n}", "func execWaitFor(call string, args []string, waitFor []string, waitTime int) (string, error) {\n\n\tctx, _ := context.WithTimeout(context.Background(), time.Duration(waitTime)*time.Second)\n\n\tcmd := exec.CommandContext(ctx, call, args...)\n\taddSysProgAttrs(cmd)\n\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"LC_MESSAGES=%s\", locale))\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdone := make(chan bool)\n\tvar doneErr error = nil\n\tvar doneLine string = \"\"\n\n\t// react to call timeout\n\tgo func() {\n\t\tfor {\n\t\t\t<-ctx.Done()\n\t\t\tdoneErr = errors.New(\"timeout reached\")\n\t\t\tdone <- true\n\t\t\treturn\n\t\t}\n\t}()\n\n\t// react to new lines from standard output\n\tgo func() {\n\t\tif err := cmd.Start(); err != nil {\n\t\t\tdoneErr = err\n\t\t\tdone <- true\n\t\t\treturn\n\t\t}\n\n\t\tlog := []string{}\n\t\tbuf := bufio.NewReader(stdout)\n\t\tfor {\n\t\t\tline, _, err := buf.ReadLine()\n\t\t\tif err != nil {\n\t\t\t\tdoneErr = err\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog = append(log, string(line))\n\n\t\t\t// success if expected lines turned up\n\t\t\tfor _, waitLine := range waitFor {\n\n\t\t\t\tif strings.Contains(string(line), waitLine) {\n\n\t\t\t\t\tdoneLine = waitLine\n\t\t\t\t\tdone <- true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(log) == 0 {\n\t\t\t// nothing turned up\n\t\t\tdoneErr = errors.New(\"output is empty\")\n\t\t\tdone <- true\n\t\t\treturn\n\t\t}\n\n\t\t// expected lines did not turn up\n\t\tdoneErr = fmt.Errorf(\"unexpected output, got: %s\", strings.Join(log, \",\"))\n\t\tdone <- true\n\t}()\n\n\t<-done\n\treturn doneLine, doneErr\n}", "func (c *Container) Wait() (int32, error) {\n\terr := wait.PollImmediateInfinite(1,\n\t\tfunc() (bool, error) {\n\t\t\tstopped, err := c.isStopped()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif !stopped {\n\t\t\t\treturn false, nil\n\t\t\t} else { // nolint\n\t\t\t\treturn true, nil // nolint\n\t\t\t} // nolint\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\texitCode := c.state.ExitCode\n\treturn exitCode, nil\n}", "func (p *process) Wait() {\n\tif p.cmdDoneCh != nil {\n\t\t<-p.cmdDoneCh\n\t}\n}", "func (wg *ErrorWaitGroup) Wait() (err error) {\n\tn := cap(wg.ch)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tfor {\n\t\tif resErr := <-wg.ch; resErr != nil && err == nil {\n\t\t\terr = resErr\n\t\t}\n\t\tif n--; n == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\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 (s *DockerSuite) TestWaitNonBlockedExitRandom(c *check.C) {\n\tout, _ := dockerCmd(c, \"run\", \"-d\", \"busybox\", \"sh\", \"-c\", \"exit 99\")\n\tcontainerID := strings.TrimSpace(out)\n\n\terr := waitInspect(containerID, \"{{.State.Running}}\", \"false\", 30*time.Second)\n\tc.Assert(err, checker.IsNil) //Container should have stopped by now\n\tout, _ = dockerCmd(c, \"wait\", containerID)\n\tc.Assert(strings.TrimSpace(out), checker.Equals, \"99\", check.Commentf(\"failed to set up container, %v\", out))\n\n}", "func WaitContext(ctx context.Context, cmd *exec.Cmd) error {\n\t// We use cmd.Process.Wait instead of cmd.Wait because cmd.Wait is not reenterable\n\tc := make(chan error, 1)\n\tgo func() {\n\t\tif cmd == nil || cmd.Process == nil {\n\t\t\tc <- nil\n\t\t} else {\n\t\t\t_, err := cmd.Process.Wait()\n\t\t\tc <- err\n\t\t}\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ErrorWaitTimeout\n\tcase err := <-c:\n\t\treturn err\n\t}\n}", "func (ret *OpRet) Wait() error {\n\tif ret.delayed == nil {\n\t\treturn nil\n\t}\n\n\t<-ret.delayed\n\treturn ret.error\n}", "func (g *Group) Wait() error {\n\t<-g.done\n\n\tg.errM.RLock()\n\tdefer g.errM.RUnlock()\n\n\treturn g.err\n}", "func (s *Server) Wait() { <-s.exited; s.BaseService.Wait() }", "func (r *Runner) Wait(t *time.Timer, signals []os.Signal) bool {\n\tif !r.Started() {\n\t\treturn true\n\t}\n\tfor _, sig := range signals {\n\t\tselect {\n\t\tcase err, ok := <-r.errCh:\n\t\t\tif ok {\n\t\t\t\tr.setError(err, ifNotSet)\n\t\t\t}\n\t\t\treturn true\n\t\tcase <-t.C:\n\t\t\tr.setError(timeoutErr, ifNotSet)\n\t\t\tr.Cmd.Process.Signal(sig)\n\t\t\tt.Reset(r.Killout)\n\t\t}\n\t}\n\tr.setError(fmt.Errorf(\"unkillable child: %v\", r.Cmd.Process))\n\treturn false\n}", "func (c *DockerContainer) WaitUntilFinished() error {\n\tstatusCh, errCh := c.DockerClient.ContainerWait(c.Ctx, c.ID, container.WaitConditionNotRunning)\n\tlog.Debugf(\"waiting until command is finished...\")\n\tselect {\n\tcase err := <-errCh:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase retCode := <-statusCh:\n\t\tif retCode.StatusCode != 0 {\n\t\t\tlogsCmd := fmt.Sprintf(\"docker logs %s\", c.ID)\n\t\t\treturn ErrRunContainerCommand{Cmd: logsCmd}\n\t\t}\n\t}\n\treturn nil\n}", "func (res *errResult) Wait() error {\n\tif res == nil {\n\t\treturn nil\n\t}\n\tif res.listen != nil {\n\t\tres.err = <-res.listen\n\t\tres.listen = nil\n\t}\n\treturn res.err\n}", "func (j *JournalTailer) Wait() error {\n\terr := j.cmd.Wait()\n\tif err == nil {\n\t\tglog.V(2).Infof(\"Journal tailing of %s stopped, get them again with: %s\", j.GetUnitName(), j.GetCommandLine())\n\t\treturn nil\n\t}\n\tglog.Errorf(\"Journal tailing of %s stopped with unexpected error: %s\", j.GetUnitName(), err)\n\treturn err\n}", "func (wg *WaitGroup) Wait() error {\n\twg.wg.Wait()\n\treturn wg.err\n}", "func waitRun(contID string) error {\n\treturn daemon.WaitInspectWithArgs(dockerBinary, contID, \"{{.State.Running}}\", \"true\", 5*time.Second)\n}", "func executeCommandTimeout(cmd *exec.Cmd, timeSecs int, exitFile string, osSignal chan os.Signal) int {\n\tif DEBUG {\n\t\tlog.Printf(\"Debug: executeCommandTimeout\\n\")\n\t}\n\n\t// Wait for execution to finish or timeout\n\texitStr := \"\"\n\tif timeSecs <= 0 {\n\t\ttimeSecs = 31536000 // Default: One year\n\t}\n\n\t// Create a timeout process\n\t// References: http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html\n\texitCode := make(chan string, 1)\n\tgo execute(cmd, exitCode)\n\n\t// Wait until executions ends, timeout or OS signal\n\tkill := false\n\trun := true\n\tfor run {\n\t\tselect {\n\t\tcase exitStr = <-exitCode:\n\t\t\tkill = false\n\t\t\trun = false\n\n\t\tcase <-time.After(time.Duration(timeSecs) * time.Second):\n\t\t\trun = false\n\t\t\tkill = true\n\t\t\texitStr = \"Time out\"\n\t\t\tif DEBUG {\n\t\t\t\tlog.Printf(\"Debug: Timeout!\\n\")\n\t\t\t}\n\n\t\tcase sig := <-osSignal:\n\t\t\t// Ignore some signals (e.g. \"window changed\")\n\t\t\tsigStr := sig.String()\n\t\t\tif sigStr != \"window changed\" && sigStr != \"child exited\" {\n\t\t\t\tif VERBOSE || DEBUG {\n\t\t\t\t\tlog.Printf(\"bds: Received OS signal '%s'\\n\", sigStr)\n\t\t\t\t}\n\n\t\t\t\tkill = true\n\t\t\t\texitStr = \"Signal received\"\n\t\t\t\trun = false\n\t\t\t}\n\t\t}\n\t}\n\n\t// Should we kill child process?\n\tif kill {\n\t\tcmd.Process.Kill()\n\t\tcmd.Process.Wait() // Reap their souls\n\t}\n\n\t// Write exitCode to file or show as log message\n\tif (exitFile != \"\") && (exitFile != \"-\") {\n\t\twriteFile(exitFile, exitStr) // Dump error to 'exitFile'\n\t}\n\n\tif kill {\n\t\t// Should we kill all process groups from taskLoggerFile?\n\t\tif taskLoggerFile != \"\" {\n\t\t\ttaskLoggerCleanUpAll(taskLoggerFile)\n\t\t}\n\n\t\t// Send a SIGKILL to the process group (just in case any child process is still executing)\n\t\tsyscall.Kill(0, syscall.SIGHUP) // Other options: -syscall.Getpgrp() , syscall.SIGKILL\n\t}\n\n\t// OK? exit value should be zero\n\tif exitStr == \"0\" {\n\t\treturn EXITCODE_OK\n\t}\n\n\t// Timeout?\n\tif exitStr == \"Time out\" {\n\t\treturn EXITCODE_TIMEOUT\n\t}\n\n\treturn EXITCODE_ERROR\n}", "func runCommand(cmd *exec.Cmd, ch chan<- error) {\n\tch <- cmd.Wait()\n}", "func (p Process) Wait() (*os.ProcessState, error) {\n\tif p.ops == nil {\n\t\treturn nil, errInvalidProcess\n\t}\n\treturn p.ops.wait()\n}", "func (n *Node) Wait() (int, error) {\n\tctx := context.TODO()\n\n\tclient, err := client.NewEnvClient()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn client.ContainerWait(ctx, n.id)\n}", "func wait() os.Signal {\n\tsigC := make(chan os.Signal, 1)\n\tsignal.Notify(\n\t\tsigC,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGQUIT)\n\tsignal := <-sigC\n\treturn signal\n}", "func (c *Container) Wait() error {\n\tif c.id == \"\" {\n\t\treturn fmt.Errorf(\"container %s absent\", c.id)\n\t}\n\t_, err := c.cli.ContainerWait(c.ctx, c.id)\n\treturn err\n}", "func (res *stateResult) Wait() error {\n\tif res == nil {\n\t\treturn nil\n\t}\n\tif res.listen != nil {\n\t\tswitch state := <-res.listen; {\n\t\tcase state.State == res.expected:\n\t\tcase state.Err != nil:\n\t\t\tres.err = state.Err\n\t\tdefault:\n\t\t\tcode := 50001\n\t\t\tif state.Type == StateConn {\n\t\t\t\tcode = 50002\n\t\t\t}\n\t\t\tres.err = &Error{\n\t\t\t\tCode: code,\n\t\t\t\tErr: fmt.Errorf(\"failed %s state: %s\", state.Type, state.State),\n\t\t\t}\n\t\t}\n\t\tres.listen = nil\n\t}\n\treturn res.err\n}", "func (p *Pipeline) Wait() error {\n\tp.Stop()\n\tp.wait.Wait()\n\treturn p.err\n}", "func (g *Group) WaitErr() error {\n\tg.wg.Wait()\n\tif g.cancel != nil {\n\t\tg.cancel()\n\t}\n\tif g.firstErr >= 0 && len(g.errs) > int(g.firstErr) {\n\t\t// len(g.errs) > int(g.firstErr) is for then used uninitialized.\n\t\treturn g.errs[g.firstErr]\n\t}\n\treturn nil\n}", "func (s *Servers) Wait() error {\n\tlog.Debug(\"Waiting\")\n\terr := <-s.errors\n\ts.Close()\n\treturn err\n}", "func exitStatus(err error) (int, error) {\n\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\treturn status.ExitStatus(), nil\n\t\t}\n\t}\n\treturn 0, err\n}", "func (m *MemCmd) Wait() error {\n\tif m.WaitCallback != nil {\n\t\treturn m.WaitCallback(m)\n\t}\n\treturn nil\n}", "func execute(cmd *exec.Cmd, exitCode chan string) {\n\tif DEBUG {\n\t\tlog.Printf(\"Debug: execute\\n\")\n\t}\n\n\t// Wait for command to finish\n\tif err := cmd.Wait(); err != nil {\n\t\texitCode <- err.Error()\n\t} \n\n\texitCode <- \"0\"\n}", "func (ep *ExpectProcess) Wait() {\n\tep.wg.Wait()\n}", "func (bw *BinaryWaiter) Wait() error {\n\terr := bw.cmd.Wait()\n\t<-bw.logsWritten\n\treturn err\n}", "func WaitForExit(matcher Matcher, wait time.Duration, delay time.Duration, log Log) ([]ps.Process, error) {\n\tbreakFn := func(procs []ps.Process) bool {\n\t\treturn len(procs) == 0\n\t}\n\treturn findProcesses(matcher, breakFn, wait, delay, log)\n}", "func (g *Group) Wait() error {\n\tg.wg.Wait()\n\treturn g.err\n}", "func (e *DockerEngine) wait(ctx context.Context, id string) (*compiler.State, error) {\n\t_, errc := e.client.ContainerWait(ctx, id)\n\tif errc != nil {\n\t\treturn nil, errc\n\t}\n\n\tinfo, err := e.client.ContainerInspect(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif info.State.Running {\n\t\t// TODO(bradrydewski) if the state is still running\n\t\t// we should call wait again.\n\t}\n\n\treturn &compiler.State{\n\t\tExited: true,\n\t\tExitCode: info.State.ExitCode,\n\t\tOOMKilled: info.State.OOMKilled,\n\t}, nil\n}", "func (i *InvokeMotorStop) Wait() error {\n\treturn i.Result(nil)\n}", "func (kw *osKillWait) KillAndWait(command Commander, waitCh chan error) error {\n\tprocess := command.Process()\n\tif process == nil {\n\t\treturn ErrProcessNotStarted\n\t}\n\n\tlog := kw.logger.WithFields(logrus.Fields{\n\t\t\"PID\": process.Pid,\n\t})\n\n\tprocessKiller := newProcessKiller(log, command)\n\tprocessKiller.Terminate()\n\n\tselect {\n\tcase err := <-waitCh:\n\t\treturn err\n\tcase <-time.After(kw.gracefulKillTimeout):\n\t\tprocessKiller.ForceKill()\n\n\t\tselect {\n\t\tcase err := <-waitCh:\n\t\t\treturn err\n\t\tcase <-time.After(kw.forceKillTimeout):\n\t\t\treturn &KillProcessError{pid: process.Pid}\n\t\t}\n\t}\n}", "func (s *BasevhdlListener) ExitWait_statement(ctx *Wait_statementContext) {}", "func runCmd(cmd *exec.Cmd) error {\n\tcmd.Start()\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- cmd.Wait()\n\t}()\n\tselect {\n\tcase <-time.After(1 * time.Second):\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\tfmt.Println(\"failed to kill: \" + err.Error())\n\t\t}\n\t\t<-done // allow goroutine to exit\n\t\tfmt.Println(\"process killed - had to timeout\")\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (y *Yaraus) wait(id uint) *Error {\n\tif !y.useWait {\n\t\treturn nil\n\t}\n\n\t// get slaves count\n\tsc, err := slaveCount(y.c)\n\tif err != nil {\n\t\treturn &Error{\n\t\t\tErr: err,\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\tif sc == 0 {\n\t\treturn nil\n\t}\n\n\t// wait for redis slaves.\n\ti, err := y.c.Wait(sc/2+1, y.Interval).Result()\n\tif err != nil {\n\t\treturn &Error{\n\t\t\tErr: err,\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\tif int(i) < sc/2+1 {\n\t\treturn &Error{\n\t\t\tErr: fmt.Errorf(\"failed to sync, got %d, want %d\", int(i), sc/2+1),\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *CLI) WaitForCmdResult(\n\tt testing.TB,\n\tcommand icmd.Cmd,\n\tpredicate func(*icmd.Result) bool,\n\ttimeout time.Duration,\n\tdelay time.Duration,\n) {\n\tt.Helper()\n\tassert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), \"timeout must be greater than delay\")\n\tvar res *icmd.Result\n\tcheckStopped := func(logt poll.LogT) poll.Result {\n\t\tfmt.Printf(\"\\t[%s] %s\\n\", t.Name(), strings.Join(command.Command, \" \"))\n\t\tres = icmd.RunCmd(command)\n\t\tif !predicate(res) {\n\t\t\treturn poll.Continue(\"Cmd output did not match requirement: %q\", res.Combined())\n\t\t}\n\t\treturn poll.Success()\n\t}\n\tpoll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))\n}", "func Test_CmdRun_And_Reaper_PoC_Code(t *testing.T) {\n\tt.SkipNow()\n\tlog.SetLevel(log.DebugLevel)\n\n\tconfig := Config{\n\t\tPid: -1,\n\t\tDisablePid1Check: true,\n\t}\n\tgo Start(config)\n\n\tvar exitCode int\n\tdefaultFailedCode := 1\n\n\tname := \"/bin/bash\"\n\t//name := \"/bin/bashk\" // err будет PathError\n\targs := []string{\n\t\t\"-c\",\n\t\t\"ls -la; /bin/bash -c 'sleep 0.2; exit 1'; exit 2\",\n\t\t// \"ls -la; sleep 1; exit 2\", // no waitid error\n\t}\n\tlog.Infof(\"run command: %s %+v\", name, args)\n\tvar outbuf, errbuf bytes.Buffer\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdout = &outbuf\n\tcmd.Stderr = &errbuf\n\n\t//err := cmd.Run()\n\n\terr := func(c *exec.Cmd) error {\n\t\t// с блоком всё работает, получаем exitCode 2\n\t\t// executor.ExecutorLock.Lock()\n\t\t// defer executor.ExecutorLock.Unlock()\n\t\tif err := c.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t\tlog.Debug(\"start wait\")\n\t\treturn c.Wait()\n\t}(cmd)\n\n\tstdout := outbuf.String()\n\tstderr := errbuf.String()\n\n\techild := false\n\n\tif err != nil {\n\t\t// try to get the exit code\n\t\tif errv, ok := err.(*os.SyscallError); ok {\n\t\t\tif sysErr, ok := errv.Err.(syscall.Errno); ok {\n\t\t\t\tif sysErr == syscall.ECHILD {\n\t\t\t\t\techild = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Debugf(\"SyscallError %+v\", errv)\n\t\t}\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\tws := exitError.Sys().(syscall.WaitStatus)\n\t\t\texitCode = ws.ExitStatus()\n\t\t} else {\n\t\t\t// This will happen (in OSX) if `name` is not available in $PATH,\n\t\t\t// in this situation, exit code could not be get, and stderr will be\n\t\t\t// empty string very likely, so we use the default fail code, and format err\n\t\t\t// to string and set to stderr\n\t\t\tlog.Debugf(\"Could not get exit code for failed program: %v, %+v\", name, args)\n\t\t\texitCode = defaultFailedCode\n\t\t\tif stderr == \"\" {\n\t\t\t\tstderr = err.Error()\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// success, exitCode should be 0 if go is ok\n\t\tws := cmd.ProcessState.Sys().(syscall.WaitStatus)\n\t\texitCode = ws.ExitStatus()\n\t}\n\tlog.Debugf(\"command result, stdout: %v, stderr: %v, exitCode: %v, echild: %v\", stdout, stderr, exitCode, echild)\n}", "func (wait *WaitCommand) runWait(args []string) error {\n\tctx := context.Background()\n\tapiClient := wait.cli.Client()\n\n\tvar errs []string\n\tfor _, name := range args {\n\t\tresponse, err := apiClient.ContainerWait(ctx, name)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d\\n\", response.StatusCode)\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn errors.New(strings.Join(errs, \"\\n\"))\n\t}\n\n\treturn nil\n}", "func (s *Connection) CloseWait() error {\n\tcloseErr := s.Close()\n\tif closeErr != nil {\n\t\treturn closeErr\n\t}\n\tshutdownErr, ok := <-s.shutdownChan\n\tif ok {\n\t\treturn shutdownErr\n\t}\n\treturn nil\n}", "func (p *Processor) Wait() []error {\n\tclose(p.Input)\n\tp.wg.Wait()\n\tclose(p.output)\n\tp.hwg.Wait()\n\treturn p.herr\n}", "func (c *Container) Wait(ctx context.Context) error {\n\tdefer c.stopProfiling()\n\tstatusChan, errChan := c.client.ContainerWait(ctx, c.id, container.WaitConditionNotRunning)\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tcase res := <-statusChan:\n\t\tif res.StatusCode != 0 {\n\t\t\tvar msg string\n\t\t\tif res.Error != nil {\n\t\t\t\tmsg = res.Error.Message\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"container returned non-zero status: %d, msg: %q\", res.StatusCode, msg)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (g *Group) Wait() error", "func (a API) StopWait(cmd *None) (out *None, e error) {\n\tRPCHandlers[\"stop\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan StopRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (tb *Testbed) Wait(timeout time.Duration) error {\n\tdefer tb.cancel()\n\tnow := time.Now()\n\tselect {\n\tcase <-tb.donec:\n\t\treturn nil\n\tcase to := <-time.After(timeout):\n\t\twaited := to.Sub(now)\n\t\treturn errors.New(\"timeout after \" + waited.String())\n\t}\n}", "func (w *InstanceStoppedWaiter) Wait(ctx context.Context, params *DescribeInstancesInput, maxWaitDur time.Duration, optFns ...func(*InstanceStoppedWaiterOptions)) error {\n\t_, err := w.WaitForOutput(ctx, params, maxWaitDur, optFns...)\n\treturn err\n}", "func (s *InvokeSync) Wait(ctx context.Context) error {\n\tif !s.wait.Wait(ctx) {\n\t\treturn task.StopReason(ctx)\n\t}\n\treturn s.err\n}", "func (e *engine) Wait(context.Context, *Spec, *Step) (*State, error) {\n\treturn nil, nil // no-op for bash implementation\n}" ]
[ "0.71921074", "0.6797356", "0.675889", "0.6755778", "0.67316556", "0.6584684", "0.6526827", "0.6401224", "0.63894427", "0.63415635", "0.6319634", "0.6313171", "0.62899655", "0.6217153", "0.6215627", "0.62074", "0.6202083", "0.6173427", "0.6171321", "0.61360484", "0.6130087", "0.6098518", "0.6057281", "0.60417575", "0.5960839", "0.5947161", "0.5946861", "0.59399235", "0.5939447", "0.587577", "0.58711135", "0.5805608", "0.5755276", "0.5751148", "0.57405674", "0.5725252", "0.57064396", "0.5693801", "0.56910825", "0.5685164", "0.56611955", "0.5643889", "0.5630525", "0.5622451", "0.56114626", "0.5609718", "0.558093", "0.55673283", "0.5553882", "0.55511844", "0.5515918", "0.5515799", "0.5511195", "0.5500522", "0.5474498", "0.5448469", "0.5429979", "0.5426253", "0.5425145", "0.54240245", "0.54159814", "0.54151964", "0.5395837", "0.5387638", "0.53837025", "0.5367589", "0.536514", "0.53505325", "0.53475493", "0.53273416", "0.5321824", "0.5312757", "0.5310021", "0.52758175", "0.5271707", "0.5266999", "0.52585953", "0.5256109", "0.52381825", "0.5206712", "0.52057326", "0.52012557", "0.5198712", "0.5198685", "0.5194404", "0.5192681", "0.51859015", "0.51782954", "0.51738113", "0.5165377", "0.51635486", "0.5154675", "0.5152964", "0.5152109", "0.5149909", "0.5149548", "0.5144785", "0.5144669", "0.5139834", "0.5138805" ]
0.5931322
29
Signal will send a signal to the running process.
func (s *Session) Signal(sig os.Signal) { s.command.Process.Signal(sig) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Process) Signal(sig os.Signal) error {\n return p.Process.Signal(sig)\n}", "func (p *process) Signal(s os.Signal) error {\n\treturn syscall.Kill(p.pid, s.(syscall.Signal))\n}", "func (c *D) Signal(signal os.Signal) error {\n\tif !c.IsRunning() {\n\t\treturn ErrNotRunning\n\t}\n\treturn c.cmd.Process.Signal(signal)\n}", "func (c *qemuCmd) Signal(sig unix.Signal) error {\n\tcommand := api.InstanceExecControl{\n\t\tCommand: \"signal\",\n\t\tSignal: int(sig),\n\t}\n\n\t// Check handler hasn't finished.\n\tselect {\n\tcase <-c.dataDone:\n\t\treturn fmt.Errorf(\"no such process\") // Aligns with error retured from unix.Kill in lxc's Signal().\n\tdefault:\n\t}\n\n\tc.controlSendCh <- command\n\terr := <-c.controlResCh\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Debugf(`Forwarded signal \"%d\" to lxd-agent`, sig)\n\treturn nil\n}", "func ProcessSignal(p *os.Process, sig os.Signal,) error", "func (b *BoatHandle) Signal(sig os.Signal) error { return b.cmd.Process.Signal(sig) }", "func (d *Daemon) Signal(sig os.Signal) error {\n\tprocess, err := d.Process()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn process.Signal(sig)\n}", "func (p Process) Signal(sig os.Signal) error {\n\tif p.ops == nil {\n\t\treturn errInvalidProcess\n\t}\n\treturn p.ops.signal(sig)\n}", "func (c *Cmd) Signal(sig os.Signal) error {\n\treturn signal(c.cmd.Process, sig)\n}", "func (c *Cmd) Signal(signal syscall.Signal) error {\n\tif c.Process == nil {\n\t\treturn errNotStarted\n\t}\n\tif c.ProcessState != nil {\n\t\treturn errAlreadyWaited\n\t}\n\n\t// Negative PID means the process group led by the process.\n\treturn syscall.Kill(-c.Process.Pid, signal)\n}", "func (p *Process) SendSignal(sig Signal) error {\n\treturn p.SendSignalWithContext(context.Background(), sig)\n}", "func (k *KACollector) signal(sig syscall.Signal) error {\n\tps, err := process.Processes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar pid int32\n\tfor _, p := range ps {\n\t\tname, err := p.Name()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name == \"keepalived\" {\n\t\t\tpid = p.Pid\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif pid == 0 {\n\t\treturn fmt.Errorf(\"cannot find pid\")\n\t}\n\n\tproc, err := os.FindProcess(int(pid))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"process %v: %v\", pid, err)\n\t}\n\n\terr = proc.Signal(sig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"signal %v: %v\", sig, err)\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\treturn nil\n}", "func (ep *ExpectProcess) Signal(sig os.Signal) error {\n\tep.mu.Lock()\n\tdefer ep.mu.Unlock()\n\n\tif ep.cmd == nil {\n\t\treturn errors.New(\"expect process already closed\")\n\t}\n\n\treturn ep.cmd.Process.Signal(sig)\n}", "func (x *RpcExector) signal(rpcc *rpc.XmlRPCClient, sig_name string, processes []string) {\n\tfor _, process := range processes {\n\t\tif process == \"all\" {\n\t\t\treply, err := rpcc.SignalAll(process)\n\t\t\tif err == nil {\n\t\t\t\tx.showProcessInfo(&reply, make(map[string]bool))\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to all process\", sig_name)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\treply, err := rpcc.SignalProcess(sig_name, process)\n\t\t\tif err == nil && reply.Success {\n\t\t\t\tfmt.Printf(\"Succeed to send signal %s to process %s\\n\", sig_name, process)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to process %s\\n\", sig_name, process)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n}", "func (x *CtlCommand) signal(rpcc *xmlrpcclient.XMLRPCClient, sigName string, processes []string) {\n\tfor _, process := range processes {\n\t\tif process == \"all\" {\n\t\t\treply, err := rpcc.SignalAll(process)\n\t\t\tif err == nil {\n\t\t\t\tx.showProcessInfo(&reply, make(map[string]bool))\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to all process\", sigName)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\treply, err := rpcc.SignalProcess(sigName, process)\n\t\t\tif err == nil && reply.Success {\n\t\t\t\tfmt.Printf(\"Succeed to send signal %s to process %s\\n\", sigName, process)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to process %s\\n\", sigName, process)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n}", "func (x *CtlCommand) signal(rpcc *rpcclient.RPCClient, sig_name string, processes []string) {\n\tfor _, process := range processes {\n\t\tif process == \"all\" {\n\t\t\treply, err := rpcc.SignalAllProcesses(&rpcclient.SignalAllProcessesArg{\n\t\t\t\tSignal: sig_name,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tx.showProcessInfo(reply.AllProcessInfo, make(map[string]bool))\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to all process\", sig_name)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\treply, err := rpcc.SignalProcess(&rpcclient.SignalProcessArg{\n\t\t\t\tProcName: process,\n\t\t\t\tSignal: sig_name,\n\t\t\t})\n\t\t\tif err == nil && reply.Success {\n\t\t\t\tfmt.Printf(\"Succeed to send signal %s to process %s\\n\", sig_name, process)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Fail to send signal %s to process %s\\n\", sig_name, process)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n}", "func signal(s os.Signal) {\n\tp, _ := os.FindProcess(os.Getpid())\n\t_ = p.Signal(s)\n\t// Sleep so test won't finish and signal will be received.\n\ttime.Sleep(999)\n}", "func (c *Cond) Signal() {\n\tc.Do(func() {})\n}", "func (c *gcsCore) SignalProcess(pid int, options prot.SignalProcessOptions) error {\n\tc.processCacheMutex.Lock()\n\tif _, ok := c.processCache[pid]; !ok {\n\t\tc.processCacheMutex.Unlock()\n\t\treturn gcserr.NewHresultError(gcserr.HrErrNotFound)\n\t}\n\tc.processCacheMutex.Unlock()\n\n\t// Interpret signal value 0 as SIGKILL.\n\t// TODO: Remove this special casing when we are not worried about breaking\n\t// older Windows builds which don't support sending signals.\n\tvar signal syscall.Signal\n\tif options.Signal == 0 {\n\t\tsignal = unix.SIGKILL\n\t} else {\n\t\tsignal = syscall.Signal(options.Signal)\n\t}\n\n\tif err := syscall.Kill(pid, signal); err != nil {\n\t\treturn errors.Wrapf(err, \"failed call to kill on process %d with signal %d\", pid, options.Signal)\n\t}\n\n\treturn nil\n}", "func (p *Process) signalToProcess(signal os.Signal) error {\n\tif p.command == nil || p.command.Process == nil {\n\t\terr := errors.Errorf(\"attempt to send signal to non-running process\")\n\t\tp.log.Error(err)\n\t\treturn err\n\t}\n\n\treturn p.command.Process.Signal(signal)\n}", "func (s *sidecar) signalProcess() (err error) {\n\tif atomic.LoadInt32(&s.processRunning) == 0 {\n\t\tcmd := exec.Command(s.config.Cmd, strings.Split(s.config.CmdArgs, \" \")...)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\terr = cmd.Start()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error executing process: %v\\n%v\", s.config.Cmd, err)\n\t\t}\n\t\ts.process = cmd.Process\n\t\tgo s.checkProcessExit()\n\t} else {\n\t\t// Signal to reload certs\n\t\tsig, err := getSignal(s.config.RenewSignal)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting signal: %v\\n%v\", s.config.RenewSignal, err)\n\t\t}\n\n\t\terr = s.process.Signal(sig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error signaling process with signal: %v\\n%v\", sig, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (n *mockAgent) signalProcess(c *Container, processID string, signal syscall.Signal, all bool) error {\n\treturn nil\n}", "func (q *queue) Signal() {\n\tq.notEmpty.Broadcast()\n}", "func (s *countingSemaphore) Signal() {\n\ts.sem <- 1\n}", "func (s *Service) onSignal(sig os.Signal) {\n\tswitch sig {\n\tcase syscall.SIGTERM:\n\t\tfallthrough\n\tcase syscall.SIGINT:\n\t\ts.xlog.Infof(\"received signal %s, exiting...\", sig.String())\n\t\ts.Close()\n\t\tos.Exit(0)\n\t}\n}", "func (s *ShutdownManager) SignalShutdown() {\n\ts.ShutdownState = true\n}", "func signal() {\n\tnoEvents = true\n}", "func doSignal() {\n\tstop := signals.NewStopChannel()\n\t<-stop\n\tlog.Println(\"Exit signal received. Shutting down.\")\n\tos.Exit(0)\n}", "func (o *Wireless) SetSignal(v int32) {\n\to.Signal = &v\n}", "func sendSignal(cmd *exec.Cmd, ch <-chan error, sig syscall.Signal, timeout time.Duration) bool {\n\tif cmd.Process == nil {\n\t\tlog.Debug(\"Not terminating process, it seems to have not started yet\")\n\t\treturn false\n\t}\n\t// This is a bit of a fiddle. We want to wait for the process to exit but only for just so\n\t// long (we do not want to get hung up if it ignores our SIGTERM).\n\tlog.Debug(\"Sending signal %s to -%d\", sig, cmd.Process.Pid)\n\tsyscall.Kill(-cmd.Process.Pid, sig) // Kill the group - we always set one in ExecCommand.\n\n\tselect {\n\tcase <-ch:\n\t\treturn true\n\tcase <-time.After(timeout):\n\t\treturn false\n\t}\n}", "func (o *V0037JobProperties) SetSignal(v string) {\n\to.Signal = &v\n}", "func Kill(sig os.Signal) {\n go func() {\n signals.ch <- sig\n }()\n}", "func Example_signal() {\n\tevents.Listen(&events.Listener{\n\t\tEventName: SignalHello,\n\t\tHandler: func(e events.Event) {\n\t\t\tfmt.Println(e)\n\t\t},\n\t})\n\tevents.Emit(events.Signal(SignalHello))\n\t// Output: Hello world\n}", "func (o *ContainerSignalParams) SetSignal(signal int64) {\n\to.Signal = signal\n}", "func (l *Libvirt) DomainSendProcessSignal(Dom Domain, PidValue int64, Signum uint32, Flags uint32) (err error) {\n\tvar buf []byte\n\n\targs := DomainSendProcessSignalArgs {\n\t\tDom: Dom,\n\t\tPidValue: PidValue,\n\t\tSignum: Signum,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(295, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (g *Goer) installSignal() {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)\n\tfor signalType := range ch {\n\t\tswitch signalType {\n\t\t// stop process in debug mode with Ctrl+c.\n\t\tcase syscall.SIGINT:\n\t\t\tg.stopAll(ch, signalType)\n\t\t// kill signal in bash shell.\n\t\tcase syscall.SIGKILL | syscall.SIGTERM:\n\t\t\tg.stopAll(ch, signalType)\n\t\t// graceful reload\n\t\tcase syscall.SIGQUIT:\n\t\t\tsignal.Stop(ch)\n\t\t\tg.reload()\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}", "func (t *Broadcaster) Signal(ctx context.Context) error {\n\tif !t.mutex.RTryLock(ctx) {\n\t\treturn context.DeadlineExceeded\n\t}\n\tdefer t.mutex.RUnlock()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn context.DeadlineExceeded\n\tcase t.channel <- struct{}{}:\n\tdefault:\n\t}\n\n\treturn nil\n}", "func (p *promise) Signal(waitChan chan Controller) Promise {\n\tp.Always(func(p2 Controller) {\n\t\twaitChan <- p2\n\t})\n\n\treturn p\n}", "func (e *Exit) Signal() {\n\te.once.Do(func() {\n\t\tclose(e.c)\n\n\t\te.mtx.Lock()\n\t\texits := e.exits\n\t\te.exits = nil\n\t\te.mtx.Unlock()\n\n\t\tfor i := len(exits); i > 0; i-- {\n\t\t\texits[i-1]()\n\t\t}\n\t})\n}", "func (srv *Server) handleSignal(msg *Message) {\n\tsrv.opsLock.Lock()\n\t// Ignore incoming signals during shutdown\n\tif srv.shutdown {\n\t\tsrv.opsLock.Unlock()\n\t\treturn\n\t}\n\tsrv.currentOps++\n\tsrv.opsLock.Unlock()\n\n\tsrv.hooks.OnSignal(context.WithValue(context.Background(), Msg, *msg))\n\n\t// Mark signal 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 (lc *Closer) Signal() {\n\tlc.cancel()\n}", "func SignalSelf(sig os.Signal) error {\n\tself, err := os.FindProcess(os.Getpid())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn self.Signal(sig)\n}", "func PidfdSendSignal(pidfd uintptr, signum unix.Signal) error {\n\t// the runtime OS thread must be locked to safely enter namespaces.\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\t// setns with pidfd requires at least kernel version 5.8.0\n\terr := unix.Setns(int(pidfd), unix.CLONE_NEWPID)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// pifd_send_signal was introduced in kernel version 5.3\n\t_, _, e1 := unix.Syscall(unix.SYS_PIDFD_SEND_SIGNAL, pidfd, uintptr(signum), 0)\n\tif e1 != 0 {\n\t\treturn e1\n\t}\n\treturn nil\n}", "func Signal(val string) error {\n\t_, err := signals.Parse(val)\n\tif err != nil {\n\t\treturn err //nolint: wrapcheck // error string formed in external package is styled correctly\n\t}\n\n\treturn nil\n}", "func (a *App) SignalShutdown() {\n\ta.shutdown <- syscall.SIGTERM\n}", "func (a *App) SignalShutdown() {\n\ta.shutdown <- syscall.SIGTERM\n}", "func OnSignal(handler func(os.Signal), signals ...os.Signal) {\n\tif handler == nil || len(signals) == 0 {\n\t\treturn\n\t}\n\n\tsh := &sigHandler{\n\t\tsignals: signals,\n\t\ttarget: handler,\n\t}\n\tsh.Start()\n}", "func (srv *Server) handleSignal(msg *Message) {\n\tsrv.hooks.OnSignal(context.WithValue(context.Background(), Msg, *msg))\n}", "func Signal(signs ...os.Signal) Option {\n\treturn func(o *options) { o.signs = signs }\n}", "func (r *ResetReady) Signal() {\n\tr.lock.Lock()\n\tr.ready.Signal()\n\tr.lock.Unlock()\n}", "func PrintSignal(l Logger, signal os.Signal) {\n\tfmt.Println(\"\")\n\tl.Println(strings.ToUpper(signal.String()))\n}", "func X__sysv_signal(tls *TLS, signum int32, handler uintptr) {\n\tch := make(chan os.Signal)\n\tgo func() {\n\t\t<-ch\n\t\t(*(*func(*TLS, int32))(unsafe.Pointer(&handler)))(tls, signum)\n\t}()\n\tsignal.Notify(ch, syscall.Signal(signum))\n}", "func (a *Agent) trapSignal() {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, os.Interrupt)\n\tsignal.Notify(ch, syscall.SIGTERM)\n\tgo func() {\n\t\t<-ch\n\t\tlog.Println(\"\\nagent received SIGTERM signal\")\n\t\ta.stop()\n\t\tos.Exit(1)\n\t}()\n}", "func (s *Supervisor) SetShutdownSignal(signal chan struct{}) {\n\tif signal != nil {\n\t\ts.shutdown = signal\n\t}\n}", "func (re RunError) Signal() string {\n\treturn re.signal\n}", "func sendSignal(status string) {\n\tcf := cloudformation.New(session.New(&aws.Config{Region: &region}))\n\tparams := &cloudformation.SignalResourceInput{\n\t\tLogicalResourceId: &resource,\n\t\tStackName: &stack,\n\t\tStatus: &status,\n\t\tUniqueId: &uniqueID,\n\t}\n\t_, err := cf.SignalResource(params)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to signal CloudFormation: %q.\\n\", err.Error())\n\t}\n\tlog.Printf(\"Sent a %q signal to CloudFormation.\\n\", status)\n\treturn\n}", "func (a *AbstractSessionChannelHandler) OnSignal(\n\t_ uint64,\n\t_ string,\n) error {\n\treturn fmt.Errorf(\"not supported\")\n}", "func (d *Driver) SignalTask(taskID string, signal string) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\treturn d.podman.ContainerKill(d.ctx, handle.containerID, signal)\n}", "func NotifySignal(c chan<- Signal, sig ...Signal) error {\n\tif c == nil {\n\t\treturn fmt.Errorf(\"NotifySignal using nil channel\")\n\t}\n\n\tvar pid = os.Getpid()\n\tevts := make([]windows.Handle, 0, len(sig))\n\n\tfor _, s := range sig {\n\t\tname, err := windows.UTF16PtrFromString(eventName(s, pid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\th, err := windows.CreateEvent(nil, 1, 0, name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tevts = append(evts, h)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tev, err := windows.WaitForMultipleObjects(evts, false, windows.INFINITE)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"WaitForMultipleObjects failed: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toffset := ev - windows.WAIT_OBJECT_0\n\t\t\tc <- sig[offset]\n\t\t\tif err := windows.ResetEvent(evts[offset]); err != nil {\n\t\t\t\tlog.Printf(\"ResetEvent failed: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}", "func StartSignal(myPhone string, targetGroupID string, writer io.Writer) (*exec.Cmd, io.ReadCloser) {\n\tcmd := exec.Command(\"signal-cli\", \"-u\", myPhone, \"receive\", \"-t\", \"-1\", \"--json\")\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn cmd, stdout\n}", "func (mr *MockOSProcessMockRecorder) Signal(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Signal\", reflect.TypeOf((*MockOSProcess)(nil).Signal), arg0)\n}", "func Signal(sigs ...os.Signal) Option {\n\treturn func(o *options) { o.sigs = sigs }\n}", "func handleSignal(onSignal func()) {\n\tsigChan := make(chan os.Signal, 10)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGPIPE)\n\tfor signo := range sigChan {\n\t\tswitch signo {\n\t\tcase syscall.SIGINT, syscall.SIGTERM:\n\t\t\tlog.Infof(\"received signal %d (%v)\", signo, signo)\n\t\t\tonSignal()\n\t\t\treturn\n\t\tcase syscall.SIGPIPE:\n\t\t\t// By default systemd redirects the stdout to journald. When journald is stopped or crashes we receive a SIGPIPE signal.\n\t\t\t// Go ignores SIGPIPE signals unless it is when stdout or stdout is closed, in this case the agent is stopped.\n\t\t\t// We never want the agent to stop upon receiving SIGPIPE, so we intercept the SIGPIPE signals and just discard them.\n\t\tdefault:\n\t\t\tlog.Warnf(\"unhandled signal %d (%v)\", signo, signo)\n\t\t}\n\t}\n}", "func (o *TechnicalAnalysis) SetSignal(v string) {\n\to.Signal = &v\n}", "func Kill(pid int, signal syscall.Signal) error {\n\treturn syscall.Kill(pid, signal)\n}", "func Kill(pid int, signal syscall.Signal) error {\n\treturn syscall.Kill(pid, signal)\n}", "func setupSignal(d chan int) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tfmt.Printf(\"\\nCaptured signal %v\\n\", sig)\n\t\t\tfmt.Printf(\"Output in %v\\n\", \"proc.log\")\n\t\t\tos.Exit(1) // Will exit immediately.\n\t\t\td <- 0\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n}", "func (mr *MockProcessMockRecorder) Signal(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Signal\", reflect.TypeOf((*MockProcess)(nil).Signal), arg0)\n}", "func signalHandler(server net.PacketConn) {\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)\n\tfor {\n\t\tsig := <-sigCh\n\t\tswitch sig {\n\t\tcase syscall.SIGHUP:\n\t\t\tlog.Info(\"SIGHUP received, reloading route map\")\n\t\t\tif err := routeMapReload(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\tcase os.Interrupt, syscall.SIGTERM:\n\t\t\tlog.Info(sig)\n\t\t\tserver.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (k Keeper) SetSignal(ctx sdk.Context, protocol uint64, address string) {\n\tkvStore := ctx.KVStore(k.storeKey)\n\tkvStore.Set(types.GetSignalKey(protocol, address), k.cdc.MustMarshalBinaryLengthPrefixed(true))\n}", "func handleSignal(env *Environment) {\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(ch, stopSignals...)\n\n\tgo func() {\n\t\ts := <-ch\n\t\tdelay := getDelaySecondsFromEnv()\n\t\tlog.Warn(\"well: got signal\", map[string]interface{}{\n\t\t\t\"signal\": s.String(),\n\t\t\t\"delay\": delay,\n\t\t})\n\t\ttime.Sleep(time.Duration(delay) * time.Second)\n\t\tenv.Cancel(errSignaled)\n\t}()\n}", "func signalCatcher(liner *liner.State) {\n\tch := make(chan os.Signal)\n\tsignal.Notify(ch, syscall.SIGINT)\n\t<-ch\n\tliner.Close()\n\tos.Exit(0)\n}", "func (wc *workflowClient) SignalWorkflow(ctx context.Context, workflowID string, runID string, signalName string, arg interface{}) error {\n\tinput, err := encodeArg(wc.dataConverter, arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn signalWorkflow(ctx, wc.workflowService, wc.identity, wc.domain, workflowID, runID, signalName, input, wc.featureFlags)\n}", "func signalHandler(sig chan os.Signal, cancel context.CancelFunc) {\n\tfor {\n\t\tselect {\n\t\tcase s := <-sig:\n\t\t\tswitch s {\n\t\t\tcase syscall.SIGINT:\n\t\t\t\tlog.sugar.Info(\"received SIGINT signal\")\n\t\t\t\tlog.sugar.Info(\"shutdown...\")\n\t\t\t\tcancel()\n\t\t\tcase syscall.SIGTERM:\n\t\t\t\tlog.sugar.Info(\"received SIGTERM signal\")\n\t\t\t\tlog.sugar.Info(\"shutdown...\")\n\t\t\t\tcancel()\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *DriverHandle) SetKillSignal(signal string) {\n\th.killSignal = signal\n}", "func TrapSignal(cleanupFunc func()) {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tsig := <-sigs\n\n\t\tif cleanupFunc != nil {\n\t\t\tcleanupFunc()\n\t\t}\n\t\texitCode := 128\n\n\t\tswitch sig {\n\t\tcase syscall.SIGINT:\n\t\t\texitCode += int(syscall.SIGINT)\n\t\tcase syscall.SIGTERM:\n\t\t\texitCode += int(syscall.SIGTERM)\n\t\t}\n\n\t\tos.Exit(exitCode)\n\t}()\n}", "func (r *RuntimeImpl) Kill() {\n\tr.osSignals <- syscall.SIGKILL\n}", "func (m *MockProcess) Signal(arg0 os.Signal) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Signal\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (s WorkerSemaphore) Signal(n int) {\n\te := empty{}\n\tfor i := 0; i < n; i++ {\n\t\ts.permits <- e\n\t}\n}", "func (t *Indie) handleSignal() {\n signal.Notify(t.signalChan, syscall.SIGTERM)\n\n for {\n\tswitch <-t.signalChan {\n\tcase syscall.SIGTERM:\n\t log.Println(\"[NOTICE] RECEIVE signal: SIGTERM. \")\n\n\t // Notify Stop\n\t t.stopModules()\n\n\t // Wait Modules Stop\n\t t.waitModules()\n\n\t log.Println(\"[NOTICE] ALL MODULES ARE STOPPED, GOING TO EXIT.\")\n\n\t os.Exit(0)\n\t}\n }\n}", "func HandleSignal(c chan os.Signal, arg interface{}) {\n\t// Block until a signal is received.\n\tfor {\n\t\ts := <-c\n\t\tLog.Info(\"Get a signal %s\", s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:\n\t\t\t// Exit\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\t\t// TODO\n\t\t\t// Reload\n\t\t\t// return\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (srv *server) signalShutdown() {\n\tsrv.once.Do(func() {\n\t\tsrv.cond.L.Lock()\n\t\tsrv.cond.Signal()\n\t\tsrv.cond.L.Unlock()\n\t})\n}", "func TestSignal(t *testing.T) {\n\t// Ask for SIGHUP\n\tc := make(chan os.Signal, 1)\n\tNotify(c, syscall.SIGHUP)\n\tdefer Stop(c)\n\n\t// Send this process a SIGHUP\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSig(t, c, syscall.SIGHUP)\n\n\t// Ask for everything we can get. The buffer size has to be\n\t// more than 1, since the runtime might send SIGURG signals.\n\t// Using 10 is arbitrary.\n\tc1 := make(chan os.Signal, 10)\n\tNotify(c1)\n\t// Stop relaying the SIGURG signals. See #49724\n\tReset(syscall.SIGURG)\n\tdefer Stop(c1)\n\n\t// Send this process a SIGWINCH\n\tt.Logf(\"sigwinch...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGWINCH)\n\twaitSigAll(t, c1, syscall.SIGWINCH)\n\n\t// Send two more SIGHUPs, to make sure that\n\t// they get delivered on c1 and that not reading\n\t// from c does not block everything.\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSigAll(t, c1, syscall.SIGHUP)\n\tt.Logf(\"sighup...\")\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGHUP)\n\twaitSigAll(t, c1, syscall.SIGHUP)\n\n\t// The first SIGHUP should be waiting for us on c.\n\twaitSig(t, c, syscall.SIGHUP)\n}", "func (e *AutoResetEvent) Signal() {\n\te.l.Lock()\n\tif len(e.c) == 0 {\n\t\te.c <- struct{}{}\n\t}\n\te.l.Unlock()\n}", "func (t *SignalTable)StartSignalHandle() {\n go t.signalHandle()\n}", "func handleSignal() {\n\tgo func() {\n\t\tc := make(chan os.Signal)\n\n\t\tsignal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\t\ts := <-c\n\t\tlogger.Tracef(\"Got signal [%s]\", s)\n\n\t\tsession.SaveOnlineUsers()\n\t\tlogger.Tracef(\"Saved all online user, exit\")\n\n\t\tos.Exit(0)\n\t}()\n}", "func RaiseSignal(pid int, sig Signal) error {\n\tname, err := windows.UTF16PtrFromString(eventName(sig, pid))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tev, err := windows.OpenEvent(windows.EVENT_MODIFY_STATE, false, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer windows.CloseHandle(ev)\n\treturn windows.SetEvent(ev)\n}", "func (m *MockOSProcess) Signal(arg0 os.Signal) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Signal\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (svr *server) signalShutdown(err error) {\n\tsvr.once.Do(func() {\n\t\tsvr.cond.L.Lock()\n\t\tsvr.serr = err\n\t\tsvr.cond.Signal()\n\t\tsvr.cond.L.Unlock()\n\t})\n}", "func (a *Application) AwaitSignal() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Reset(syscall.SIGTERM, syscall.SIGINT)\n\tsignal.Notify(c, syscall.SIGTERM, syscall.SIGINT)\n\n\ts := <-c\n\ta.logger.Info(\"receive a signal\", zap.String(\"signal\", s.String()))\n\tif a.httpServer != nil {\n\t\tif err := a.httpServer.Stop(); err != nil {\n\t\t\ta.logger.Warn(\"stop http server error\", zap.Error(err))\n\t\t}\n\t}\n\tif a.grpcServer != nil {\n\t\tif err := a.grpcServer.Stop(); err != nil {\n\t\t\ta.logger.Warn(\"stop grpc server error\", zap.Error(err))\n\t\t}\n\t}\n\n\tos.Exit(0)\n}", "func (s *Signal) SendSig(recv, sender Ki, sig int64, data any) {\n\ts.Mu.RLock()\n\tfun := s.Cons[recv]\n\ts.Mu.RUnlock()\n\tif fun != nil {\n\t\tfun(recv, sender, sig, data)\n\t}\n}", "func (c *gcsCore) SignalContainer(id string, signal syscall.Signal) error {\n\tc.containerCacheMutex.Lock()\n\tdefer c.containerCacheMutex.Unlock()\n\n\tcontainerEntry := c.getContainer(id)\n\tif containerEntry == nil {\n\t\treturn gcserr.NewHresultError(gcserr.HrVmcomputeSystemNotFound)\n\t}\n\n\tif containerEntry.container != nil {\n\t\tif err := containerEntry.container.Kill(signal); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (g *Pin) Notify(sig ...os.Signal) {\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, sig...)\n\tgo func() {\n\t\tn := 0\n\t\tfor sig := range c {\n\t\t\tif n == 1 {\n\t\t\t\tpanic(\"got too many signals\")\n\t\t\t}\n\t\t\tg.Pull(fmt.Errorf(\"Recieved signal %s\", sig))\n\t\t\tn++\n\t\t}\n\t}()\n}", "func TestSignals(t *testing.T) {\n\tseq := make(chan int)\n\twait := make(chan int)\n\tfreq := make(chan time.Time)\n\n\tqueue := &WaitQueue{\n\t\tsem: new(sync.WaitGroup),\n\t\tseq: seq,\n\t\twait: wait,\n\t}\n\n\t// begin listening\n\tgo waitListen(queue, freq, seq)\n\n\t// send a tick, this should start a call to Poll()\n\tfreq <- time.Now()\n\n\t// when that call starts, we should get `1` on the sequence channel\n\tval := <-seq\n\trequire.Equal(t, val, 1)\n\n\t// send a signal, this should start the graceful exit\n\tsignals <- os.Interrupt\n\n\t// tell Poll() that it can exit\n\twait <- 1\n\n\t// first Poll() should exit\n\tval = <-seq\n\trequire.Equal(t, val, 2)\n\n\t// then Listen() should exit\n\tval = <-seq\n\trequire.Equal(t, val, 3)\n}", "func handlerSignal() {\n\texpectedSignals := make(chan os.Signal, 1)\n\tdoneSignals := make(chan bool, 1)\n\n\t// register channel to receive 2 signals\n\tsignal.Notify(expectedSignals, syscall.SIGTERM, syscall.SIGINT)\n\n\t// this routine is blocking, i.e. when it gets one signal it prints it and notifies the program that it can finish\n\tgo func() {\n\t\tsig := <-expectedSignals\n\t\tfmt.Println()\n\t\tfmt.Println(sig.String())\n\t\tdoneSignals <- true\n\t}()\n\n\tfmt.Println(\"awaiting signal...\")\n\n\t<-doneSignals\n\n\tfmt.Println(\"exiting...\")\n}", "func WaitSignal(stop chan struct{}) {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n\tglog.Warningln(\"Finishing with signal handling.\")\n\tclose(stop)\n}", "func (a *Agent) stopSignalHandler() {\n\tsignal.Stop(a.signalCh)\n\tsignal.Reset() // so a second ctrl-c will force a kill\n}", "func WaitSignal(stop chan struct{}) {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n\tclose(stop)\n}", "func InitSignal() {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)\n\tfor {\n\t\ts := <-c\n\t\tlog.Info(\"job[%s] get a signal %s\", Ver, s.String())\n\t\tswitch s {\n\t\tcase syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:\n\t\t\treturn\n\t\tcase syscall.SIGHUP:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func HandleSignal(b bool) Option {\n\treturn func(o *Options) {\n\t\to.Signal = b\n\t}\n}" ]
[ "0.83315116", "0.7944749", "0.76571196", "0.763797", "0.75873667", "0.7493231", "0.74723375", "0.74002385", "0.72498876", "0.72400916", "0.71118015", "0.70792997", "0.6922517", "0.68888897", "0.6854779", "0.6834527", "0.68048215", "0.66322833", "0.6622571", "0.6621923", "0.6420721", "0.6392595", "0.63191336", "0.63042265", "0.6232893", "0.61851275", "0.61743104", "0.61587423", "0.6139846", "0.6112988", "0.610563", "0.6059617", "0.5981677", "0.59742796", "0.59706664", "0.59351516", "0.59335285", "0.5926369", "0.58859557", "0.58723384", "0.58414364", "0.58321524", "0.5823279", "0.5782348", "0.5730077", "0.5730077", "0.57171154", "0.57138515", "0.570245", "0.56955415", "0.5683154", "0.5682878", "0.56750494", "0.5659737", "0.5645514", "0.56212324", "0.560798", "0.5596805", "0.55890393", "0.55862236", "0.55803573", "0.5566607", "0.5554403", "0.55371535", "0.553649", "0.553649", "0.5527479", "0.5522104", "0.5510685", "0.5483899", "0.54680127", "0.5465629", "0.5458621", "0.54428786", "0.5415794", "0.5406952", "0.5404573", "0.5372108", "0.53630924", "0.5355907", "0.5349539", "0.53419", "0.53399783", "0.5339838", "0.53360283", "0.53323424", "0.53097004", "0.53088504", "0.5299481", "0.5296927", "0.52704704", "0.5264441", "0.5261657", "0.52583784", "0.52566", "0.52459496", "0.52431595", "0.5242259", "0.52388453", "0.5232687" ]
0.75317323
5
canonical service name, e.g. "comment" => "comment.hy.byted.org." can be further used as DNS domain name
func (sd *ServiceDiscovery) CanonicalName(service string) string { if strings.HasSuffix(service, sd.Domain) { return service } return strings.Join([]string{service, serviceSuffix, sd.Dc, sd.Domain}, ".") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func hostnameForService(svc string) string {\n\n\tparts := strings.Split(svc, \"/\")\n\tif len(parts) < 2 {\n\t\treturn parts[0]\n\t}\n\tif len(parts) > 2 {\n\t\tlog.Printf(\"Malformated service identifier [%s] - Hostname will be truncated\", svc)\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", parts[1], parts[0])\n\n}", "func serviceHostname(name string) string {\n\t// TODO include datacenter in Hostname?\n\t// consul DNS uses \"redis.service.us-east-1.consul\" -> \"[<optional_tag>].<svc>.service.[<optional_datacenter>].consul\"\n\treturn fmt.Sprintf(\"%s.service.consul\", name)\n}", "func NormalizeForServiceName(svcName string) string {\n\tre := regexp.MustCompile(\"[._]\")\n\tnewName := strings.ToLower(re.ReplaceAllString(svcName, \"-\"))\n\tif newName != svcName {\n\t\tlog.Infof(\"Changing service name to %s from %s\", svcName, newName)\n\t}\n\treturn newName\n}", "func cleanServiceName(in string) string {\n\tr := strings.NewReplacer(\n\t\t\"-\", \"_\",\n\t\t\" \", \"_\",\n\t\t\".\", \"_\",\n\t\t\"/\", \"_\",\n\t\t\"\\\\\", \"_\",\n\t)\n\n\treturn snaker.SnakeToCamel(r.Replace(in))\n}", "func servicename(meta metav1.ObjectMeta, portname string) string {\n\tname := []string{\n\t\tmeta.Namespace,\n\t\tmeta.Name,\n\t\tportname,\n\t}\n\tif portname == \"\" {\n\t\tname = name[:2]\n\t}\n\treturn strings.Join(name, \"/\")\n}", "func GetServiceDomainName(prefix string) (ret string) {\n\tsuffix := extractSuffix()\n\tret = prefix + suffix\n\tLogf(\"Get domain name: %s\", ret)\n\treturn\n}", "func DomainName() string {\n\treturn fmt.Sprintf(\"%s.%s\",\n\t\tAlpha(\"\", 14),\n\t\tItem(\"net\", \"com\", \"org\", \"io\", \"gov\"))\n}", "func BuildServiceDNSName(service, branch, environment, serviceNamespace string) string {\n\treturn service + \"-\" + branch + \"-\" + environment + \".\" + serviceNamespace\n}", "func (d Config) Service() string {\n\treturn \"dns\"\n}", "func ToCanonicalName(name string) string {\n\tnameParts := strings.Split(name, \"/\")\n\t// Reverse first part. e.g., io.k8s... instead of k8s.io...\n\tif len(nameParts) > 0 && strings.Contains(nameParts[0], \".\") {\n\t\tparts := strings.Split(nameParts[0], \".\")\n\t\tfor i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {\n\t\t\tparts[i], parts[j] = parts[j], parts[i]\n\t\t}\n\t\tnameParts[0] = strings.Join(parts, \".\")\n\t}\n\treturn strings.Join(nameParts, \".\")\n}", "func normalizeDomain(domain string) (string, error) {\n\tdomain = strings.Trim(strings.ToLower(domain), \" \")\n\t// not checking if it belongs to icann\n\tsuffix, _ := publicsuffix.PublicSuffix(domain)\n\tif domain != \"\" && suffix == domain { // input is publicsuffix\n\t\treturn \"\", errors.New(\"domain [\" + domain + \"] is public suffix\")\n\t}\n\tif !strings.HasPrefix(domain, \"http\") {\n\t\tdomain = fmt.Sprintf(\"http://%s\", domain)\n\t}\n\turl, err := url.Parse(domain)\n\tif nil == err && url.Host != \"\" {\n\t\treturn strings.Replace(url.Host, \"www.\", \"\", 1), nil\n\t}\n\treturn \"\", err\n}", "func frontendNameForServicePort(service *corev1.Service, port corev1.ServicePort) string {\n\treturn fmt.Sprintf(serviceFrontendNameFormatString, stringsutil.ReplaceForwardSlashesWithDots(cluster.Name), service.Namespace, service.Name, port.Port)\n}", "func makeServiceName(msURL string, msOrg string, msVersion string) string {\n\n\turl := \"\"\n\tpieces := strings.SplitN(msURL, \"/\", 3)\n\tif len(pieces) >= 3 {\n\t\turl = strings.TrimSuffix(pieces[2], \"/\")\n\t\turl = strings.Replace(url, \"/\", \"-\", -1)\n\t}\n\n\tversion := \"\"\n\tvExp, err := policy.Version_Expression_Factory(msVersion)\n\tif err == nil {\n\t\tversion = fmt.Sprintf(\"%v-%v\", vExp.Get_start_version(), vExp.Get_end_version())\n\t}\n\n\treturn fmt.Sprintf(\"%v_%v_%v\", url, msOrg, version)\n\n}", "func serviceUnitName(appName types.ACName) string {\n\treturn appName.String() + \".service\"\n}", "func canonicalizeInstanceName(name string) string {\n\tix := strings.Index(name, \".\")\n\tif ix != -1 {\n\t\tname = name[:ix]\n\t}\n\treturn name\n}", "func DNSName(hostport string) (string, error) {\n\thost, err := Host(hostport)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\tif ip := net.ParseIP(host); len(ip) != 0 {\n\t\treturn \"\", trace.BadParameter(\"%v is an IP address\", host)\n\t}\n\treturn host, nil\n}", "func getServiceName(vpnName string) string {\n\treturn \"openvpn-server@\" + vpnName\n}", "func (k *K8sutil) GetClientServiceNameFullDNS(clusterName, namespace string) string {\n\treturn fmt.Sprintf(\"%s.%s.svc.cluster.local\", k.GetClientServiceName(clusterName), namespace)\n}", "func canonicalHost(host string) string {\n\t// If no port is present in the server, we assume port 2424\n\t_, _, err := net.SplitHostPort(host)\n\tif err != nil {\n\t\thost += \":2424\"\n\t}\n\n\t// if no protocol is given, assume https://\n\tif !strings.Contains(host, \"://\") {\n\t\thost = \"https://\" + host\n\t}\n\n\treturn host\n}", "func shortHostname(hostname string) string {\n\tif i := strings.Index(hostname, \".\"); i >= 0 {\n\t\treturn hostname[:i]\n\t}\n\treturn hostname\n}", "func shortHostname(hostname string) string {\n\tif i := strings.Index(hostname, \".\"); i >= 0 {\n\t\treturn hostname[:i]\n\t}\n\treturn hostname\n}", "func getManagementServiceDnsName(cluster types.NamespacedName) string {\n\treturn cluster.Name + \".\" + cluster.Namespace + \".svc.cluster.local\"\n}", "func hostnameInSNI(name string) string {\n\thost := name\n\tif len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {\n\t\thost = host[1 : len(host)-1]\n\t}\n\tif i := strings.LastIndex(host, \"%\"); i > 0 {\n\t\thost = host[:i]\n\t}\n\tif net.ParseIP(host) != nil {\n\t\treturn \"\"\n\t}\n\tfor len(name) > 0 && name[len(name)-1] == '.' {\n\t\tname = name[:len(name)-1]\n\t}\n\treturn name\n}", "func backendNameForServicePort(service *corev1.Service, port corev1.ServicePort) string {\n\treturn fmt.Sprintf(serviceBackendNameFormatString, stringsutil.ReplaceForwardSlashesWithDots(cluster.Name), service.Namespace, service.Name, port.Port)\n}", "func ServiceName(instanceGroupName string) string {\n\treturn names.Sanitize(instanceGroupName)\n}", "func canonicalAddress(url *url.URL) string {\n\thost := url.Hostname()\n\tport := url.Port()\n\tif port == \"\" {\n\t\tport = defaultPorts[url.Scheme]\n\t}\n\treturn fmt.Sprintf(\"%s:%s\", host, port)\n}", "func HostToService(host string, externalApex string) (string, error) {\n\t// First, prepend a \".\" to root domain\n\texternalApex = \".\" + strings.ToLower(externalApex)\n\n\t// For safety, set host to lowercase\n\thost = strings.ToLower(host)\n\n\t// Host may contain a port, so chop it off\n\tcolonIndex := strings.Index(host, \":\")\n\tif colonIndex > -1 {\n\t\thost = host[:colonIndex]\n\t}\n\n\t// Check that host ends with subdomain\n\tif len(host) <= len(externalApex) {\n\t\treturn \"\", fmt.Errorf(\"Host is less than root domain length\")\n\t}\n\n\tsubdomainLength := len(host) - len(externalApex)\n\tif host[subdomainLength:] != externalApex {\n\t\treturn \"\", fmt.Errorf(\"Does not contain root domain\")\n\t}\n\n\t// Return subdomain\n\treturn host[:subdomainLength], nil\n}", "func formatHost(host string) string {\n\tswitch h := strings.ToLower(host); h {\n\tcase \"github.com\":\n\t\treturn \"GitHub\"\n\tcase \"gitlab.com\":\n\t\treturn \"GitLab\"\n\tcase \"bitbucket.org\":\n\t\treturn \"Bitbucket\"\n\tdefault:\n\t\treturn host\n\t}\n}", "func hosten(dom string) string {\n\tdom = strings.TrimSpace(dom)\n\tvar domain string\n\tif strings.HasPrefix(dom, \"http:\") ||\n\t\tstrings.HasPrefix(dom, \"https:\") {\n\t\tdmt, err := url.Parse(dom)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdomain = dmt.Host\n\t} else {\n\t\tdomain = dom\n\t}\n\treturn domain\n}", "func GetServiceFQDN(namespace string, name string) string {\n\tclusterDomain := os.Getenv(\"CLUSTER_DOMAIN\")\n\tif clusterDomain == \"\" {\n\t\tclusterDomain = \"cluster.local\"\n\t}\n\treturn fmt.Sprintf(\n\t\t\"%s.%s.svc.%s\",\n\t\tname, namespace, clusterDomain,\n\t)\n}", "func DetectNamingService(domainName string) (string, error) {\n\tchunks := strings.Split(domainName, \".\")\n\tif len(chunks) == 0 {\n\t\treturn \"\", &DomainNotSupportedError{DomainName: domainName}\n\t}\n\textension := chunks[len(chunks)-1]\n\tservice := supportedNamingServices[extension]\n\tif service == \"\" {\n\t\treturn \"\", &DomainNotSupportedError{DomainName: domainName}\n\t}\n\treturn service, nil\n}", "func servicePortChainName(serviceStr string, protocol string) string {\n\thash := sha256.Sum256([]byte(serviceStr + protocol))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn \"KUBE-SVC-\" + encoded[:16]\n}", "func ToFqdn(name string) string {\r\n\tif strings.HasSuffix(name, \".\") {\r\n\t\treturn name\r\n\t}\r\n\treturn name + \".\"\r\n}", "func ServiceUnitName(appName types.ACName) string {\n\treturn appName.String() + \".service\"\n}", "func GetHostname(addr string) string {\n\treturn strings.Split(addr, \":\")[0]\n}", "func (h Host) Normalize() string {\n\t// separate host and port\n\thost, _, err := net.SplitHostPort(string(h))\n\tif err != nil {\n\t\thost, _, _ = net.SplitHostPort(string(h) + \":\")\n\t}\n\treturn strings.ToLower(dns.Fqdn(host))\n}", "func (o KafkaConnectorOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaConnector) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o ServiceCorrelationDescriptionOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceCorrelationDescription) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o M3DbOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *M3Db) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func DomainName(opts ...options.OptionFunc) string {\n\treturn singleFakeData(DomainNameTag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\td, err := i.domainName()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn d\n\t}, opts...).(string)\n}", "func parseServiceName(name string) (instance, serviceType, domain string, err error) {\n\ts := trimDot(name)\n\tl := len(s)\n\tvar ss []string\n\tfor {\n\t\tpos := strings.LastIndex(s[:l], \".\")\n\t\tif pos != -1 {\n\t\t\tss = append(ss, s[pos+1:l])\n\t\t\tl = pos\n\t\t\tif len(ss) >= 3 {\n\t\t\t\t// done\n\t\t\t\tdomain = ss[0]\n\t\t\t\tserviceType = ss[2] + \".\" + ss[1]\n\t\t\t\tinstance = s[:l]\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"illegal service instance\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (s *Service) Name() string { return app.ServiceName }", "func Parse(s string) (Name, error) {\n\tformattedName := strings.Trim(strings.ToLower(s), \".\")\n\n\tif strings.HasPrefix(formattedName, \"*.\") {\n\t\tformattedName = strings.Replace(formattedName, \"*.\", \"\", 1)\n\t}\n\tif strings.HasPrefix(formattedName, \"@.\") {\n\t\tformattedName = strings.Replace(formattedName, \"@.\", \"\", 1)\n\t}\n\n\tif len(formattedName) == 0 {\n\t\treturn Name{}, fmt.Errorf(\"domain name is empty\")\n\t}\n\n\tvar err error\n\tformattedName, err = idna.ToASCII(formattedName)\n\tif err != nil {\n\t\treturn Name{}, fmt.Errorf(\"domain name %s is invalid: %w\", s, err)\n\t}\n\n\tif err = Validate(formattedName); err != nil {\n\t\treturn Name{}, fmt.Errorf(\"domain name %s is invalid: %w\", s, err)\n\t}\n\n\trule := publicsuffix.DefaultList.Find(formattedName, publicsuffix.DefaultFindOptions)\n\tif rule == nil {\n\t\treturn Name{}, fmt.Errorf(\"domain name %s is invalid: no rule found\", s)\n\t}\n\n\tcategory := eTLDUndefined\n\tif rule.Private {\n\t\tcategory = eTLDPrivate\n\t} else if len(rule.Value) > 0 {\n\t\t// empty value indicates the default rule\n\t\tcategory = eTLDICANN\n\t}\n\n\tdecomposedName := rule.Decompose(formattedName)\n\tif decomposedName[1] == \"\" {\n\t\t// no TLD found, which means it's already a TLD\n\t\treturn Name{\n\t\t\tlabels: []string{formattedName},\n\t\t\tcategory: category,\n\t\t}, nil\n\t}\n\n\tlabelsNoTDL := strings.TrimSuffix(formattedName, decomposedName[1])\n\tlabelsNoTDL = strings.TrimSuffix(labelsNoTDL, \".\")\n\n\tif len(labelsNoTDL) == 0 {\n\t\treturn Name{\n\t\t\tlabels: []string{decomposedName[1]},\n\t\t\tcategory: category,\n\t\t}, nil\n\t}\n\n\treturn Name{\n\t\tlabels: append(strings.Split(labelsNoTDL, \".\"), decomposedName[1]),\n\t\tcategory: category,\n\t}, nil\n}", "func buildHostName(subDomainPrefix string, subDomainSuffix string, subDomain string, domain string) string {\n\treturn joinNonEmpty([]interface{}{joinNonEmpty([]interface{}{subDomainPrefix, subDomain, subDomainSuffix}, \"-\"), domain}, \".\")\n}", "func UConverterGetCanonicalName(arg2 string, arg3 string, arg4 *UErrorCode) (_swig_ret string)", "func LookupDNSHostCNAME(domain string) string {\n\tif nsRecord, err := net.LookupCNAME(domain); err == nil {\n\t\treturn nsRecord\n\t}\n\treturn \"\"\n}", "func DnsDomain(s string) string {\n\tl := strings.Split(s, \"/\")\n\t// start with 1, to strip /skydns\n\tfor i, j := 1, len(l)-1; i < j; i, j = i+1, j-1 {\n\t\tl[i], l[j] = l[j], l[i]\n\t}\n\treturn dns.Fqdn(strings.Join(l[2:len(l)-1], \".\"))\n}", "func getServiceName(service *apiv1.Service) string {\n\treturn fmt.Sprintf(\"%s/%s\", service.Namespace, service.Name)\n}", "func (o KafkaAclOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaAcl) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o ServiceCorrelationDescriptionResponseOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceCorrelationDescriptionResponse) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func Name(s string) string {\n\tparts := strings.Split(s, \".\")\n\n\tfor key, value := range parts {\n\t\tparts[key] = strings.Title(value)\n\t}\n\n\treturn strings.Join(parts, \"\\\\\")\n}", "func (o ServiceOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Service) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func absDomainName(b []byte) string {\n\thasDots := false\n\tfor _, x := range b {\n\t\tif x == '.' {\n\t\t\thasDots = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasDots && b[len(b)-1] != '.' {\n\t\tb = append(b, '.')\n\t}\n\treturn string(b)\n}", "func (o PgDatabaseOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PgDatabase) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func canonicalAddr(url *url.URL) string {\n\taddr := url.Host\n\tif !HasPort(addr) {\n\t\treturn addr + \":\" + portMap[url.Scheme]\n\t}\n\treturn addr\n}", "func GetHostName(hostAddr string) string {\n\treturn strings.Split(hostAddr, base.UrlPortNumberDelimiter)[0]\n}", "func canonicalAddr(url *url.URL) string {\n\taddr := url.Host\n\tif !hasPort(addr) {\n\t\treturn addr + \":\" + portMap[url.Scheme]\n\t}\n\treturn addr\n}", "func NormalizeService(svc string, lang string) (string, error) {\n\tif svc == \"\" {\n\t\treturn fallbackService(lang), ErrEmpty\n\t}\n\tvar err error\n\tif len(svc) > MaxServiceLen {\n\t\tsvc = TruncateUTF8(svc, MaxServiceLen)\n\t\terr = ErrTooLong\n\t}\n\t// We are normalizing just the tag value.\n\ts := NormalizeTagValue(svc)\n\tif s == \"\" {\n\t\treturn fallbackService(lang), ErrInvalid\n\t}\n\treturn s, err\n}", "func PackageName(d *pdl.Domain) string {\n\treturn strings.ToLower(d.Domain.String())\n}", "func (o KafkaMirrorMakerOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaMirrorMaker) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o FlinkApplicationOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FlinkApplication) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func TruncatedServiceName(igName string, maxLength int) string {\n\ts := names.DNSLabelSafe(igName)\n\treturn names.TruncateMD5(s, maxLength)\n}", "func Hostname() (string, error)", "func ServiceName(serviceName string) string {\n\treturn serviceNameReplacer.Replace(serviceName)\n}", "func servicePortEndpointChainName(servicePortName string, protocol string, endpoint string) string {\n\thash := sha256.Sum256([]byte(servicePortName + protocol + endpoint))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn \"k8s-nfproxy-sep-\" + encoded[:16]\n}", "func (k *Kit) ServiceName() string { return k.name }", "func getDomainPrefix(app string) string {\n\tv, _ := version.Agent()\n\treturn fmt.Sprintf(\"%d-%d-%d-%s.agent\", v.Major, v.Minor, v.Patch, app)\n}", "func ServiceName(file *descriptor.FileDescriptorProto, svc *descriptor.ServiceDescriptorProto) string {\n\tserviceName := svc.GetName()\n\n\treturn ClassNamePrefix(serviceName, file) + serviceName\n}", "func (sd *ServiceDiscovery) ResolveName(name string) (string, string) {\n\tname = stripDomain(name)\n\tif strings.HasSuffix(name, sd.Domain) {\n\t\tname = name[0 : len(name)-len(sd.Domain)-1]\n\t}\n\tseparator := fmt.Sprintf(\".%s\", serviceSuffix)\n\tvar service string\n\tvar dc string\n\tif strings.Contains(name, separator) {\n\t\tcols := strings.Split(name, separator)\n\t\tservice, dc = cols[0], stripDomain(cols[1])\n\t\tif len(dc) < 1 {\n\t\t\tdc = sd.Dc\n\t\t}\n\t} else {\n\t\tservice, dc = name, sd.Dc\n\t}\n\treturn service, dc\n}", "func (o CustomDomainScmOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainScm) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (r *ClusterServiceResource) ServiceFQDN(clusterDomain string) string {\n\t// In every dns name there is trailing dot to query absolute path\n\t// For trailing dot explanation please visit http://www.dns-sd.org/trailingdotsindomainnames.html\n\tif r.pandaCluster.Spec.DNSTrailingDotDisabled {\n\t\treturn fmt.Sprintf(\"%s%c%s.svc.%s\",\n\t\t\tr.Key().Name,\n\t\t\t'.',\n\t\t\tr.Key().Namespace,\n\t\t\tclusterDomain,\n\t\t)\n\t}\n\treturn fmt.Sprintf(\"%s%c%s.svc.%s.\",\n\t\tr.Key().Name,\n\t\t'.',\n\t\tr.Key().Namespace,\n\t\tclusterDomain,\n\t)\n}", "func ServiceTypeName(t string) string {\n\tres := serviceTypeNames[t]\n\tif res == \"\" {\n\t\tpanic(fmt.Sprintf(\"no nice string for Service Type %s\", t))\n\t}\n\n\treturn res\n}", "func GetDSDomainName(dsExampleURLs []string) (string, error) {\n\t// TODO move somewhere generic\n\tif len(dsExampleURLs) == 0 {\n\t\treturn \"\", errors.New(\"no example URLs\")\n\t}\n\n\tdsName := dsExampleURLs[0] + \".\"\n\tfirstDot := strings.Index(dsName, \".\")\n\tif firstDot == -1 {\n\t\treturn \"\", errors.New(\"malformed example URL, no dots\")\n\t}\n\tif len(dsName) < firstDot+2 {\n\t\treturn \"\", errors.New(\"malformed example URL, nothing after first dot\")\n\t}\n\tdsName = dsName[firstDot+1:]\n\tdsName = strings.ToLower(dsName)\n\treturn dsName, nil\n}", "func PrintSocketDomain(sd uint32) string {\n\tvar socketDomains = map[uint32]string{\n\t\t0: \"AF_UNSPEC\",\n\t\t1: \"AF_UNIX\",\n\t\t2: \"AF_INET\",\n\t\t3: \"AF_AX25\",\n\t\t4: \"AF_IPX\",\n\t\t5: \"AF_APPLETALK\",\n\t\t6: \"AF_NETROM\",\n\t\t7: \"AF_BRIDGE\",\n\t\t8: \"AF_ATMPVC\",\n\t\t9: \"AF_X25\",\n\t\t10: \"AF_INET6\",\n\t\t11: \"AF_ROSE\",\n\t\t12: \"AF_DECnet\",\n\t\t13: \"AF_NETBEUI\",\n\t\t14: \"AF_SECURITY\",\n\t\t15: \"AF_KEY\",\n\t\t16: \"AF_NETLINK\",\n\t\t17: \"AF_PACKET\",\n\t\t18: \"AF_ASH\",\n\t\t19: \"AF_ECONET\",\n\t\t20: \"AF_ATMSVC\",\n\t\t21: \"AF_RDS\",\n\t\t22: \"AF_SNA\",\n\t\t23: \"AF_IRDA\",\n\t\t24: \"AF_PPPOX\",\n\t\t25: \"AF_WANPIPE\",\n\t\t26: \"AF_LLC\",\n\t\t27: \"AF_IB\",\n\t\t28: \"AF_MPLS\",\n\t\t29: \"AF_CAN\",\n\t\t30: \"AF_TIPC\",\n\t\t31: \"AF_BLUETOOTH\",\n\t\t32: \"AF_IUCV\",\n\t\t33: \"AF_RXRPC\",\n\t\t34: \"AF_ISDN\",\n\t\t35: \"AF_PHONET\",\n\t\t36: \"AF_IEEE802154\",\n\t\t37: \"AF_CAIF\",\n\t\t38: \"AF_ALG\",\n\t\t39: \"AF_NFC\",\n\t\t40: \"AF_VSOCK\",\n\t\t41: \"AF_KCM\",\n\t\t42: \"AF_QIPCRTR\",\n\t\t43: \"AF_SMC\",\n\t\t44: \"AF_XDP\",\n\t}\n\tvar res string\n\tif sdName, ok := socketDomains[sd]; ok {\n\t\tres = sdName\n\t} else {\n\t\tres = strconv.Itoa(int(sd))\n\t}\n\treturn res\n}", "func (o LookupMysqlDatabaseResultOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupMysqlDatabaseResult) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job) {\n\tif s.Name == \"\" {\n\t\tif t != nil {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s-%s\", *job.Name, *tg.Name, t.Name)\n\t\t} else {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s\", *job.Name, *tg.Name)\n\t\t}\n\t}\n\n\t// Default to AddressModeAuto\n\tif s.AddressMode == \"\" {\n\t\ts.AddressMode = \"auto\"\n\t}\n\n\t// Default to OnUpdateRequireHealthy\n\tif s.OnUpdate == \"\" {\n\t\ts.OnUpdate = OnUpdateRequireHealthy\n\t}\n\n\t// Default the service provider.\n\tif s.Provider == \"\" {\n\t\ts.Provider = ServiceProviderConsul\n\t}\n\n\tif len(s.Meta) == 0 {\n\t\ts.Meta = nil\n\t}\n\n\tif len(s.CanaryMeta) == 0 {\n\t\ts.CanaryMeta = nil\n\t}\n\n\tif len(s.TaggedAddresses) == 0 {\n\t\ts.TaggedAddresses = nil\n\t}\n\n\ts.Connect.Canonicalize()\n\n\t// Canonicalize CheckRestart on Checks and merge Service.CheckRestart\n\t// into each check.\n\tfor i, check := range s.Checks {\n\t\ts.Checks[i].CheckRestart = s.CheckRestart.Merge(check.CheckRestart)\n\t\ts.Checks[i].CheckRestart.Canonicalize()\n\n\t\tif s.Checks[i].SuccessBeforePassing < 0 {\n\t\t\ts.Checks[i].SuccessBeforePassing = 0\n\t\t}\n\n\t\tif s.Checks[i].FailuresBeforeCritical < 0 {\n\t\t\ts.Checks[i].FailuresBeforeCritical = 0\n\t\t}\n\n\t\t// Inhert Service\n\t\tif s.Checks[i].OnUpdate == \"\" {\n\t\t\ts.Checks[i].OnUpdate = s.OnUpdate\n\t\t}\n\t}\n}", "func callboxHostName(dut *dut.DUT) (string, error) {\n\tdutHost := dut.HostName()\n\tif host, _, err := net.SplitHostPort(dutHost); err == nil {\n\t\tdutHost = host\n\t}\n\n\tdutHost = strings.TrimSuffix(dutHost, \".cros\")\n\tif dutHost == \"localhost\" {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, localhost not supported\", dutHost)\n\t}\n\n\tif ip := net.ParseIP(dutHost); ip != nil {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, ip:port format not supported\", dutHost)\n\t}\n\n\thostname := strings.Split(dutHost, \"-\")\n\tif len(hostname) < 2 {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, unknown name format\", dutHost)\n\t}\n\n\t// CallboxManager expects callbox hostnames to end in .cros\n\thostname = hostname[0 : len(hostname)-1]\n\treturn fmt.Sprintf(\"%s.cros\", strings.Join(hostname, \"-\")), nil\n}", "func (h *dnsHandler) getDomain(origin string) string {\n\tdomain := origin\n\n\tnamespace, find := os.LookupEnv(\"PROXY_NAMESPACE\")\n\tif !find {\n\t\tnamespace = \"default\"\n\t}\n\n\tindex := strings.Index(domain, \".\")\n\n\tif index+1 == len(domain) {\n\t\tdomain = domain + namespace + \".svc.cluster.local.\"\n\t\tlog.Info().Msgf(\"*** Use in cluster dns address %s\\n\", domain)\n\t}\n\tlog.Info().Msgf(\"Format domain %s to %s\\n\", origin, domain)\n\n\treturn domain\n}", "func shortenName(name, origin string) string {\n\tif name == origin {\n\t\treturn \"@\"\n\t}\n\treturn strings.TrimSuffix(name, \".\"+origin)\n}", "func getHostName(staxName string, nodeName string) string {\n\treturn fmt.Sprintf(\"%s-%s\", staxName, nodeName)\n}", "func canonicalizeExperimentName(name string) string {\n\tswitch name = strcase.ToSnake(name); name {\n\tcase \"ndt_7\":\n\t\tname = \"ndt\" // since 2020-03-18, we use ndt7 to implement ndt by default\n\tdefault:\n\t}\n\treturn name\n}", "func ServiceName(val string) zap.Field {\n\treturn zap.String(FieldServiceName, val)\n}", "func lookupDomainName(domainName string) string {\n\tif du, ok := domainUuid[domainName]; ok {\n\t\treturn du\n\t}\n\treturn \"\"\n}", "func getFqdnHostname(osHost string) (string, error) {\n\tips, err := lookupIp(osHost)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, ip := range ips {\n\t\thosts, err := lookupAddr(ip.String())\n\t\tif err != nil || len(hosts) == 0 {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif hosts[0] == \"localhost\" {\n\t\t\tcontinue\n\t\t}\n\t\ttrace.Hostname(\"found FQDN hosts: %s\", strings.Join(hosts, \", \"))\n\t\treturn strings.TrimSuffix(hosts[0], \".\"), nil\n\t}\n\treturn \"\", errors.New(\"can't lookup FQDN\")\n}", "func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job) {\n\tif s.Name == \"\" {\n\t\tif t != nil {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s-%s\", *job.Name, *tg.Name, t.Name)\n\t\t} else {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s\", *job.Name, *tg.Name)\n\t\t}\n\t}\n\n\t// Default to AddressModeAuto\n\tif s.AddressMode == \"\" {\n\t\ts.AddressMode = \"auto\"\n\t}\n\n\t// Canonicalize CheckRestart on Checks and merge Service.CheckRestart\n\t// into each check.\n\tfor i, check := range s.Checks {\n\t\ts.Checks[i].CheckRestart = s.CheckRestart.Merge(check.CheckRestart)\n\t\ts.Checks[i].CheckRestart.Canonicalize()\n\t}\n}", "func isDomainName(s string) bool {\n\t// See RFC 1035, RFC 3696.\n\t// Presentation format has dots before every label except the first, and the\n\t// terminal empty label is optional here because we assume fully-qualified\n\t// (absolute) input. We must therefore reserve space for the first and last\n\t// labels' length octets in wire format, where they are necessary and the\n\t// maximum total length is 255.\n\t// So our _effective_ maximum is 253, but 254 is not rejected if the last\n\t// character is a dot.\n\tl := len(s)\n\tif l == 0 || l > 254 || l == 254 && s[l-1] != '.' {\n\t\treturn false\n\t}\n\n\tlast := byte('.')\n\tnonNumeric := false // true once we've seen a letter or hyphen\n\tpartlen := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tdefault:\n\t\t\treturn false\n\t\tcase 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':\n\t\t\tnonNumeric = true\n\t\t\tpartlen++\n\t\tcase '0' <= c && c <= '9':\n\t\t\t// fine\n\t\t\tpartlen++\n\t\tcase c == '-':\n\t\t\t// Byte before dash cannot be dot.\n\t\t\tif last == '.' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen++\n\t\t\tnonNumeric = true\n\t\tcase c == '.':\n\t\t\t// Byte before dot cannot be dot, dash.\n\t\t\tif last == '.' || last == '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif partlen > 63 || partlen == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen = 0\n\t\t}\n\t\tlast = c\n\t}\n\tif last == '-' || partlen > 63 {\n\t\treturn false\n\t}\n\n\treturn nonNumeric\n}", "func (m *PrintConnector) GetFullyQualifiedDomainName()(*string) {\n val, err := m.GetBackingStore().Get(\"fullyQualifiedDomainName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func tincName(i ClusterInstance) string {\n\treturn strings.Replace(strings.Replace(i.Name, \".\", \"_\", -1), \"-\", \"_\", -1)\n}", "func Domain(named Named) string {\n\tif r, ok := named.(namedRepository); ok {\n\t\treturn r.Domain()\n\t}\n\tdomain, _ := splitDomain(named.Name())\n\treturn domain\n}", "func getWorkflowNameFromHost(host string) string {\n\tmatches := re.FindAllString(host, -1)\n\tif matches[0] != \"\" {\n\t\treturn matches[0]\n\t}\n\treturn \"\"\n}", "func cleanName(name string) string {\n\tname = strings.TrimSpace(strings.ToLower(name))\n\n\tfor {\n\t\tif i := nameStripRE.FindStringIndex(name); i != nil {\n\t\t\tname = name[i[1]:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tname = strings.Trim(name, \"-\")\n\t// Remove dots at the beginning of names\n\tif len(name) > 1 && name[0] == '.' {\n\t\tname = name[1:]\n\t}\n\treturn name\n}", "func (mts *BaseMetadataService) ServiceName() (string, error) {\n\treturn mts.serviceName, nil\n}", "func (p *plug) Name() string { return \"dnsfilter\" }", "func (internet *Internet) DomainWord() string {\n\treturn strings.ToLower(internet.cleanupDomainName(internet.faker.Company.Name()))\n}", "func (o DomainNameOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DomainName) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (internet Internet) DomainName(v reflect.Value) (interface{}, error) {\n\treturn internet.domainName()\n}", "func fallbackService(lang string) string {\n\tif lang == \"\" {\n\t\treturn DefaultServiceName\n\t}\n\tif v, ok := fallbackServiceNames.Load(lang); ok {\n\t\treturn v.(string)\n\t}\n\tvar str strings.Builder\n\tstr.WriteString(\"unnamed-\")\n\tstr.WriteString(lang)\n\tstr.WriteString(\"-service\")\n\tfallbackServiceNames.Store(lang, str.String())\n\treturn str.String()\n}", "func (o KafkaSchemaConfigurationOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaSchemaConfiguration) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func FQDN(domain, hostname, ip string) string {\n\t// in case hostname comes already with this domain suffix,\n\t// we assume that it's set by provisioner or user in on-prem\n\t// scenario, so we reuse it\n\tif strings.HasSuffix(hostname, \".\"+domain) {\n\t\treturn hostname\n\t}\n\tprefix := strings.Replace(ip, \".\", \"_\", -1)\n\treturn fmt.Sprintf(\"%v.%v\", prefix, domain)\n}", "func resolveCNAME(domain string) (string, error) {\n\tresolver := net.Resolver{}\n\treturn resolver.LookupCNAME(context.Background(), domain)\n}" ]
[ "0.73525965", "0.71070457", "0.661327", "0.6535657", "0.64382684", "0.6371256", "0.6304489", "0.6274248", "0.62092716", "0.61814994", "0.61593896", "0.61587137", "0.6156627", "0.6149207", "0.61265564", "0.6115233", "0.60776806", "0.60719866", "0.60674506", "0.60491043", "0.60491043", "0.604378", "0.6043485", "0.60315776", "0.6016418", "0.6014941", "0.6006392", "0.59320796", "0.5926976", "0.5861041", "0.58508927", "0.5833985", "0.5830812", "0.58147365", "0.58140755", "0.5805315", "0.58019155", "0.57938594", "0.57923394", "0.5786391", "0.5783201", "0.5778903", "0.57769895", "0.5769325", "0.5757237", "0.5746307", "0.5738175", "0.5720016", "0.57152843", "0.5715102", "0.5707632", "0.57074285", "0.57069725", "0.5694938", "0.56948215", "0.5694383", "0.56928813", "0.56855476", "0.5683931", "0.5670217", "0.5669341", "0.5662675", "0.5653664", "0.56365716", "0.5635373", "0.562109", "0.56122816", "0.5606815", "0.5580818", "0.55765396", "0.5573069", "0.55718297", "0.55610496", "0.55566955", "0.554976", "0.5548683", "0.55411", "0.55391514", "0.5537264", "0.5526145", "0.5522711", "0.55220735", "0.55206466", "0.5518199", "0.55116284", "0.55049515", "0.5501275", "0.54879767", "0.5487647", "0.54865503", "0.54787415", "0.5476449", "0.5466857", "0.546164", "0.5457648", "0.5457229", "0.5456812", "0.54469496", "0.5446935", "0.5441458" ]
0.7669328
0
convert canonical service name to (service, dc)
func (sd *ServiceDiscovery) ResolveName(name string) (string, string) { name = stripDomain(name) if strings.HasSuffix(name, sd.Domain) { name = name[0 : len(name)-len(sd.Domain)-1] } separator := fmt.Sprintf(".%s", serviceSuffix) var service string var dc string if strings.Contains(name, separator) { cols := strings.Split(name, separator) service, dc = cols[0], stripDomain(cols[1]) if len(dc) < 1 { dc = sd.Dc } } else { service, dc = name, sd.Dc } return service, dc }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NormalizeForServiceName(svcName string) string {\n\tre := regexp.MustCompile(\"[._]\")\n\tnewName := strings.ToLower(re.ReplaceAllString(svcName, \"-\"))\n\tif newName != svcName {\n\t\tlog.Infof(\"Changing service name to %s from %s\", svcName, newName)\n\t}\n\treturn newName\n}", "func cleanServiceName(in string) string {\n\tr := strings.NewReplacer(\n\t\t\"-\", \"_\",\n\t\t\" \", \"_\",\n\t\t\".\", \"_\",\n\t\t\"/\", \"_\",\n\t\t\"\\\\\", \"_\",\n\t)\n\n\treturn snaker.SnakeToCamel(r.Replace(in))\n}", "func (sd *ServiceDiscovery) CanonicalName(service string) string {\n\tif strings.HasSuffix(service, sd.Domain) {\n\t\treturn service\n\t}\n\treturn strings.Join([]string{service, serviceSuffix, sd.Dc, sd.Domain}, \".\")\n}", "func hostnameForService(svc string) string {\n\n\tparts := strings.Split(svc, \"/\")\n\tif len(parts) < 2 {\n\t\treturn parts[0]\n\t}\n\tif len(parts) > 2 {\n\t\tlog.Printf(\"Malformated service identifier [%s] - Hostname will be truncated\", svc)\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", parts[1], parts[0])\n\n}", "func ServiceKeyToLabel(service string) string {\n\tss := strings.Split(service, \"|\")\n\tif len(ss) != 4 {\n\t\treturn \"\"\n\t}\n\treturn ss[2]\n}", "func serviceHostname(name string) string {\n\t// TODO include datacenter in Hostname?\n\t// consul DNS uses \"redis.service.us-east-1.consul\" -> \"[<optional_tag>].<svc>.service.[<optional_datacenter>].consul\"\n\treturn fmt.Sprintf(\"%s.service.consul\", name)\n}", "func NormalizeService(svc string, lang string) (string, error) {\n\tif svc == \"\" {\n\t\treturn fallbackService(lang), ErrEmpty\n\t}\n\tvar err error\n\tif len(svc) > MaxServiceLen {\n\t\tsvc = TruncateUTF8(svc, MaxServiceLen)\n\t\terr = ErrTooLong\n\t}\n\t// We are normalizing just the tag value.\n\ts := NormalizeTagValue(svc)\n\tif s == \"\" {\n\t\treturn fallbackService(lang), ErrInvalid\n\t}\n\treturn s, err\n}", "func makeServiceName(msURL string, msOrg string, msVersion string) string {\n\n\turl := \"\"\n\tpieces := strings.SplitN(msURL, \"/\", 3)\n\tif len(pieces) >= 3 {\n\t\turl = strings.TrimSuffix(pieces[2], \"/\")\n\t\turl = strings.Replace(url, \"/\", \"-\", -1)\n\t}\n\n\tversion := \"\"\n\tvExp, err := policy.Version_Expression_Factory(msVersion)\n\tif err == nil {\n\t\tversion = fmt.Sprintf(\"%v-%v\", vExp.Get_start_version(), vExp.Get_end_version())\n\t}\n\n\treturn fmt.Sprintf(\"%v_%v_%v\", url, msOrg, version)\n\n}", "func serviceUnitName(appName types.ACName) string {\n\treturn appName.String() + \".service\"\n}", "func getServiceName(service *apiv1.Service) string {\n\treturn fmt.Sprintf(\"%s/%s\", service.Namespace, service.Name)\n}", "func parseServiceName(name string) (instance, serviceType, domain string, err error) {\n\ts := trimDot(name)\n\tl := len(s)\n\tvar ss []string\n\tfor {\n\t\tpos := strings.LastIndex(s[:l], \".\")\n\t\tif pos != -1 {\n\t\t\tss = append(ss, s[pos+1:l])\n\t\t\tl = pos\n\t\t\tif len(ss) >= 3 {\n\t\t\t\t// done\n\t\t\t\tdomain = ss[0]\n\t\t\t\tserviceType = ss[2] + \".\" + ss[1]\n\t\t\t\tinstance = s[:l]\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"illegal service instance\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func servicename(meta metav1.ObjectMeta, portname string) string {\n\tname := []string{\n\t\tmeta.Namespace,\n\t\tmeta.Name,\n\t\tportname,\n\t}\n\tif portname == \"\" {\n\t\tname = name[:2]\n\t}\n\treturn strings.Join(name, \"/\")\n}", "func parseK8sServiceName(fqdn, clusterDomain string) (watcher.ServiceID, instanceID, error) {\n\tlabels := strings.Split(fqdn, \".\")\n\tsuffix := append([]string{\"svc\"}, strings.Split(clusterDomain, \".\")...)\n\n\tif !hasSuffix(labels, suffix) {\n\t\treturn watcher.ServiceID{}, \"\", fmt.Errorf(\"name %s does not match cluster domain %s\", fqdn, clusterDomain)\n\t}\n\n\tn := len(labels)\n\tif n == 2+len(suffix) {\n\t\t// <service>.<namespace>.<suffix>\n\t\tservice := watcher.ServiceID{\n\t\t\tName: labels[0],\n\t\t\tNamespace: labels[1],\n\t\t}\n\t\treturn service, \"\", nil\n\t}\n\n\tif n == 3+len(suffix) {\n\t\t// <instance-id>.<service>.<namespace>.<suffix>\n\t\tinstanceID := labels[0]\n\t\tservice := watcher.ServiceID{\n\t\t\tName: labels[1],\n\t\t\tNamespace: labels[2],\n\t\t}\n\t\treturn service, instanceID, nil\n\t}\n\n\treturn watcher.ServiceID{}, \"\", fmt.Errorf(\"invalid k8s service %s\", fqdn)\n}", "func SplitServiceKindName(serviceName string) (string, string, error) {\n\tsn := strings.SplitN(serviceName, \"/\", 2)\n\tif len(sn) != 2 || sn[0] == \"\" || sn[1] == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"couldn't split %q into exactly two\", serviceName)\n\t}\n\n\tkind := sn[0]\n\tname := sn[1]\n\n\treturn kind, name, nil\n}", "func UConverterGetCanonicalName(arg2 string, arg3 string, arg4 *UErrorCode) (_swig_ret string)", "func (s *KubernetesServiceRegistryServicer) convertMagmaServiceNameToK8sServiceName(serviceName string) string {\n\tk8sSvcNameSuffix := strings.ReplaceAll(serviceName, \"_\", \"-\")\n\treturn fmt.Sprintf(\"%s%s\", orc8rServiceNamePrefix, k8sSvcNameSuffix)\n}", "func (s *KubernetesServiceRegistryServicer) convertK8sServiceNameToMagmaServiceName(serviceName string) string {\n\ttrimmedSvcName := strings.TrimPrefix(serviceName, orc8rServiceNamePrefix)\n\treturn strings.ReplaceAll(trimmedSvcName, \"-\", \"_\")\n}", "func extractServiceName(tag string) string {\n\tserviceName := strings.Replace(tag, watchedRegistry, \"\", 1)\n\tserviceName = strings.Replace(serviceName, \":\", \"-\", 1)\n\tserviceName = strings.Replace(serviceName, \"/\", \"\", -1)\n\treturn serviceName\n}", "func frontendNameForServicePort(service *corev1.Service, port corev1.ServicePort) string {\n\treturn fmt.Sprintf(serviceFrontendNameFormatString, stringsutil.ReplaceForwardSlashesWithDots(cluster.Name), service.Namespace, service.Name, port.Port)\n}", "func GetServiceDomainName(prefix string) (ret string) {\n\tsuffix := extractSuffix()\n\tret = prefix + suffix\n\tLogf(\"Get domain name: %s\", ret)\n\treturn\n}", "func servicePortChainName(serviceStr string, protocol string) string {\n\thash := sha256.Sum256([]byte(serviceStr + protocol))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn \"KUBE-SVC-\" + encoded[:16]\n}", "func getServiceName(vpnName string) string {\n\treturn \"openvpn-server@\" + vpnName\n}", "func (o M3DbOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *M3Db) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o KafkaConnectorOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaConnector) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func ToCanonicalName(name string) string {\n\tnameParts := strings.Split(name, \"/\")\n\t// Reverse first part. e.g., io.k8s... instead of k8s.io...\n\tif len(nameParts) > 0 && strings.Contains(nameParts[0], \".\") {\n\t\tparts := strings.Split(nameParts[0], \".\")\n\t\tfor i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {\n\t\t\tparts[i], parts[j] = parts[j], parts[i]\n\t\t}\n\t\tnameParts[0] = strings.Join(parts, \".\")\n\t}\n\treturn strings.Join(nameParts, \".\")\n}", "func getRulePrefix(service *apiv1.Service) string {\n\treturn cloudprovider.GetSecurityGroupName(service)\n}", "func NormalizePeerService(svc string) (string, error) {\n\tif svc == \"\" {\n\t\treturn \"\", nil\n\t}\n\tvar err error\n\tif len(svc) > MaxServiceLen {\n\t\tsvc = TruncateUTF8(svc, MaxServiceLen)\n\t\terr = ErrTooLong\n\t}\n\t// We are normalizing just the tag value.\n\ts := NormalizeTagValue(svc)\n\tif s == \"\" {\n\t\treturn \"\", ErrInvalid\n\t}\n\treturn s, err\n}", "func ServiceUnitName(appName types.ACName) string {\n\treturn appName.String() + \".service\"\n}", "func (o KafkaAclOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaAcl) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func backendNameForServicePort(service *corev1.Service, port corev1.ServicePort) string {\n\treturn fmt.Sprintf(serviceBackendNameFormatString, stringsutil.ReplaceForwardSlashesWithDots(cluster.Name), service.Namespace, service.Name, port.Port)\n}", "func ServiceName(instanceGroupName string) string {\n\treturn names.Sanitize(instanceGroupName)\n}", "func getManagementServiceDnsName(cluster types.NamespacedName) string {\n\treturn cluster.Name + \".\" + cluster.Namespace + \".svc.cluster.local\"\n}", "func findValidServiceName(messages []*dpb.DescriptorProto, serviceName string) string {\n\tmessageNames := make(map[string]bool)\n\n\tfor _, m := range messages {\n\t\tmessageNames[*m.Name] = true\n\t}\n\n\tvalidServiceName := serviceName\n\tctr := 0\n\tfor {\n\t\tif nameIsAlreadyTaken, _ := messageNames[validServiceName]; !nameIsAlreadyTaken {\n\t\t\treturn validServiceName\n\t\t}\n\t\tvalidServiceName = serviceName + \"Service\"\n\t\tif ctr > 0 {\n\t\t\tvalidServiceName += strconv.Itoa(ctr)\n\t\t}\n\t\tctr += 1\n\t}\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 (resolver nameResolver) ExtractServiceId(host string) string {\n\tresourceName := strings.Split(host, \".\")[0]\n\treturn strings.TrimPrefix(resourceName, resolver.resourceNamePrefix)\n}", "func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job) {\n\tif s.Name == \"\" {\n\t\tif t != nil {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s-%s\", *job.Name, *tg.Name, t.Name)\n\t\t} else {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s\", *job.Name, *tg.Name)\n\t\t}\n\t}\n\n\t// Default to AddressModeAuto\n\tif s.AddressMode == \"\" {\n\t\ts.AddressMode = \"auto\"\n\t}\n\n\t// Default to OnUpdateRequireHealthy\n\tif s.OnUpdate == \"\" {\n\t\ts.OnUpdate = OnUpdateRequireHealthy\n\t}\n\n\t// Default the service provider.\n\tif s.Provider == \"\" {\n\t\ts.Provider = ServiceProviderConsul\n\t}\n\n\tif len(s.Meta) == 0 {\n\t\ts.Meta = nil\n\t}\n\n\tif len(s.CanaryMeta) == 0 {\n\t\ts.CanaryMeta = nil\n\t}\n\n\tif len(s.TaggedAddresses) == 0 {\n\t\ts.TaggedAddresses = nil\n\t}\n\n\ts.Connect.Canonicalize()\n\n\t// Canonicalize CheckRestart on Checks and merge Service.CheckRestart\n\t// into each check.\n\tfor i, check := range s.Checks {\n\t\ts.Checks[i].CheckRestart = s.CheckRestart.Merge(check.CheckRestart)\n\t\ts.Checks[i].CheckRestart.Canonicalize()\n\n\t\tif s.Checks[i].SuccessBeforePassing < 0 {\n\t\t\ts.Checks[i].SuccessBeforePassing = 0\n\t\t}\n\n\t\tif s.Checks[i].FailuresBeforeCritical < 0 {\n\t\t\ts.Checks[i].FailuresBeforeCritical = 0\n\t\t}\n\n\t\t// Inhert Service\n\t\tif s.Checks[i].OnUpdate == \"\" {\n\t\t\ts.Checks[i].OnUpdate = s.OnUpdate\n\t\t}\n\t}\n}", "func (c *ECSDeploymentControllerImpl) ServiceToECSDeploymentId(i interface{}) (string, error) {\n\ts, _ := i.(*v1.Service)\n\tlog.Printf(\"Service update: %v\", s.Name)\n\tif len(s.OwnerReferences) == 1 && s.OwnerReferences[0].Kind == OWNERREF_KIND {\n\t\treturn s.Namespace + \"/\" + s.OwnerReferences[0].Name, nil\n\t} else {\n\t\treturn \"\", nil\n\t}\n}", "func GetLoadBalancerNameFromService(service corev1.Service) (string, error) {\n\tloadbalancerInfo := service.Status.LoadBalancer.Ingress\n\tif len(loadbalancerInfo) == 0 {\n\t\treturn \"\", NewLoadBalancerNotReadyError(service.Name)\n\t}\n\tloadbalancerHostname := loadbalancerInfo[0].Hostname\n\n\t// TODO: When expanding to GCP, update this logic\n\n\t// For ELB, the subdomain will be one of NAME-TIME or internal-NAME-TIME\n\tloadbalancerHostnameSubDomain := strings.Split(loadbalancerHostname, \".\")[0]\n\tloadbalancerHostnameSubDomainParts := strings.Split(loadbalancerHostnameSubDomain, \"-\")\n\tnumParts := len(loadbalancerHostnameSubDomainParts)\n\tif numParts == 2 {\n\t\treturn loadbalancerHostnameSubDomainParts[0], nil\n\t} else if numParts == 3 {\n\t\treturn loadbalancerHostnameSubDomainParts[1], nil\n\t} else {\n\t\treturn \"\", NewLoadBalancerNameFormatError(loadbalancerHostname)\n\t}\n}", "func (o ServiceCorrelationDescriptionOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceCorrelationDescription) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func CoordinatorServiceName(undermoonName string) string {\n\treturn fmt.Sprintf(\"%s-cd-svc\", undermoonName)\n}", "func (o LookupMysqlDatabaseResultOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupMysqlDatabaseResult) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (o KafkaMirrorMakerOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaMirrorMaker) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func parseNsAndSvc(svc string) (namespace string, service string, ok bool) {\n\tif svc == \"\" {\n\t\treturn \"\", \"\", false\n\t}\n\tif strings.Contains(svc, \":\") {\n\t\tpairs := strings.Split(svc, \":\")\n\t\tif pairs[1] == \"\" {\n\t\t\treturn \"\", \"\", false\n\t\t}\n\t\treturn pairs[0], pairs[1], true\n\t}\n\treturn \"default\", svc, true\n}", "func canonicalizeInstanceName(name string) string {\n\tix := strings.Index(name, \".\")\n\tif ix != -1 {\n\t\tname = name[:ix]\n\t}\n\treturn name\n}", "func ServiceTypeName(t string) string {\n\tres := serviceTypeNames[t]\n\tif res == \"\" {\n\t\tpanic(fmt.Sprintf(\"no nice string for Service Type %s\", t))\n\t}\n\n\treturn res\n}", "func BuildServiceDNSName(service, branch, environment, serviceNamespace string) string {\n\treturn service + \"-\" + branch + \"-\" + environment + \".\" + serviceNamespace\n}", "func TruncatedServiceName(igName string, maxLength int) string {\n\ts := names.DNSLabelSafe(igName)\n\treturn names.TruncateMD5(s, maxLength)\n}", "func ServiceNameFromNamespaceLabels(namespaceLabels map[string]string) (voyager.ServiceName, error) {\n\tserviceName, ok := namespaceLabels[voyager.ServiceNameLabel]\n\tif !ok {\n\t\treturn \"\", errors.Errorf(\"namespace is missing %q label\", voyager.ServiceNameLabel)\n\t}\n\tif serviceName == \"\" {\n\t\treturn \"\", errors.Errorf(\"label %q has empty value\", voyager.ServiceNameLabel)\n\t}\n\treturn voyager.ServiceName(serviceName), nil\n}", "func namespacedNameFrom(name string) (types.NamespacedName, error) {\n\tvar nsName types.NamespacedName\n\n\tchunks := strings.Split(name, \"/\")\n\tif len(chunks) != 2 {\n\t\treturn nsName, fmt.Errorf(\"%s is not a namespaced name\", name)\n\t}\n\n\tnsName.Namespace = chunks[0]\n\tnsName.Name = chunks[1]\n\n\treturn nsName, nil\n}", "func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job) {\n\tif s.Name == \"\" {\n\t\tif t != nil {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s-%s\", *job.Name, *tg.Name, t.Name)\n\t\t} else {\n\t\t\ts.Name = fmt.Sprintf(\"%s-%s\", *job.Name, *tg.Name)\n\t\t}\n\t}\n\n\t// Default to AddressModeAuto\n\tif s.AddressMode == \"\" {\n\t\ts.AddressMode = \"auto\"\n\t}\n\n\t// Canonicalize CheckRestart on Checks and merge Service.CheckRestart\n\t// into each check.\n\tfor i, check := range s.Checks {\n\t\ts.Checks[i].CheckRestart = s.CheckRestart.Merge(check.CheckRestart)\n\t\ts.Checks[i].CheckRestart.Canonicalize()\n\t}\n}", "func (o PgDatabaseOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PgDatabase) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func idFromName(name string) string {\n\ts := strings.Split(strings.ToLower(strings.TrimSpace(name)), \" \")\n\tns := strings.Join(s, \"-\")\n\ts = strings.Split(ns, \".\")\n\treturn strings.Join(s, \"-\")\n}", "func (o ServiceCorrelationDescriptionResponseOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceCorrelationDescriptionResponse) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (in *instance) toKubernetesName(nm string) string {\n\tfor _, exp := range []string{`^[^A-Za-z0-9]+`, `[^A-Za-z0-9-]`, `-*$`} {\n\t\tre := regexp.MustCompile(exp)\n\t\tnm = re.ReplaceAllString(nm, ``)\n\t\tif len(nm) > 63 {\n\t\t\tnm = nm[:63]\n\t\t}\n\t}\n\tif nm == \"\" {\n\t\tnm = \"undef\"\n\t}\n\treturn nm\n}", "func (o ServiceOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Service) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func serviceName(instance *v1alpha1.Nuxeo, nodeSet v1alpha1.NodeSet) string {\n\treturn instance.Name + \"-\" + nodeSet.Name + \"-service\"\n}", "func (o CassandraUserOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CassandraUser) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (k *Kit) ServiceName() string { return k.name }", "func HostToService(host string, externalApex string) (string, error) {\n\t// First, prepend a \".\" to root domain\n\texternalApex = \".\" + strings.ToLower(externalApex)\n\n\t// For safety, set host to lowercase\n\thost = strings.ToLower(host)\n\n\t// Host may contain a port, so chop it off\n\tcolonIndex := strings.Index(host, \":\")\n\tif colonIndex > -1 {\n\t\thost = host[:colonIndex]\n\t}\n\n\t// Check that host ends with subdomain\n\tif len(host) <= len(externalApex) {\n\t\treturn \"\", fmt.Errorf(\"Host is less than root domain length\")\n\t}\n\n\tsubdomainLength := len(host) - len(externalApex)\n\tif host[subdomainLength:] != externalApex {\n\t\treturn \"\", fmt.Errorf(\"Does not contain root domain\")\n\t}\n\n\t// Return subdomain\n\treturn host[:subdomainLength], nil\n}", "func (k *K8sutil) GetClientServiceNameFullDNS(clusterName, namespace string) string {\n\treturn fmt.Sprintf(\"%s.%s.svc.cluster.local\", k.GetClientServiceName(clusterName), namespace)\n}", "func kubeToIstioServiceAccount(saname string, ns string) string {\n\treturn spiffe.MustGenSpiffeURI(ns, saname)\n}", "func (o FlinkApplicationOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FlinkApplication) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func (r *Service) urlNormalized() *Service {\n\tnormalized := dcl.Copy(*r).(Service)\n\tnormalized.Name = dcl.SelfLinkToName(r.Name)\n\tnormalized.DisplayName = dcl.SelfLinkToName(r.DisplayName)\n\tnormalized.Project = dcl.SelfLinkToName(r.Project)\n\treturn &normalized\n}", "func fallbackService(lang string) string {\n\tif lang == \"\" {\n\t\treturn DefaultServiceName\n\t}\n\tif v, ok := fallbackServiceNames.Load(lang); ok {\n\t\treturn v.(string)\n\t}\n\tvar str strings.Builder\n\tstr.WriteString(\"unnamed-\")\n\tstr.WriteString(lang)\n\tstr.WriteString(\"-service\")\n\tfallbackServiceNames.Store(lang, str.String())\n\treturn str.String()\n}", "func (o KafkaSchemaConfigurationOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KafkaSchemaConfiguration) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func servicePortEndpointChainName(servicePortName string, protocol string, endpoint string) string {\n\thash := sha256.Sum256([]byte(servicePortName + protocol + endpoint))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn \"k8s-nfproxy-sep-\" + encoded[:16]\n}", "func parseName(ns []string) string {\n\treturn strings.Join(ns[len(namespacePrefix):], \"/\")\n}", "func canonicalizeExperimentName(name string) string {\n\tswitch name = strcase.ToSnake(name); name {\n\tcase \"ndt_7\":\n\t\tname = \"ndt\" // since 2020-03-18, we use ndt7 to implement ndt by default\n\tdefault:\n\t}\n\treturn name\n}", "func swaggify(name string) string {\n\tname = strings.Replace(name, \"github.com/openkruise/kruise/apis\", \"kruise\", -1)\n\tparts := strings.Split(name, \"/\")\n\thostParts := strings.Split(parts[0], \".\")\n\t// reverses something like k8s.io to io.k8s\n\tfor i, j := 0, len(hostParts)-1; i < j; i, j = i+1, j-1 {\n\t\thostParts[i], hostParts[j] = hostParts[j], hostParts[i]\n\t}\n\tparts[0] = strings.Join(hostParts, \".\")\n\treturn strings.Join(parts, \".\")\n}", "func makeRegisteredName(metric *dto.Metric, metricName string) string {\n\tname := \"\"\n\tlabels := metric.GetLabel()\n\tsort.Sort(mxd_exp.ByName(labels))\n\n\tfor _, labelPair := range labels {\n\t\tif labelPair.GetName() == mxd_exp.SERVICE_LABEL_NAME || labelPair.GetName() == \"serviceName\" {\n\t\t\tcontinue\n\t\t}\n\t\tname = fmt.Sprintf(\"%s_%s_%s\", name, labelPair.GetName(), labelPair.GetValue())\n\t}\n\tregisteredName := metricName + name\n\treturn SanitizePrometheusNames(registeredName)\n}", "func (o ContainerOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Container) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}", "func ServiceName(serviceName string) string {\n\treturn serviceNameReplacer.Replace(serviceName)\n}", "func parseServiceURL(path string) (provider, resource string) {\n\tvar (\n\t\tservicePattern *regexp.Regexp = regexp.MustCompile(`(?i)subscriptions/.+/providers/(.+?)/(.+?)$`)\n\t\tmatch []string = servicePattern.FindStringSubmatch(path)\n\t)\n\n\tprovider = \"unknown\"\n\tresource = \"unknown\"\n\n\tif len(match) > 0 {\n\t\tprovider = strings.ReplaceAll(strings.ToLower(match[1]), \"microsoft.\", \"\")\n\t\tresource = strings.ToLower(match[2])\n\t} else if _, err := regexp.Match(`(?i)subscriptions/.+/resourcegroups/?[^/]*$`, []byte(path)); err == nil {\n\t\tprovider = \"resources\"\n\t\tresource = \"groups\"\n\t}\n\n\treturn provider, resource\n}", "func GetServiceFQDN(namespace string, name string) string {\n\tclusterDomain := os.Getenv(\"CLUSTER_DOMAIN\")\n\tif clusterDomain == \"\" {\n\t\tclusterDomain = \"cluster.local\"\n\t}\n\treturn fmt.Sprintf(\n\t\t\"%s.%s.svc.%s\",\n\t\tname, namespace, clusterDomain,\n\t)\n}", "func getConceptFromService(svc *AggregateService, ctx context.Context, conceptUUID string, bookmark string) (transform.OldAggregatedConcept, string, error) {\n\tc, tid, err := svc.GetConcordedConcept(ctx, conceptUUID, bookmark)\n\tif err != nil {\n\t\treturn transform.OldAggregatedConcept{}, \"\", err\n\t}\n\told, err := transform.ToOldAggregateConcept(c)\n\tif err != nil {\n\t\treturn transform.OldAggregatedConcept{}, \"\", err\n\t}\n\tsort.Strings(old.Aliases)\n\tsort.Strings(old.FormerNames)\n\treturn old, tid, nil\n}", "func parseSystemdServices(services string) string {\n\treturn strings.TrimSpace(strings.Replace(services, \",\", \" \", -1))\n}", "func normaliseHeaderName(headerName string) string {\n\tsegments := strings.Split(headerName, \"-\")\n\tfor index, segment := range segments {\n\t\tsegments[index] = strings.Title(\n\t\t\tstrings.ToLower(segment),\n\t\t)\n\t}\n\n\treturn strings.Join(segments, \"-\")\n}", "func GetServiceKeyPrefix(c srpc.ServiceCoordinate) string {\n\treturn fmt.Sprintf(\"services/\" + c.ServicePath())\n}", "func MakeAdressStringFromIpvsService(service *ipvs.Service) string {\n\tvar adrStr string\n\tif service.Protocol != 0 {\n\t\tprotoStr := protoNumToStr(service)\n\t\tipStr := fmt.Sprintf(\"%s\", service.Address)\n\t\tvar portStr = \"\"\n\t\tif service.Port != 0 {\n\t\t\tportStr = fmt.Sprintf(\":%d\", service.Port)\n\t\t}\n\t\tadrStr = fmt.Sprintf(\"%s://%s%s\", protoStr, ipStr, portStr)\n\t} else {\n\t\tadrStr = fmt.Sprintf(\"fwmark:%d\", service.FWMark)\n\t}\n\n\treturn adrStr\n}", "func ServiceName(val string) zap.Field {\n\treturn zap.String(FieldServiceName, val)\n}", "func makeServiceDescription(serviceName string) string {\n\treturn fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, serviceName)\n}", "func tincName(i ClusterInstance) string {\n\treturn strings.Replace(strings.Replace(i.Name, \".\", \"_\", -1), \"-\", \"_\", -1)\n}", "func CanonicalCategory(cat string) string {\n\t// TODO: improve.\n\tcat = strings.Replace(cat, \" \", \"\", -1)\n\tcat = strings.Replace(cat, \",\", \"\", -1)\n\tcat = strings.Replace(cat, \"_\", \"\", -1)\n\tcat = strings.ToLower(cat)\n\treturn cat\n}", "func transformFirstName(input string) string {\n\treturn strings.Replace(toLowerAndTrim(input), \" \", \"-\", -1)\n}", "func (o HybridConnectionOutput) AppServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.AppServiceName }).(pulumi.StringOutput)\n}", "func (o ApiImportWsdlSelectorOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApiImportWsdlSelector) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func GetServiceName(entity ProjectEntity) string {\n\treturn composeutils.GetServiceName(getServicePrefix(entity), GetProjectName(entity))\n}", "func formatProcName(fullURI string) string {\n\t// remove leading `/`\n\tfullURI = fullURI[1:]\n\n\t// When meet `/{`\n\t// - replace it with `By`\n\t// - make uppercase the first char after `/{`\n\tspl := strings.Split(fullURI, \"/{\")\n\ttmp := []string{}\n\tfor i, v := range spl {\n\t\tif i != 0 {\n\t\t\tv = strings.Title(v)\n\t\t}\n\t\ttmp = append(tmp, v)\n\t}\n\tname := strings.Join(tmp, \"By\")\n\n\t// when meet `/`\n\t// - make uppercase the first char after `/`\n\t// - remove the `/`\n\tspl = strings.Split(name, \"/\")\n\ttmp = []string{}\n\tfor i, v := range spl {\n\t\tif i != 0 {\n\t\t\tv = strings.Title(v)\n\t\t}\n\t\ttmp = append(tmp, v)\n\t}\n\n\treturn strings.Join(tmp, \"\")\n}", "func decodeServicesCaveatValue(s string) ([]Service, error) {\n\tif s == \"\" {\n\t\treturn nil, ErrNoServices\n\t}\n\n\trawServices := strings.Split(s, \",\")\n\tservices := make([]Service, 0, len(rawServices))\n\tfor _, rawService := range rawServices {\n\t\tserviceInfo := strings.Split(rawService, \":\")\n\t\tif len(serviceInfo) != 2 {\n\t\t\treturn nil, ErrInvalidService\n\t\t}\n\n\t\tname, tierStr := serviceInfo[0], serviceInfo[1]\n\t\tif name == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"%w: %v\", ErrInvalidService,\n\t\t\t\t\"empty name\")\n\t\t}\n\t\ttier, err := strconv.Atoi(tierStr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: %v\", ErrInvalidService, err)\n\t\t}\n\n\t\tservices = append(services, Service{\n\t\t\tName: name,\n\t\t\tTier: ServiceTier(tier),\n\t\t})\n\t}\n\n\treturn services, nil\n}", "func svcInfo(svc v1.Service) (result string) {\n\tsvcname := svc.Name\n\tsvctype := svc.Spec.Type\n\tsvcclusterip := svc.Spec.ClusterIP\n\tports := \"\"\n\tfor _, port := range svc.Spec.Ports {\n\t\tports += fmt.Sprintf(\" %v %v/%v\", port.Name, port.Protocol, port.Port)\n\t}\n\tresult += fmt.Sprintf(\"service [%v] of type %v uses IP %v and port(s)%v\\n\", svcname, svctype, svcclusterip, ports)\n\treturn result\n}", "func ToDBName(name string) string {\n\tif v := smap.Get(name); v != \"\" {\n\t\treturn v\n\t}\n\n\tif name == \"\" {\n\t\treturn \"\"\n\t}\n\n\tvar (\n\t\tvalue = commonInitialismsReplacer.Replace(name)\n\t\tbuf = bytes.NewBufferString(\"\")\n\t\tlastCase, currCase, nextCase, nextNumber strCase\n\t)\n\n\tfor i, v := range value[:len(value)-1] {\n\t\tnextCase = strCase(value[i+1] >= 'A' && value[i+1] <= 'Z')\n\t\tnextNumber = strCase(value[i+1] >= '0' && value[i+1] <= '9')\n\n\t\tif i > 0 {\n\t\t\tif currCase == upper {\n\t\t\t\tif lastCase == upper && (nextCase == upper || nextNumber == upper) {\n\t\t\t\t\tbuf.WriteRune(v)\n\t\t\t\t} else {\n\t\t\t\t\tif value[i-1] != '_' && value[i+1] != '_' {\n\t\t\t\t\t\tbuf.WriteRune('_')\n\t\t\t\t\t}\n\t\t\t\t\tbuf.WriteRune(v)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbuf.WriteRune(v)\n\t\t\t\tif i == len(value)-2 && (nextCase == upper && nextNumber == lower) {\n\t\t\t\t\tbuf.WriteRune('_')\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tcurrCase = upper\n\t\t\tbuf.WriteRune(v)\n\t\t}\n\t\tlastCase = currCase\n\t\tcurrCase = nextCase\n\t}\n\n\tbuf.WriteByte(value[len(value)-1])\n\n\ts := strings.ToLower(buf.String())\n\tsmap.Set(name, s)\n\treturn s\n}", "func GenerateDerivedServiceName(serviceName string) string {\n\treturn fmt.Sprintf(\"%s-%s\", derivedServicePrefix, serviceName)\n}", "func ServiceName(ctx context.Context) (string, bool) {\n\tname, ok := ctx.Value(ServiceNameKey).(string)\n\treturn name, ok\n}", "func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}", "func innerServiceConvert(ksvc *gokong.Service) *register.Service {\n\tsvc := &register.Service{\n\t\tName: *ksvc.Name,\n\t\tProtocol: *ksvc.Protocol,\n\t\tHost: *ksvc.Host,\n\t\tPort: uint(*ksvc.Port),\n\t}\n\t//path will be empty when rewrite feature turns off\n\tif ksvc.Path != nil {\n\t\tsvc.Path = *ksvc.Path\n\t}\n\treturn svc\n}", "func (o LookupMirrorMakerReplicationFlowResultOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupMirrorMakerReplicationFlowResult) string { return v.ServiceName }).(pulumi.StringOutput)\n}", "func NormalizedName(s string) string {\n\treturn strings.Map(normalizedChar, s)\n}", "func getHostName(staxName string, nodeName string) string {\n\treturn fmt.Sprintf(\"%s-%s\", staxName, nodeName)\n}", "func canonicalizeSemverPrefix(s string) string {\n\treturn addSemverPrefix(removeSemverPrefix(s))\n}", "func (o GetEndpointResultOutput) ServiceName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) *string { return v.ServiceName }).(pulumi.StringPtrOutput)\n}" ]
[ "0.6761654", "0.67161447", "0.66240215", "0.6538214", "0.64352095", "0.64233994", "0.6297522", "0.62180257", "0.6172227", "0.6166578", "0.6105407", "0.60922176", "0.6058803", "0.60244125", "0.6020425", "0.60160077", "0.59808594", "0.5971854", "0.5956637", "0.5895601", "0.5892213", "0.58800936", "0.5757172", "0.568605", "0.5683168", "0.56793815", "0.566575", "0.56423324", "0.5636453", "0.56179374", "0.56165636", "0.5610186", "0.55964553", "0.5586948", "0.5585073", "0.5575019", "0.55723417", "0.5571323", "0.5566549", "0.5562502", "0.55479723", "0.5547406", "0.55238456", "0.550125", "0.54937214", "0.54936713", "0.54922837", "0.54857874", "0.54834986", "0.5480736", "0.5466907", "0.5461181", "0.54379684", "0.5433771", "0.54237366", "0.54141265", "0.54045695", "0.5392379", "0.53877395", "0.5364086", "0.53519374", "0.5336109", "0.5322237", "0.53187996", "0.53186226", "0.5306554", "0.52997863", "0.52962095", "0.5289359", "0.5271161", "0.526569", "0.52508205", "0.5243179", "0.5241648", "0.5240204", "0.5228721", "0.5218759", "0.5205999", "0.5203881", "0.5199306", "0.51860136", "0.51777965", "0.5170321", "0.516786", "0.51658624", "0.51631063", "0.5157206", "0.5153418", "0.51526654", "0.51507884", "0.5150217", "0.5147734", "0.51459205", "0.514544", "0.51402384", "0.51364", "0.51311445", "0.5126708", "0.5124721", "0.51245767" ]
0.5368005
59
/ WARN: use weak consistency causes stale read unless explicitly specific otherwise (values: 'default', 'consistent' or 'stale') 'default': R/W goes to leader without quorum verification of leadership 'consistency': R/W goes to leader with quorum verification of leadership (extra RTT) 'stale': R goes to any server, W goes to leader
func (sd *ServiceDiscovery) lookupInternal(name, consistency string) ([]*Endpoint, error) { service, dc := sd.ResolveName(name) opts := &QueryOptions{ dc, consistency == weakConsistency, consistency == strongConsistency, 0, 0, "", } entries, _, err := sd.Client.Health().Service(service, "", true, opts) if err != nil { return nil, err } result := make([]*Endpoint, len(entries)) i := 0 for _, entry := range entries { result[i] = loadServiceNode(entry) i++ } return result, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestReadOnlyForNewLeader(t *testing.T) {\n\tnodeConfigs := []struct {\n\t\tid uint64\n\t\tcommitted uint64\n\t\tapplied uint64\n\t\tcompact_index uint64\n\t}{\n\t\t{1, 1, 1, 0},\n\t\t{2, 2, 2, 2},\n\t\t{3, 2, 2, 2},\n\t}\n\tpeers := make([]stateMachine, 0)\n\tfor _, c := range nodeConfigs {\n\t\tstorage := NewMemoryStorage()\n\t\tdefer storage.Close()\n\t\tstorage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})\n\t\tstorage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})\n\t\tif c.compact_index != 0 {\n\t\t\tstorage.Compact(c.compact_index)\n\t\t}\n\t\tcfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)\n\t\tcfg.Applied = c.applied\n\t\traft := newRaft(cfg)\n\t\tpeers = append(peers, raft)\n\t}\n\tnt := newNetwork(peers...)\n\n\t// Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.\n\tnt.ignore(pb.MsgApp)\n\t// Force peer a to become leader.\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tsm := nt.peers[1].(*raft)\n\tif sm.state != StateLeader {\n\t\tt.Fatalf(\"state = %s, want %s\", sm.state, StateLeader)\n\t}\n\n\t// Ensure peer a drops read only request.\n\tvar windex uint64 = 4\n\twctx := []byte(\"ctx\")\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})\n\tif len(sm.readStates) != 0 {\n\t\tt.Fatalf(\"len(readStates) = %d, want zero\", len(sm.readStates))\n\t}\n\n\tnt.recover()\n\n\t// Force peer a to commit a log entry at its term\n\tfor i := 0; i < sm.heartbeatTimeout; i++ {\n\t\tsm.tick()\n\t}\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})\n\tif sm.raftLog.committed != 4 {\n\t\tt.Fatalf(\"committed = %d, want 4\", sm.raftLog.committed)\n\t}\n\tlastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))\n\tif lastLogTerm != sm.Term {\n\t\tt.Fatalf(\"last log term = %d, want %d\", lastLogTerm, sm.Term)\n\t}\n\n\t// Ensure peer a accepts read only request after it commits a entry at its term.\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})\n\tif len(sm.readStates) != 1 {\n\t\tt.Fatalf(\"len(readStates) = %d, want 1\", len(sm.readStates))\n\t}\n\trs := sm.readStates[0]\n\tif rs.Index != windex {\n\t\tt.Fatalf(\"readIndex = %d, want %d\", rs.Index, windex)\n\t}\n\tif !bytes.Equal(rs.RequestCtx, wctx) {\n\t\tt.Fatalf(\"requestCtx = %v, want %v\", rs.RequestCtx, wctx)\n\t}\n}", "func (s *Server) consistentRead() error {\n\tdefer metrics.MeasureSince([]string{\"rpc\", \"consistentRead\"}, time.Now())\n\tfuture := s.raft.VerifyLeader()\n\tif err := future.Error(); err != nil {\n\t\treturn err //fail fast if leader verification fails\n\t}\n\t// poll consistent read readiness, wait for up to RPCHoldTimeout milliseconds\n\tif s.isReadyForConsistentReads() {\n\t\treturn nil\n\t}\n\tjitter := lib.RandomStagger(s.config.RPCHoldTimeout / jitterFraction)\n\tdeadline := time.Now().Add(s.config.RPCHoldTimeout)\n\n\tfor time.Now().Before(deadline) {\n\n\t\tselect {\n\t\tcase <-time.After(jitter):\n\t\t\t// Drop through and check before we loop again.\n\n\t\tcase <-s.shutdownCh:\n\t\t\treturn fmt.Errorf(\"shutdown waiting for leader\")\n\t\t}\n\n\t\tif s.isReadyForConsistentReads() {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn structs.ErrNotReadyForConsistentReads\n}", "func (psm *ProtocolStateMachine) read(req readRequest) {\n\tif psm.debug && psm.l() {\n\t\tpsm.logger.Debug(\"incoming read request\")\n\t}\n\t// shortcut: ConsistencyStale\n\tif psm.state.Consistency == ConsistencyStale {\n\t\t// note: read shouldn't even be called in the first place\n\t\tpsm.endPendingRead(psm.state.Read.TID)\n\t\treturn\n\t}\n\n\t// read request must go through leader\n\tif psm.state.Leader == 0 {\n\t\tif psm.l() {\n\t\t\tpsm.logger.Info(\"read to no leader\")\n\t\t}\n\t\treturn\n\t}\n\n\tif psm.state.Role == RoleLeader {\n\t\t// service read directly\n\t\tswitch psm.state.Consistency {\n\t\tcase ConsistencyStrict:\n\t\t\t// ping everyone\n\t\t\tpsm.state.Read.TID++\n\t\t\tpsm.state.Read.Acks = 1\n\t\t\tpsm.state.Read.Index = psm.state.Commit\n\t\t\t// shortcut: 1-node cluster\n\t\t\tif psm.state.QuorumSize == 1 {\n\t\t\t\tpsm.endPendingRead(psm.state.Read.TID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpsm.heartbeatRead(psm.state.Read.TID, psm.state.ID)\n\t\tcase ConsistencyLease:\n\t\t\t// shortcut: 1-node cluster\n\t\t\tif psm.state.QuorumSize == 1 {\n\t\t\t\tpsm.state.Read.Index = psm.state.Commit\n\t\t\t\tpsm.endPendingRead(psm.state.Read.TID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// service the read if within lease timeout\n\t\t\tif req.unixNano <= psm.state.Lease.Timeout {\n\t\t\t\tpsm.state.Read.TID = req.unixNano\n\t\t\t\tpsm.endPendingRead(psm.state.Read.TID)\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"\")\n\t\t}\n\t} else {\n\t\t// send read request to leader\n\t\tswitch psm.state.Consistency {\n\t\tcase ConsistencyStrict:\n\t\t\tpsm.state.Read.TID++\n\t\tcase ConsistencyLease:\n\t\t\tpsm.state.Read.TID = req.unixNano\n\t\tdefault:\n\t\t\tpanic(\"\")\n\t\t}\n\t\tpsm.sendChan <- buildRead(\n\t\t\tpsm.state.Term, psm.state.ID, psm.state.Leader,\n\t\t\tpsm.state.Read.TID)\n\t}\n}", "func (e *ClusterElector) appropriate() error {\n\texist, _, err := e.zkConn.Exists(e.zkLeaderPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif exist {\n\t\t_, err := e.zkConn.Set(e.zkLeaderPath, []byte(strconv.FormatUint(e.id, 10)), -1)\n\t\treturn err\n\t}\n\n\treturn e.ascend()\n}", "func BenchmarkRead_NoReplica(b *testing.B) {\n\tvar listen string = fmt.Sprintf(\"localhost:%d\", i)\n\ti++\n\ttrans, err := InitTCPTransport(listen, timeout)\n\tif err != nil {\n\t\tfmt.Println(\"TCP Transport err : \", err)\n\t}\n\tvar conf *Config = fastConf()\n\tr, _ := Create(conf, trans)\n\tlm := &LManagerClient{Ring: r, RLocks: make(map[string]*RLockVal), WLocks: make(map[string]*WLockVal)}\n\tversion, _ := lm.WLock(TEST_KEY, 1, 10)\n\t_ = lm.CommitWLock(TEST_KEY, version)\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = lm.RLock(TEST_KEY, true)\n\t}\n\tr.Shutdown()\n}", "func TestLeaderTransferWithCheckQuorum(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tfor i := 1; i < 4; i++ {\n\t\tr := nt.peers[uint64(i)].(*raft)\n\t\tr.checkQuorum = true\n\t\tsetRandomizedElectionTimeout(r, r.electionTimeout+i)\n\t}\n\n\t// Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1\n\tf := nt.peers[2].(*raft)\n\tfor i := 0; i < f.electionTimeout; i++ {\n\t\tf.tick()\n\t}\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tlead := nt.peers[1].(*raft)\n\n\tif lead.lead != 1 {\n\t\tt.Fatalf(\"after election leader is %x, want 1\", lead.lead)\n\t}\n\n\t// Transfer leadership to 2.\n\tnt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateFollower, 2)\n\n\t// After some log replication, transfer leadership back to 1.\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})\n\n\tnt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateLeader, 1)\n}", "func leaderElection(nodeCtx *NodeCtx) {\n\t// The paper doesnt specifically mention any leader election protocols, so we assume that the leader election protocol\n\t// used in bootstrap is also used in the normal protocol, with the adition of iteration (unless the same leader would\n\t// be selected).\n\n\t// TODO actually add a setup phase where one must publish their hash. This way there will always\n\t// be a leader even if some nodes are offline. But with the assumption that every node is online\n\t// this works fine.\n\n\t// get current randomness\n\trecBlock := nodeCtx.blockchain.getLastReconfigurationBlock()\n\trnd := recBlock.Randomness\n\n\t// get current iteration\n\t_currIteration := nodeCtx.i.getI()\n\tcurrI := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(currI, uint64(_currIteration))\n\n\tlistOfHashes := make([]byte32sortHelper, len(nodeCtx.committee.Members))\n\t// calculate hash(id | rnd | currI) for every member\n\tii := 0\n\tfor _, m := range nodeCtx.committee.Members {\n\t\tconnoctated := byteSliceAppend(m.Pub.Bytes[:], rnd[:], currI)\n\t\thsh := hash(connoctated)\n\t\tlistOfHashes[ii] = byte32sortHelper{m.Pub.Bytes, hsh}\n\t\tii++\n\t}\n\n\t// sort list\n\tlistOfHashes = sortListOfByte32SortHelper(listOfHashes)\n\n\t// calculate hash of self\n\tselfHash := hash(byteSliceAppend(nodeCtx.self.Priv.Pub.Bytes[:], rnd[:], currI))\n\t// fmt.Println(\"self: \", bytes32ToString(selfHash), bytes32ToString(nodeCtx.self.Priv.Pub.Bytes))\n\t// for i, lof := range listOfHashes {\n\t// \tfmt.Println(i, bytes32ToString(lof.toSort), bytes32ToString(lof.original))\n\t// }\n\n\t// the leader is the lowest in list except if selfHash is lower than that.\n\t// fmt.Println(byte32Operations(selfHash, \"<\", listOfHashes[0].toSort))\n\tif byte32Operations(selfHash, \"<\", listOfHashes[0].toSort) {\n\t\tnodeCtx.committee.CurrentLeader = nodeCtx.self.Priv.Pub\n\t\tlog.Println(\"I am leader!\", nodeCtx.amILeader())\n\t} else {\n\t\tleader := listOfHashes[0].original\n\t\tnodeCtx.committee.CurrentLeader = nodeCtx.committee.Members[leader].Pub\n\t}\n}", "func TestClusteringFollowerDeleteOldChannelPriorToSnapshotRestore(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\trestoreMsgsAttempts = 2\n\trestoreMsgsRcvTimeout = 50 * time.Millisecond\n\trestoreMsgsSleepBetweenAttempts = 0\n\tdefer func() {\n\t\trestoreMsgsAttempts = defaultRestoreMsgsAttempts\n\t\trestoreMsgsRcvTimeout = defaultRestoreMsgsRcvTimeout\n\t\trestoreMsgsSleepBetweenAttempts = defaultRestoreMsgsSleepBetweenAttempts\n\t}()\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\tmaxInactivity := 250 * time.Millisecond\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1sOpts.Clustering.TrailingLogs = 0\n\ts1sOpts.MaxInactivity = maxInactivity\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2sOpts.Clustering.TrailingLogs = 0\n\ts2sOpts.MaxInactivity = maxInactivity\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3sOpts.Clustering.TrailingLogs = 0\n\ts3sOpts.MaxInactivity = maxInactivity\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\n\t// Wait for leader to be elected.\n\tleader := getLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Send a message, which will create the channel\n\tchannel := \"foo\"\n\texpectedMsg := make(map[uint64]msg)\n\texpectedMsg[1] = msg{sequence: 1, data: []byte(\"1\")}\n\texpectedMsg[2] = msg{sequence: 2, data: []byte(\"2\")}\n\texpectedMsg[3] = msg{sequence: 3, data: []byte(\"3\")}\n\tfor i := 1; i < 4; i++ {\n\t\tif err := sc.Publish(channel, expectedMsg[uint64(i)].data); err != nil {\n\t\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t\t}\n\t}\n\t// Wait for channel to be replicated in all servers\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 3, expectedMsg, servers...)\n\n\t// Shutdown a follower\n\tvar follower *StanServer\n\tfor _, s := range servers {\n\t\tif leader != s {\n\t\t\tfollower = s\n\t\t\tbreak\n\t\t}\n\t}\n\tservers = removeServer(servers, follower)\n\tfollower.Shutdown()\n\n\t// Let the channel be deleted\n\ttime.Sleep(2 * maxInactivity)\n\n\t// Now send a message that causes the channel to be recreated\n\texpectedMsg = make(map[uint64]msg)\n\texpectedMsg[1] = msg{sequence: 1, data: []byte(\"4\")}\n\tif err := sc.Publish(channel, expectedMsg[1].data); err != nil {\n\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t}\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 1, expectedMsg, servers...)\n\n\t// Perform snapshot on the leader.\n\tif err := leader.raft.Snapshot().Error(); err != nil {\n\t\tt.Fatalf(\"Error during snapshot: %v\", err)\n\t}\n\n\t// Now send another message then a sub to prevent deletion\n\texpectedMsg[2] = msg{sequence: 2, data: []byte(\"5\")}\n\tif err := sc.Publish(channel, expectedMsg[2].data); err != nil {\n\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t}\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 2, expectedMsg, servers...)\n\tsc.Subscribe(channel, func(_ *stan.Msg) {}, stan.DeliverAllAvailable())\n\n\t// Now restart the follower...\n\tfollower = runServerWithOpts(t, follower.opts, nil)\n\tdefer follower.Shutdown()\n\tservers = append(servers, follower)\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Now check content of channel on the follower.\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 2, expectedMsg, follower)\n}", "func TestRaftVerifyRead(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tclusterPrefix := \"TestRaftVerifyRead\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tn1 := testCreateRaftNode(getTestConfig(ID1, clusterPrefix+ID1), newStorage())\n\t// Create n2 node.\n\tfsm2 := newTestFSM(ID2)\n\tn2 := testCreateRaftNode(getTestConfig(ID2, clusterPrefix+ID2), newStorage())\n\tconnectAllNodes(n1, n2)\n\tn1.transport = NewMsgDropper(n1.transport, 193, 0)\n\tn2.transport = NewMsgDropper(n2.transport, 42, 0)\n\tn1.Start(fsm1)\n\tn2.Start(fsm2)\n\tn2.ProposeInitialMembership([]string{ID1, ID2})\n\n\t// Find out who leader is.\n\tvar leader *Raft\n\tvar follower *Raft\n\tselect {\n\tcase <-fsm1.leaderCh:\n\t\tleader = n1\n\t\tfollower = n2\n\tcase <-fsm2.leaderCh:\n\t\tleader = n2\n\t\tfollower = n1\n\t}\n\n\t// Verification on leader side should succeed.\n\tpending1 := leader.VerifyRead()\n\tpending2 := leader.VerifyRead()\n\t<-pending1.Done\n\t<-pending2.Done\n\tif pending1.Err != nil || pending2.Err != nil {\n\t\tt.Fatalf(\"VerifyRead on leader should succeed\")\n\t}\n\n\t// A new round.\n\tpending3 := leader.VerifyRead()\n\t<-pending3.Done\n\tif pending3.Err != nil {\n\t\tt.Fatalf(\"VerifyRead on leader should succeed\")\n\t}\n\n\t// Verification on follower side should fail.\n\tpending4 := follower.VerifyRead()\n\t<-pending4.Done\n\tif pending4.Err == nil {\n\t\tt.Fatalf(\"VerifyRead on follower should fail\")\n\t}\n\n\t// Create a network partition between \"1\" and \"2\"\n\tn1.transport.(*msgDropper).Set(ID2, 1)\n\tn2.transport.(*msgDropper).Set(ID1, 1)\n\n\t// Now there's a network partition between \"1\" and \"2\", verification should\n\t// either timeout or fail.\n\tpending1 = leader.VerifyRead()\n\tselect {\n\tcase <-pending1.Done:\n\t\tif pending1.Err == nil {\n\t\t\tlog.Fatalf(\"expected the verification to be timeout or failed in the case of partition\")\n\t\t}\n\tcase <-time.After(100 * time.Millisecond):\n\t}\n}", "func TestLearnerLogReplication(t *testing.T) {\n\tn1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())\n\tn2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(n1)\n\tdefer closeAndFreeRaft(n2)\n\n\tnt := newNetwork(n1, n2)\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\n\tsetRandomizedElectionTimeout(n1, n1.electionTimeout)\n\tfor i := 0; i < n1.electionTimeout; i++ {\n\t\tn1.tick()\n\t}\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})\n\n\t// n1 is leader and n2 is learner\n\tif n1.state != StateLeader {\n\t\tt.Errorf(\"peer 1 state: %s, want %s\", n1.state, StateLeader)\n\t}\n\tif !n2.isLearner {\n\t\tt.Error(\"peer 2 state: not learner, want yes\")\n\t}\n\n\tnextCommitted := n1.raftLog.committed + 1\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte(\"somedata\")}}})\n\tif n1.raftLog.committed != nextCommitted {\n\t\tt.Errorf(\"peer 1 wants committed to %d, but still %d\", nextCommitted, n1.raftLog.committed)\n\t}\n\n\tif n1.raftLog.committed != n2.raftLog.committed {\n\t\tt.Errorf(\"peer 2 wants committed to %d, but still %d\", n1.raftLog.committed, n2.raftLog.committed)\n\t}\n\n\tmatch := n1.getProgress(2).Match\n\tif match != n2.raftLog.committed {\n\t\tt.Errorf(\"progress 2 of leader 1 wants match %d, but got %d\", n2.raftLog.committed, match)\n\t}\n}", "func TestFreeStuckCandidateWithCheckQuorum(t *testing.T) {\n\ta := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tb := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tc := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(a)\n\tdefer closeAndFreeRaft(b)\n\tdefer closeAndFreeRaft(c)\n\n\ta.checkQuorum = true\n\tb.checkQuorum = true\n\tc.checkQuorum = true\n\n\tnt := newNetwork(a, b, c)\n\tsetRandomizedElectionTimeout(b, b.electionTimeout+1)\n\n\tfor i := 0; i < b.electionTimeout; i++ {\n\t\tb.tick()\n\t}\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tnt.isolate(1)\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\n\tif b.state != StateFollower {\n\t\tt.Errorf(\"state = %s, want %s\", b.state, StateFollower)\n\t}\n\n\tif c.state != StateCandidate {\n\t\tt.Errorf(\"state = %s, want %s\", c.state, StateCandidate)\n\t}\n\n\tif c.Term != b.Term+1 {\n\t\tt.Errorf(\"term = %d, want %d\", c.Term, b.Term+1)\n\t}\n\n\t// Vote again for safety\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\n\tif b.state != StateFollower {\n\t\tt.Errorf(\"state = %s, want %s\", b.state, StateFollower)\n\t}\n\n\tif c.state != StateCandidate {\n\t\tt.Errorf(\"state = %s, want %s\", c.state, StateCandidate)\n\t}\n\n\tif c.Term != b.Term+2 {\n\t\tt.Errorf(\"term = %d, want %d\", c.Term, b.Term+2)\n\t}\n\n\tnt.recover()\n\tnt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: a.Term})\n\n\t// Disrupt the leader so that the stuck peer is freed\n\tif a.state != StateFollower {\n\t\tt.Errorf(\"state = %s, want %s\", a.state, StateFollower)\n\t}\n\n\tif c.Term != a.Term {\n\t\tt.Errorf(\"term = %d, want %d\", c.Term, a.Term)\n\t}\n\n\t// Vote again, should become leader this time\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\n\tif c.state != StateLeader {\n\t\tt.Errorf(\"peer 3 state: %s, want %s\", c.state, StateLeader)\n\t}\n\n}", "func TestLearnerPromotion(t *testing.T) {\n\tn1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())\n\tn2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(n1)\n\tdefer closeAndFreeRaft(n2)\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\n\tnt := newNetwork(n1, n2)\n\n\tif n1.state == StateLeader {\n\t\tt.Error(\"peer 1 state is leader, want not\", n1.state)\n\t}\n\n\t// n1 should become leader\n\tsetRandomizedElectionTimeout(n1, n1.electionTimeout)\n\tfor i := 0; i < n1.electionTimeout; i++ {\n\t\tn1.tick()\n\t}\n\n\tif n1.state != StateLeader {\n\t\tt.Errorf(\"peer 1 state: %s, want %s\", n1.state, StateLeader)\n\t}\n\tif n2.state != StateFollower {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", n2.state, StateFollower)\n\t}\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})\n\tgrp2 := pb.Group{\n\t\tNodeId: 2,\n\t\tGroupId: 1,\n\t\tRaftReplicaId: 2,\n\t}\n\tn1.addNode(2, grp2)\n\tn2.addNode(2, grp2)\n\tif n2.isLearner {\n\t\tt.Error(\"peer 2 is learner, want not\")\n\t}\n\n\t// n2 start election, should become leader\n\tsetRandomizedElectionTimeout(n2, n2.electionTimeout)\n\tfor i := 0; i < n2.electionTimeout; i++ {\n\t\tn2.tick()\n\t}\n\n\tnt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})\n\n\tif n1.state != StateFollower {\n\t\tt.Errorf(\"peer 1 state: %s, want %s\", n1.state, StateFollower)\n\t}\n\tif n2.state != StateLeader {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", n2.state, StateLeader)\n\t}\n}", "func TestRaftFreesReadOnlyMem(t *testing.T) {\n\tsm := newTestRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(sm)\n\tsm.becomeCandidate()\n\tsm.becomeLeader()\n\tsm.raftLog.commitTo(sm.raftLog.lastIndex())\n\n\tctx := []byte(\"ctx\")\n\n\t// leader starts linearizable read request.\n\t// more info: raft dissertation 6.4, step 2.\n\tsm.Step(pb.Message{From: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})\n\tmsgs := sm.readMessages()\n\tif len(msgs) != 1 {\n\t\tt.Fatalf(\"len(msgs) = %d, want 1\", len(msgs))\n\t}\n\tif msgs[0].Type != pb.MsgHeartbeat {\n\t\tt.Fatalf(\"type = %v, want MsgHeartbeat\", msgs[0].Type)\n\t}\n\tif !bytes.Equal(msgs[0].Context, ctx) {\n\t\tt.Fatalf(\"Context = %v, want %v\", msgs[0].Context, ctx)\n\t}\n\tif len(sm.readOnly.readIndexQueue) != 1 {\n\t\tt.Fatalf(\"len(readIndexQueue) = %v, want 1\", len(sm.readOnly.readIndexQueue))\n\t}\n\tif len(sm.readOnly.pendingReadIndex) != 1 {\n\t\tt.Fatalf(\"len(pendingReadIndex) = %v, want 1\", len(sm.readOnly.pendingReadIndex))\n\t}\n\tif _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; !ok {\n\t\tt.Fatalf(\"can't find context %v in pendingReadIndex \", ctx)\n\t}\n\n\t// heartbeat responses from majority of followers (1 in this case)\n\t// acknowledge the authority of the leader.\n\t// more info: raft dissertation 6.4, step 3.\n\tsm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Context: ctx})\n\tif len(sm.readOnly.readIndexQueue) != 0 {\n\t\tt.Fatalf(\"len(readIndexQueue) = %v, want 0\", len(sm.readOnly.readIndexQueue))\n\t}\n\tif len(sm.readOnly.pendingReadIndex) != 0 {\n\t\tt.Fatalf(\"len(pendingReadIndex) = %v, want 0\", len(sm.readOnly.pendingReadIndex))\n\t}\n\tif _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; ok {\n\t\tt.Fatalf(\"found context %v in pendingReadIndex, want none\", ctx)\n\t}\n}", "func (le *LeaderElector) adjustLeadership() {\n\t//Try to regain leadership if this is the server with highest rank\n\t//or discover server with highest rank\n\tle.Lock()\n\tle.adjustingLead = true\n\tle.CurrentLeader = \"\"\n\tle.LeaderSID = NO_LEADER\n\tle.Unlock()\n\t<-time.After(le.RegainLeadFreq * time.Second)\n\tdebug(\"[*] Info : LeaderElector : Adjusting LeaderShip Election Started.\")\n\tle.initElection()\n\tle.Lock()\n\tle.adjustingLead = false\n\tle.Unlock()\n}", "func (kv *KVServer) Get(args *GetArgs, reply *GetReply) {\n\t//DPrintf(\"[GET Request get]From Client %d (Request %d) To Server %d\",args.ClientId,args.RequestId, kv.me)\n\tif kv.killed() {\n\t\treply.Err = ErrWrongLeader\n\t\treturn\n\t}\n\n\t_, ifLeader := kv.rf.GetState()\n\tif !ifLeader {\n\t\treply.Err = ErrWrongLeader\n\t\t//DPrintf(\"[GET SendToWrongLeader]From Client %d (Request %d) To Server %d\",args.ClientId,args.RequestId, kv.me)\n\t\treturn\n\t}\n\n\top := Op{Operation: \"get\", Key: args.Key, Value: \"\", ClientId: args.ClientId, RequestId: args.RequestId}\n\n\traftIndex, _, _ := kv.rf.Start(op)\n\tDPrintf(\"[GET StartToRaft]From Client %d (Request %d) To Server %d, key %v, raftIndex %d\",args.ClientId,args.RequestId, kv.me, op.Key, raftIndex)\n\n\t// create waitForCh\n\tkv.mu.Lock()\n\tchForRaftIndex, exist := kv.waitApplyCh[raftIndex]\n\tif !exist {\n\t\tkv.waitApplyCh[raftIndex] = make(chan Op, 1)\n\t\tchForRaftIndex = kv.waitApplyCh[raftIndex]\n\t}\n\tkv.mu.Unlock()\n\t// timeout\n\tselect {\n\tcase <- time.After(time.Millisecond*CONSENSUS_TIMEOUT) :\n\t\tDPrintf(\"[GET TIMEOUT!!!]From Client %d (Request %d) To Server %d, key %v, raftIndex %d\",args.ClientId,args.RequestId, kv.me, op.Key, raftIndex)\n\n\t\t_,ifLeader := kv.rf.GetState()\n\t\tif kv.ifRequestDuplicate(op.ClientId, op.RequestId) && ifLeader{\n\t\t\tvalue, exist := kv.ExecuteGetOpOnKVDB(op)\n\t\t\tif exist {\n\t\t\t\treply.Err = OK\n\t\t\t\treply.Value = value\n\t\t\t} else {\n\t\t\t\treply.Err = ErrNoKey\n\t\t\t\treply.Value = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\treply.Err = ErrWrongLeader\n\t\t}\n\n\t\tcase raftCommitOp := <-chForRaftIndex:\n\t\t\tDPrintf(\"[WaitChanGetRaftApplyMessage<--]Server %d , get Command <-- Index:%d , ClientId %d, RequestId %d, Opreation %v, Key :%v, Value :%v\",kv.me, raftIndex, op.ClientId, op.RequestId, op.Operation, op.Key, op.Value)\n\t\t\tif raftCommitOp.ClientId == op.ClientId && raftCommitOp.RequestId == op.RequestId {\n\t\t\t\tvalue, exist := kv.ExecuteGetOpOnKVDB(op)\n\t\t\t\tif exist {\n\t\t\t\t\treply.Err = OK\n\t\t\t\t\treply.Value = value\n\t\t\t\t} else {\n\t\t\t\t\treply.Err = ErrNoKey\n\t\t\t\t\treply.Value = \"\"\n\t\t\t\t}\n\t\t\t} else{\n\t\t\t\treply.Err = ErrWrongLeader\n\t\t\t}\n\n\t}\n\n\tkv.mu.Lock()\n\tdelete(kv.waitApplyCh, raftIndex)\n\tkv.mu.Unlock()\n\treturn\n\n}", "func (w *Worker) staleClient(authority string, timeout uint) {\n time.Sleep(int64(timeout) * 1e9)\n w.cl_lk.Lock()\n w.clients[authority].Close()\n w.clients[authority] = nil, false\n w.cl_lk.Unlock()\n}", "func TestRaftNetworkPartition(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tID3 := \"3\"\n\tclusterPrefix := \"TestRaftNetworkPartition\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tcfg := getTestConfig(ID1, clusterPrefix+ID1)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn1 := testCreateRaftNode(cfg, newStorage())\n\n\t// Create n2 node.\n\tfsm2 := newTestFSM(ID2)\n\tcfg = getTestConfig(ID2, clusterPrefix+ID2)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn2 := testCreateRaftNode(cfg, newStorage())\n\n\t// Create n3 node.\n\tfsm3 := newTestFSM(ID3)\n\tcfg = getTestConfig(ID3, clusterPrefix+ID3)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn3 := testCreateRaftNode(cfg, newStorage())\n\n\tconnectAllNodes(n1, n2, n3)\n\tn1.transport = NewMsgDropper(n1.transport, 193, 0)\n\tn2.transport = NewMsgDropper(n2.transport, 42, 0)\n\tn3.transport = NewMsgDropper(n3.transport, 111, 0)\n\n\tn1.Start(fsm1)\n\tn2.Start(fsm2)\n\tn3.Start(fsm3)\n\tn3.ProposeInitialMembership([]string{ID1, ID2, ID3})\n\n\t// Find out who leader is.\n\tvar leader *Raft\n\tvar follower1, follower2 *Raft\n\tselect {\n\tcase <-fsm1.leaderCh:\n\t\tleader = n1\n\t\tfollower1 = n2\n\t\tfollower2 = n3\n\tcase <-fsm2.leaderCh:\n\t\tleader = n2\n\t\tfollower1 = n1\n\t\tfollower2 = n3\n\tcase <-fsm3.leaderCh:\n\t\tleader = n3\n\t\tfollower1 = n1\n\t\tfollower2 = n2\n\t}\n\n\t// Propose a command on the leader.\n\tpending := leader.Propose([]byte(\"I'm data1\"))\n\t<-pending.Done\n\tif pending.Err != nil {\n\t\tt.Fatalf(\"Failed to propose command on leader side: %v\", pending.Err)\n\t}\n\n\t// Isolate the leader with follower1.\n\tleader.transport.(*msgDropper).Set(follower1.config.ID, 1)\n\tfollower1.transport.(*msgDropper).Set(leader.config.ID, 1)\n\t// Isolate the leader with follower2.\n\tleader.transport.(*msgDropper).Set(follower2.config.ID, 1)\n\tfollower2.transport.(*msgDropper).Set(leader.config.ID, 1)\n\n\t// Propose a second command on the partitioned leader.\n\tpending = leader.Propose([]byte(\"I'm data2\"))\n\n\t// Wait a new leader gets elected on the other side of the partition.\n\tvar newLeader *Raft\n\tselect {\n\tcase <-follower1.fsm.(*testFSM).leaderCh:\n\t\tnewLeader = follower1\n\tcase <-follower2.fsm.(*testFSM).leaderCh:\n\t\tnewLeader = follower2\n\t}\n\n\t// The partitioned leader should step down at some point and conclude the\n\t// command proposed after the network partition with 'ErrNotLeaderAnymore'.\n\t<-pending.Done\n\tif pending.Err != ErrNotLeaderAnymore {\n\t\tt.Fatalf(\"expected 'ErrNotLeaderAnymore' for the command proposed on partitioned leader\")\n\t}\n\n\t// Propose a new command on the newly elected leader, it should succeed.\n\tpending = newLeader.Propose([]byte(\"I'm data3\"))\n\t<-pending.Done\n\tif pending.Err != nil {\n\t\tt.Fatalf(\"Failed to propose on new leader side: %v\", pending.Err)\n\t}\n\n\t// Reconnect old leader and previous follower 1.\n\tleader.transport.(*msgDropper).Set(follower1.config.ID, 0)\n\tfollower1.transport.(*msgDropper).Set(leader.config.ID, 0)\n\t// Reconnect old leader and previous follower 2.\n\tleader.transport.(*msgDropper).Set(follower2.config.ID, 0)\n\tfollower2.transport.(*msgDropper).Set(leader.config.ID, 0)\n\n\t// At some point the old leader should join the new quorum and gets synced\n\t// from the new leader.\n\ttestEntriesEqual(\n\t\tleader.fsm.(*testFSM).appliedCh,\n\t\tnewLeader.fsm.(*testFSM).appliedCh, 2,\n\t)\n}", "func TestPreVoteWithCheckQuorum(t *testing.T) {\n\tn1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\tn3.becomeFollower(1, None)\n\n\tn1.preVote = true\n\tn2.preVote = true\n\tn3.preVote = true\n\n\tn1.checkQuorum = true\n\tn2.checkQuorum = true\n\tn3.checkQuorum = true\n\n\tnt := newNetwork(n1, n2, n3)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\t// isolate node 1. node 2 and node 3 have leader info\n\tnt.isolate(1)\n\n\t// check state\n\tsm := nt.peers[1].(*raft)\n\tif sm.state != StateLeader {\n\t\tt.Fatalf(\"peer 1 state: %s, want %s\", sm.state, StateLeader)\n\t}\n\tsm = nt.peers[2].(*raft)\n\tif sm.state != StateFollower {\n\t\tt.Fatalf(\"peer 2 state: %s, want %s\", sm.state, StateFollower)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.state != StateFollower {\n\t\tt.Fatalf(\"peer 3 state: %s, want %s\", sm.state, StateFollower)\n\t}\n\n\t// node 2 will ignore node 3's PreVote\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\tnt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})\n\n\t// Do we have a leader?\n\tif n2.state != StateLeader && n3.state != StateFollower {\n\t\tt.Errorf(\"no leader\")\n\t}\n}", "func TestLeasePreferencesRebalance(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tdefer log.Scope(t).Close(t)\n\n\tctx := context.Background()\n\tsettings := cluster.MakeTestingClusterSettings()\n\tsv := &settings.SV\n\t// set min lease transfer high, so we know it does affect the lease movement.\n\tkvserver.MinLeaseTransferInterval.Override(sv, 24*time.Hour)\n\t// Place all the leases in us-west.\n\tzcfg := zonepb.DefaultZoneConfig()\n\tzcfg.LeasePreferences = []zonepb.LeasePreference{\n\t\t{\n\t\t\tConstraints: []zonepb.Constraint{\n\t\t\t\t{Type: zonepb.Constraint_REQUIRED, Key: \"region\", Value: \"us-west\"},\n\t\t\t},\n\t\t},\n\t}\n\tnumNodes := 3\n\tserverArgs := make(map[int]base.TestServerArgs)\n\tlocality := func(region string) roachpb.Locality {\n\t\treturn roachpb.Locality{\n\t\t\tTiers: []roachpb.Tier{\n\t\t\t\t{Key: \"region\", Value: region},\n\t\t\t},\n\t\t}\n\t}\n\tlocalities := []roachpb.Locality{\n\t\tlocality(\"us-west\"),\n\t\tlocality(\"us-east\"),\n\t\tlocality(\"eu\"),\n\t}\n\tfor i := 0; i < numNodes; i++ {\n\t\tserverArgs[i] = base.TestServerArgs{\n\t\t\tLocality: localities[i],\n\t\t\tKnobs: base.TestingKnobs{\n\t\t\t\tServer: &server.TestingKnobs{\n\t\t\t\t\tDefaultZoneConfigOverride: &zcfg,\n\t\t\t\t},\n\t\t\t},\n\t\t\tSettings: settings,\n\t\t}\n\t}\n\ttc := testcluster.StartTestCluster(t, numNodes,\n\t\tbase.TestClusterArgs{\n\t\t\tReplicationMode: base.ReplicationManual,\n\t\t\tServerArgsPerNode: serverArgs,\n\t\t})\n\tdefer tc.Stopper().Stop(ctx)\n\n\tkey := keys.UserTableDataMin\n\ttc.SplitRangeOrFatal(t, key)\n\ttc.AddVotersOrFatal(t, key, tc.Targets(1, 2)...)\n\trequire.NoError(t, tc.WaitForVoters(key, tc.Targets(1, 2)...))\n\tdesc := tc.LookupRangeOrFatal(t, key)\n\tleaseHolder, err := tc.FindRangeLeaseHolder(desc, nil)\n\trequire.NoError(t, err)\n\trequire.Equal(t, tc.Target(0), leaseHolder)\n\n\t// Manually move lease out of preference.\n\ttc.TransferRangeLeaseOrFatal(t, desc, tc.Target(1))\n\n\ttestutils.SucceedsSoon(t, func() error {\n\t\tlh, err := tc.FindRangeLeaseHolder(desc, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !lh.Equal(tc.Target(1)) {\n\t\t\treturn errors.Errorf(\"Expected leaseholder to be %s but was %s\", tc.Target(1), lh)\n\t\t}\n\t\treturn nil\n\t})\n\n\ttc.GetFirstStoreFromServer(t, 1).SetReplicateQueueActive(true)\n\trequire.NoError(t, tc.GetFirstStoreFromServer(t, 1).ForceReplicationScanAndProcess())\n\n\t// The lease should be moved back by the rebalance queue to us-west.\n\ttestutils.SucceedsSoon(t, func() error {\n\t\tlh, err := tc.FindRangeLeaseHolder(desc, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !lh.Equal(tc.Target(0)) {\n\t\t\treturn errors.Errorf(\"Expected leaseholder to be %s but was %s\", tc.Target(0), lh)\n\t\t}\n\t\treturn nil\n\t})\n}", "func newPreVoteMigrationCluster(t *testing.T) *network {\n\tn1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\tn3.becomeFollower(1, None)\n\n\tn1.preVote = true\n\tn2.preVote = true\n\t// We intentionally do not enable PreVote for n3, this is done so in order\n\t// to simulate a rolling restart process where it's possible to have a mixed\n\t// version cluster with replicas with PreVote enabled, and replicas without.\n\n\tnt := newNetwork(n1, n2, n3)\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\t// Cause a network partition to isolate n3.\n\tnt.isolate(3)\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte(\"some data\")}}})\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\n\t// check state\n\t// n1.state == StateLeader\n\t// n2.state == StateFollower\n\t// n3.state == StateCandidate\n\tif n1.state != StateLeader {\n\t\tt.Fatalf(\"node 1 state: %s, want %s\", n1.state, StateLeader)\n\t}\n\tif n2.state != StateFollower {\n\t\tt.Fatalf(\"node 2 state: %s, want %s\", n2.state, StateFollower)\n\t}\n\tif n3.state != StateCandidate {\n\t\tt.Fatalf(\"node 3 state: %s, want %s\", n3.state, StateCandidate)\n\t}\n\n\t// check term\n\t// n1.Term == 2\n\t// n2.Term == 2\n\t// n3.Term == 4\n\tif n1.Term != 2 {\n\t\tt.Fatalf(\"node 1 term: %d, want %d\", n1.Term, 2)\n\t}\n\tif n2.Term != 2 {\n\t\tt.Fatalf(\"node 2 term: %d, want %d\", n2.Term, 2)\n\t}\n\tif n3.Term != 4 {\n\t\tt.Fatalf(\"node 3 term: %d, want %d\", n3.Term, 4)\n\t}\n\n\t// Enable prevote on n3, then recover the network\n\tn3.preVote = true\n\tnt.recover()\n\n\treturn nt\n}", "func TestNodeWithSmallerTermCanCompleteElection(t *testing.T) {\n\tn1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(n1)\n\tdefer closeAndFreeRaft(n2)\n\tdefer closeAndFreeRaft(n3)\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\tn3.becomeFollower(1, None)\n\n\tn1.preVote = true\n\tn2.preVote = true\n\tn3.preVote = true\n\n\t// cause a network partition to isolate node 3\n\tnt := newNetwork(n1, n2, n3)\n\tnt.cut(1, 3)\n\tnt.cut(2, 3)\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tsm := nt.peers[1].(*raft)\n\tif sm.state != StateLeader {\n\t\tt.Errorf(\"peer 1 state: %s, want %s\", sm.state, StateLeader)\n\t}\n\n\tsm = nt.peers[2].(*raft)\n\tif sm.state != StateFollower {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", sm.state, StateFollower)\n\t}\n\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\tsm = nt.peers[3].(*raft)\n\tif sm.state != StatePreCandidate {\n\t\tt.Errorf(\"peer 3 state: %s, want %s\", sm.state, StatePreCandidate)\n\t}\n\n\tnt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})\n\n\t// check whether the term values are expected\n\t// a.Term == 3\n\t// b.Term == 3\n\t// c.Term == 1\n\tsm = nt.peers[1].(*raft)\n\tif sm.Term != 3 {\n\t\tt.Errorf(\"peer 1 term: %d, want %d\", sm.Term, 3)\n\t}\n\n\tsm = nt.peers[2].(*raft)\n\tif sm.Term != 3 {\n\t\tt.Errorf(\"peer 2 term: %d, want %d\", sm.Term, 3)\n\t}\n\n\tsm = nt.peers[3].(*raft)\n\tif sm.Term != 1 {\n\t\tt.Errorf(\"peer 3 term: %d, want %d\", sm.Term, 1)\n\t}\n\n\t// check state\n\t// a == follower\n\t// b == leader\n\t// c == pre-candidate\n\tsm = nt.peers[1].(*raft)\n\tif sm.state != StateFollower {\n\t\tt.Errorf(\"peer 1 state: %s, want %s\", sm.state, StateFollower)\n\t}\n\tsm = nt.peers[2].(*raft)\n\tif sm.state != StateLeader {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", sm.state, StateLeader)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.state != StatePreCandidate {\n\t\tt.Errorf(\"peer 3 state: %s, want %s\", sm.state, StatePreCandidate)\n\t}\n\n\tsm.logger.Infof(\"going to bring back peer 3 and kill peer 2\")\n\t// recover the network then immediately isolate b which is currently\n\t// the leader, this is to emulate the crash of b.\n\tnt.recover()\n\tnt.cut(2, 1)\n\tnt.cut(2, 3)\n\n\t// call for election\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\t// do we have a leader?\n\tsma := nt.peers[1].(*raft)\n\tsmb := nt.peers[3].(*raft)\n\tif sma.state != StateLeader && smb.state != StateLeader {\n\t\tt.Errorf(\"no leader\")\n\t}\n}", "func testNonleaderStartElection(t *testing.T, state StateType) {\n\t// election timeout\n\tet := 10\n\tr := newTestRaft(1, []uint64{1, 2, 3}, et, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(r)\n\tswitch state {\n\tcase StateFollower:\n\t\tr.becomeFollower(1, 2)\n\tcase StateCandidate:\n\t\tr.becomeCandidate()\n\t}\n\n\tfor i := 1; i < 2*et; i++ {\n\t\tr.tick()\n\t}\n\n\tif r.Term != 2 {\n\t\tt.Errorf(\"term = %d, want 2\", r.Term)\n\t}\n\tif r.state != StateCandidate {\n\t\tt.Errorf(\"state = %s, want %s\", r.state, StateCandidate)\n\t}\n\tif !r.votes[r.id] {\n\t\tt.Errorf(\"vote for self = false, want true\")\n\t}\n\tmsgs := r.readMessages()\n\tsort.Sort(messageSlice(msgs))\n\twmsgs := []pb.Message{\n\t\t{From: 1, FromGroup: pb.Group{NodeId: 1, GroupId: 1, RaftReplicaId: 1},\n\t\t\tTo: 2, ToGroup: pb.Group{NodeId: 2, GroupId: 1, RaftReplicaId: 2},\n\t\t\tTerm: 2, Type: pb.MsgVote},\n\t\t{From: 1, FromGroup: pb.Group{NodeId: 1, GroupId: 1, RaftReplicaId: 1},\n\t\t\tTo: 3, ToGroup: pb.Group{NodeId: 3, GroupId: 1, RaftReplicaId: 3},\n\t\t\tTerm: 2, Type: pb.MsgVote},\n\t}\n\tif !reflect.DeepEqual(msgs, wmsgs) {\n\t\tt.Errorf(\"msgs = %v, want %v\", msgs, wmsgs)\n\t}\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n persister *Persister, applyCh chan ApplyMsg) *Raft {\n rf := &Raft{}\n rf.peers = peers\n rf.persister = persister\n rf.me = me\n rf.applyCh = applyCh\n\n // Your initialization code here (2A, 2B, 2C).\n rf.dead = 0\n\n rf.currentTerm = 0\n rf.votedFor = -1\n rf.commitIndex = -1\n rf.lastApplied = -1\n rf.state = Follower\n rf.gotHeartbeat = false\n\n // initialize from state persisted before a crash\n rf.readPersist(persister.ReadRaftState())\n\n // Start Peer State Machine\n go func() {\n // Run forver\n for {\n \n if rf.killed() {\n fmt.Printf(\"*** Peer %d term %d: I have been terminated. Bye.\",rf.me, rf.currentTerm)\n return \n }\n \n rf.mu.Lock()\n state := rf.state\n rf.mu.Unlock()\n \n switch state {\n case Follower:\n fmt.Printf(\"-- peer %d term %d, status update: I am follolwer.\\n\",rf.me, rf.currentTerm)\n snoozeTime := rand.Float64()*(RANDOM_TIMER_MAX-RANDOM_TIMER_MIN) + RANDOM_TIMER_MIN\n fmt.Printf(\" peer %d term %d -- follower -- : Set election timer to time %f\\n\", rf.me, rf.currentTerm, snoozeTime)\n time.Sleep(time.Duration(snoozeTime) * time.Millisecond) \n \n rf.mu.Lock() \n fmt.Printf(\" peer %d term %d -- follower -- : my election timer had elapsed.\\n\",rf.me, rf.currentTerm)\n if (!rf.gotHeartbeat) {\n fmt.Printf(\"-> Peer %d term %d -- follower --: did not get heartbeat during the election timer. Starting election!\\n\",rf.me, rf.currentTerm) \n rf.state = Candidate\n }\n rf.gotHeartbeat = false\n rf.mu.Unlock()\n \n\n case Candidate:\n rf.mu.Lock()\n rf.currentTerm++\n fmt.Printf(\"-- peer %d: I am candidate! Starting election term %d\\n\",rf.me, rf.currentTerm)\n numPeers := len(rf.peers) // TODO: figure out what to with mutex when reading. Atomic? Lock?\n rf.votedFor = rf.me\n rf.mu.Unlock()\n \n voteCount := 1\n var replies = make([]RequestVoteReply, numPeers)\n rf.sendVoteRequests(replies, numPeers)\n\n snoozeTime := rand.Float64()*(RANDOM_TIMER_MAX-RANDOM_TIMER_MIN) + RANDOM_TIMER_MIN\n fmt.Printf(\" peer %d term %d -- candidate -- :Set snooze timer to time %f\\n\", rf.me, rf.currentTerm, snoozeTime)\n time.Sleep(time.Duration(snoozeTime) * time.Millisecond) \n \n rf.mu.Lock()\n fmt.Printf(\" peer %d term %d -- candidate -- :Waking up from snooze to count votes. %f\\n\", rf.me, rf.currentTerm, snoozeTime)\n if (rf.state != Follower) {\n fmt.Printf(\"-> Peer %d term %d -- candidate --: Start Counting votes...\\n\\n\",rf.me, rf.currentTerm)\n \n for id:=0; id < numPeers; id++ {\n if id != rf.me && replies[id].VoteGranted {\n voteCount++\n } \n }\n\n if voteCount > numPeers/2 {\n // Initialize leader nextIndex and match index\n for id:=0; id< (len(rf.peers)-1); id++{\n rf.nextIndex[id] = len(rf.log)\n rf.matchIndex[id] = 0\n }\n\n fmt.Printf(\"-- peer %d candidate: I am elected leader for term %d. voteCount:%d majority_treshold %d\\n\\n\",rf.me,rf.currentTerm, voteCount, numPeers/2)\n rf.state = Leader\n fmt.Printf(\"-> Peer %d leader of term %d: I send first heartbeat round to assert my authority.\\n\\n\",rf.me, rf.currentTerm)\n go rf.sendHeartbeats()\n // sanity check: (if there is another leader in this term then it cannot be get the majority of votes)\n if rf.gotHeartbeat {\n log.Fatal(\"Two leaders won election in the same term!\")\n }\n } else if rf.gotHeartbeat {\n fmt.Printf(\"-- peer %d candidate of term %d: I got heartbeat from a leader. So I step down :) \\n\",rf.me, rf.currentTerm)\n rf.state = Follower\n } else {\n fmt.Printf(\"-- peer %d candidate term %d: Did not have enough votes. Moving to a new election term.\\n\\n\",rf.me,rf.currentTerm)\n } \n } \n rf.mu.Unlock()\n \n\n case Leader:\n fmt.Printf(\"-- Peer %d term %d: I am leader.\\n\\n\",rf.me, rf.currentTerm)\n snoozeTime := (1/HEARTBEAT_RATE)*1000 \n fmt.Printf(\" Leader %d term %d: snooze for %f\\n\", rf.me, rf.currentTerm, snoozeTime)\n \n time.Sleep(time.Duration(snoozeTime) * time.Millisecond)\n \n rf.mu.Lock()\n if rf.state != Follower {\n\n if rf.gotHeartbeat {\n log.Fatal(\"Fatal Error: Have two leaders in the same term!!!\")\n }\n fmt.Printf(\" peer %d term %d --leader-- : I send periodic heartbeat.\\n\",rf.me, rf.currentTerm)\n go rf.sendHeartbeats()\n } \n rf.mu.Unlock()\n\n }\n }\n } ()\n \n\n return rf\n}", "func (c *Client) LeaderDiscovery() {\n\tdir := c.dir.Election\n\t// self node key\n\tself := fmt.Sprintf(\"%v/%v\", dir, c.address)\n\t// get a list of election nodes\n\tresp, err := c.client.Get(context.Background(), dir, &client.GetOptions{Sort: true})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// leader key and address\n\tvar key, addr string\n\t// current lowest node index\n\tvar idx uint64\n\tif len(resp.Node.Nodes) > 0 {\n\t\tfor _, v := range resp.Node.Nodes {\n\t\t\tif v.Dir {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif idx == 0 || v.CreatedIndex < idx {\n\t\t\t\tkey = v.Key\n\t\t\t\taddr = v.Value\n\t\t\t\tidx = v.CreatedIndex\n\t\t\t}\n\t\t}\n\t}\n\tif key == \"\" || addr == \"\" {\n\t\tfmt.Println(\"# no nodes were found\")\n\t\tc.Lock()\n\t\tc.leader = nil\n\t\tc.Unlock()\n\t} else {\n\t\tleader := &models.Leader{Key: key, Address: addr}\n\t\tif c.leader == nil {\n\t\t\tif leader.Key == self {\n\t\t\t\tfmt.Println(\"# elected as leader\")\n\t\t\t\tc.events <- &models.Event{Type: EventElected, Group: GroupLeader}\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"# elected as worker\")\n\t\t\t\t// do not send any event until leader node is ready\n\t\t\t\tif nodes := c.GetRunningNodes(); len(nodes) > 0 {\n\t\t\t\t\tc.events <- &models.Event{Type: EventElected, Group: GroupWorker}\n\t\t\t\t} else {\n\t\t\t\t\tgo c.WaitForLeader()\n\t\t\t\t}\n\t\t\t}\n\t\t} else if c.leader != nil && leader.Key != c.leader.Key {\n\t\t\tif leader.Key == self {\n\t\t\t\tfmt.Println(\"# re-elected as leader\")\n\t\t\t\tc.events <- &models.Event{Type: EventReElected, Group: GroupLeader}\n\t\t\t}\n\t\t}\n\t\tc.Lock()\n\t\tc.leader = leader\n\t\tc.Unlock()\n\t}\n}", "func TestRaftRemoveLeader(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tID3 := \"3\"\n\tclusterPrefix := \"TestRaftRemoveLeader\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tn1 := testCreateRaftNode(getTestConfig(ID1, clusterPrefix+ID1), newStorage())\n\t// Create n2.\n\tfsm2 := newTestFSM(ID2)\n\tn2 := testCreateRaftNode(getTestConfig(ID2, clusterPrefix+ID2), newStorage())\n\t// Create n3.\n\tfsm3 := newTestFSM(ID3)\n\tn3 := testCreateRaftNode(getTestConfig(ID3, clusterPrefix+ID3), newStorage())\n\n\tconnectAllNodes(n1, n2, n3)\n\n\t// The cluster starts with only one node -- n1.\n\tn1.Start(fsm1)\n\tn1.ProposeInitialMembership([]string{ID1})\n\n\t// Wait it becomes to leader.\n\t<-fsm1.leaderCh\n\n\t// Add n2 to the cluster.\n\tpending := n1.AddNode(ID2)\n\tn2.Start(fsm2)\n\t// Wait until n2 gets joined.\n\t<-pending.Done\n\n\t// Add n3 to the cluster.\n\tpending = n1.AddNode(ID3)\n\tn3.Start(fsm3)\n\t// Wait until n3 gets joined.\n\t<-pending.Done\n\n\t// Now we have a cluster with 3 nodes and n1 as the leader.\n\n\t// Remove the leader itself.\n\tn1.RemoveNode(ID1)\n\n\t// A new leader should be elected in new configuration(n2, n3).\n\tvar newLeader *Raft\n\tselect {\n\tcase <-fsm2.leaderCh:\n\t\tnewLeader = n2\n\tcase <-fsm3.leaderCh:\n\t\tnewLeader = n1\n\t}\n\n\tnewLeader.Propose([]byte(\"data1\"))\n\tnewLeader.Propose([]byte(\"data2\"))\n\tnewLeader.Propose([]byte(\"data3\"))\n\n\t// Now n2 and n3 should commit newly proposed entries eventually>\n\tif !testEntriesEqual(fsm2.appliedCh, fsm3.appliedCh, 3) {\n\t\tt.Fatal(\"two FSMs in same group applied different sequence of commands.\")\n\t}\n}", "func main() {\n\tvar l server.ListenConst\n\n\tif useDomainSocket {\n\t\tl = server.UnixListener(sockPath)\n\t} else {\n\t\tl = server.TCPListener(port)\n\t}\n\n\tprotocols := []protocol.Components{binprot.Components, textprot.Components}\n\n\tvar o orcas.OrcaConst\n\tvar h2 handlers.HandlerConst\n\tvar h1 handlers.HandlerConst\n\n\t// Choose the proper L1 handler\n\tif l1inmem {\n\t\th1 = inmem.New\n\t} else if chunked {\n\t\th1 = memcached.Chunked(l1sock)\n\t} else if l1batched {\n\t\th1 = memcached.Batched(l1sock, batchOpts)\n\t} else {\n\t\th1 = memcached.Regular(l1sock)\n\t}\n\n\tif l2enabled {\n\t\to = orcas.L1L2\n\t\th2 = memcached.Regular(l2sock)\n\t} else {\n\t\to = orcas.L1Only\n\t\th2 = handlers.NilHandler\n\t}\n\n\t// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers\n\t// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If\n\t// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent\n\t// sets into L1 with chunking can collide and cause data corruption.\n\tvar lockset uint32\n\tif locked {\n\t\tif chunked || !multiReader {\n\t\t\to, lockset = orcas.Locked(o, false, uint8(concurrency))\n\t\t} else {\n\t\t\to, lockset = orcas.Locked(o, true, uint8(concurrency))\n\t\t}\n\t}\n\n\tgo server.ListenAndServe(l, protocols, server.Default, o, h1, h2)\n\n\tif l2enabled {\n\t\t// If L2 is enabled, start the batch L1 / L2 orchestrator\n\t\tl = server.TCPListener(batchPort)\n\t\to := orcas.L1L2Batch\n\n\t\tif locked {\n\t\t\to = orcas.LockedWithExisting(o, lockset)\n\t\t}\n\n\t\tgo server.ListenAndServe(l, protocols, server.Default, o, h1, h2)\n\t}\n\n\t// Block forever\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\twg.Wait()\n}", "func (r *rState) ConsistencyLevel(l ConsistencyLevel) (int, error) {\n\tlevel := cLevel(l, r.Len())\n\tif n := len(r.Hosts); level > n {\n\t\tnodes := []string{}\n\t\tfor k, addr := range r.NodeMap {\n\t\t\tif addr == \"\" {\n\t\t\t\tnodes = append(nodes, k)\n\t\t\t}\n\t\t}\n\t\treturn 0, fmt.Errorf(\"consistency level (%d) > available replicas(%d): %w :%v\",\n\t\t\tlevel, n, errUnresolvedName, nodes)\n\t}\n\treturn level, nil\n}", "func TestLeaderElectionInOneRoundRPC(t *testing.T) {\n\ttests := []struct {\n\t\tsize int\n\t\tvotes map[uint64]bool\n\t\tstate StateType\n\t}{\n\t\t// win the election when receiving votes from a majority of the servers\n\t\t{1, map[uint64]bool{}, StateLeader},\n\t\t{3, map[uint64]bool{2: true, 3: true}, StateLeader},\n\t\t{3, map[uint64]bool{2: true}, StateLeader},\n\t\t{5, map[uint64]bool{2: true, 3: true, 4: true, 5: true}, StateLeader},\n\t\t{5, map[uint64]bool{2: true, 3: true, 4: true}, StateLeader},\n\t\t{5, map[uint64]bool{2: true, 3: true}, StateLeader},\n\n\t\t// return to follower state if it receives vote denial from a majority\n\t\t{3, map[uint64]bool{2: false, 3: false}, StateFollower},\n\t\t{5, map[uint64]bool{2: false, 3: false, 4: false, 5: false}, StateFollower},\n\t\t{5, map[uint64]bool{2: true, 3: false, 4: false, 5: false}, StateFollower},\n\n\t\t// stay in candidate if it does not obtain the majority\n\t\t{3, map[uint64]bool{}, StateCandidate},\n\t\t{5, map[uint64]bool{2: true}, StateCandidate},\n\t\t{5, map[uint64]bool{2: false, 3: false}, StateCandidate},\n\t\t{5, map[uint64]bool{}, StateCandidate},\n\t}\n\tfor i, tt := range tests {\n\t\tr := newTestRaft(1, idsBySize(tt.size), 10, 1, NewMemoryStorage())\n\t\tdefer closeAndFreeRaft(r)\n\n\t\tr.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\t\tfor id, vote := range tt.votes {\n\t\t\tr.Step(pb.Message{From: id, To: 1, Term: r.Term, Type: pb.MsgVoteResp, Reject: !vote})\n\t\t}\n\n\t\tif r.state != tt.state {\n\t\t\tt.Errorf(\"#%d: state = %s, want %s\", i, r.state, tt.state)\n\t\t}\n\t\tif g := r.Term; g != 1 {\n\t\t\tt.Errorf(\"#%d: term = %d, want %d\", i, g, 1)\n\t\t}\n\t}\n}", "func TestRaftSingleNodeVerifyRead(t *testing.T) {\n\tID1 := \"1\"\n\tclusterPrefix := \"TestRaftSingleNodeVerifyRead\"\n\n\t// Create the Raft node.\n\tfsm := newTestFSM(ID1)\n\tcfg := getTestConfig(ID1, clusterPrefix+ID1)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn := testCreateRaftNode(cfg, newStorage())\n\tn.Start(fsm)\n\tn.ProposeInitialMembership([]string{ID1})\n\n\t// Wait it becomes leader.\n\t<-fsm.leaderCh\n\tpending := n.VerifyRead()\n\t<-pending.Done\n\tif pending.Err != nil {\n\t\tlog.Fatalf(\"Failed to do VerifyRead in single-node Raft cluster.\")\n\t}\n}", "func probeTopology(pwd string, mode Mode, addrs ...string) (i interface{}, err error) {\n\tvar redisClient *c.Client\n\n\tif reached, err := ping(addrs...); err != nil {\n\t\treturn nil, err\n\t} else if len(reached) < 1 {\n\t\treturn nil, errors.New(\"all addresses are unreachable\")\n\t} else {\n\t\tif len(pwd) > 0 {\n\t\t\tif mode == ClusterMode {\n\t\t\t\tredisClient = c.NewClient(reached[0], c.DialPassword(pwd))\n\t\t\t} else {\n\t\t\t\tredisClient = c.NewClient(reached[0])\n\t\t\t}\n\t\t} else {\n\t\t\tredisClient = c.NewClient(reached[0])\n\t\t}\n\t}\n\n\tswitch mode {\n\tcase SentinelMode:\n\t\tresult := make([][]string, 0)\n\t\tmasterSS, err := c.Strings(redisClient.Do(\"sentinel\", \"master\", \"mymaster\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, masterSS)\n\t\tslaveSS, err := c.MultiBulk(redisClient.Do(\"sentinel\", \"slaves\", \"mymaster\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i := range slaveSS {\n\t\t\tslaveInterfaces, ok := slaveSS[i].([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"assert slaves type error real type is %T\", slaveInterfaces)\n\t\t\t}\n\t\t\tslaveStrs := make([]string, 0)\n\t\t\tfor y := range slaveInterfaces {\n\t\t\t\tslave, ok := slaveInterfaces[y].([]uint8)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"assert slave error real type %T\", slave)\n\t\t\t\t}\n\t\t\t\tslaveStrs = append(slaveStrs, hack.String(uint8sToBytes(slave)))\n\t\t\t}\n\t\t\tflags := fieldSplicing(sliceStr2Dict(slaveStrs), \"flags\")\n\t\t\tif strings.Contains(flags, \"s_down\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult = append(result, slaveStrs)\n\t\t}\n\t\treturn result, nil\n\n\tcase ClusterMode:\n\t\ts, err := c.String(redisClient.Do(\"cluster\", \"nodes\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn s, nil\n\n\tcase SingleMode:\n\t\treturn addrs[0], nil\n\t}\n\treturn nil, errors.New(\"mode error\")\n}", "func main() {\n\tklog.InitFlags(nil)\n\tflag.Parse()\n\targs := flag.Args()\n\tif len(args) != 3 {\n\t\tlog.Fatalf(\"requires three arguments: ID NAMESPACE CONFIG_MAP_NAME (%d)\", len(args))\n\t}\n\n\t// leader election uses the Kubernetes API by writing to a ConfigMap or Endpoints\n\t// object. Conflicting writes are detected and each client handles those actions\n\t// independently.\n\tvar config *rest.Config\n\tvar err error\n\tif kubeconfig := os.Getenv(\"KUBECONFIG\"); len(kubeconfig) > 0 {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\n\t// we use the ConfigMap lock type since edits to ConfigMaps are less common\n\t// and fewer objects in the cluster watch \"all ConfigMaps\" (unlike the older\n\t// Endpoints lock type, where quite a few system agents like the kube-proxy\n\t// and ingress controllers must watch endpoints).\n\tid := args[0]\n\tlock := &resourcelock.ConfigMapLock{\n\t\tConfigMapMeta: metav1.ObjectMeta{\n\t\t\tNamespace: args[1],\n\t\t\tName: args[2],\n\t\t},\n\t\tClient: kubernetes.NewForConfigOrDie(config).CoreV1(),\n\t\tLockConfig: resourcelock.ResourceLockConfig{\n\t\t\tIdentity: id,\n\t\t},\n\t}\n\n\t// use a Go context so we can tell the leaderelection code when we\n\t// want to step down\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// use a client that will stop allowing new requests once the context ends\n\tconfig.Wrap(transport.ContextCanceller(ctx, fmt.Errorf(\"the leader is shutting down\")))\n\texampleClient := kubernetes.NewForConfigOrDie(config).CoreV1()\n\n\t// listen for interrupts or the Linux SIGTERM signal and cancel\n\t// our context, which the leader election code will observe and\n\t// step down\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\t<-ch\n\t\tlog.Printf(\"Received termination, signaling shutdown\")\n\t\tcancel()\n\t}()\n\n\t// start the leader election code loop\n\tleaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{\n\t\tLock: lock,\n\t\t// IMPORTANT: you MUST ensure that any code you have that\n\t\t// is protected by the lease must terminate **before**\n\t\t// you call cancel. Otherwise, you could have a background\n\t\t// loop still running and another process could\n\t\t// get elected before your background loop finished, violating\n\t\t// the stated goal of the lease.\n\t\tReleaseOnCancel: true,\n\t\tLeaseDuration: 60 * time.Second,\n\t\tRenewDeadline: 15 * time.Second,\n\t\tRetryPeriod: 5 * time.Second,\n\t\tCallbacks: leaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\t// we're notified when we start - this is where you would\n\t\t\t\t// usually put your code\n\t\t\t\tlog.Printf(\"%s: leading\", id)\n\t\t\t},\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\t// we can do cleanup here, or after the RunOrDie method\n\t\t\t\t// returns\n\t\t\t\tlog.Printf(\"%s: lost\", id)\n\t\t\t},\n\t\t},\n\t})\n\n\t// because the context is closed, the client should report errors\n\t_, err = exampleClient.ConfigMaps(args[1]).Get(args[2], metav1.GetOptions{})\n\tif err == nil || !strings.Contains(err.Error(), \"the leader is shutting down\") {\n\t\tlog.Fatalf(\"%s: expected to get an error when trying to make a client call: %v\", id, err)\n\t}\n\n\t// we no longer hold the lease, so perform any cleanup and then\n\t// exit\n\tlog.Printf(\"%s: done\", id)\n}", "func TestRaftLeaderLeaseLost(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tclusterPrefix := \"TestRaftLeaderLeaseLost\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tcfg := getTestConfig(ID1, clusterPrefix+ID1)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn1 := testCreateRaftNode(cfg, newStorage())\n\n\t// Create n2 node.\n\tfsm2 := newTestFSM(ID2)\n\tcfg = getTestConfig(ID2, clusterPrefix+ID2)\n\tcfg.LeaderStepdownTimeout = cfg.FollowerTimeout\n\tn2 := testCreateRaftNode(cfg, newStorage())\n\n\tconnectAllNodes(n1, n2)\n\tn1.transport = NewMsgDropper(n1.transport, 193, 0)\n\tn2.transport = NewMsgDropper(n2.transport, 42, 0)\n\tn1.Start(fsm1)\n\tn2.Start(fsm2)\n\tn2.ProposeInitialMembership([]string{ID1, ID2})\n\n\t// Find out who leader is.\n\tvar leader *Raft\n\tselect {\n\tcase <-fsm1.leaderCh:\n\t\tleader = n1\n\tcase <-fsm2.leaderCh:\n\t\tleader = n2\n\t}\n\n\t// Create a network partition between \"1\" and \"2\", so leader will lost its leader lease eventually.\n\tn1.transport.(*msgDropper).Set(ID2, 1)\n\tn2.transport.(*msgDropper).Set(ID1, 1)\n\n\t// The leader will lose its leadership eventually because it can't talk to\n\t// the other node.\n\t<-leader.fsm.(*testFSM).followerCh\n}", "func TestLeaderStartReplication(t *testing.T) {\n\ts := NewMemoryStorage()\n\tr := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, s)\n\tdefer closeAndFreeRaft(r)\n\tr.becomeCandidate()\n\tr.becomeLeader()\n\tcommitNoopEntry(r, s)\n\tli := r.raftLog.lastIndex()\n\n\tents := []pb.Entry{{Data: []byte(\"some data\")}}\n\tr.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: ents})\n\n\tif g := r.raftLog.lastIndex(); g != li+1 {\n\t\tt.Errorf(\"lastIndex = %d, want %d\", g, li+1)\n\t}\n\tif g := r.raftLog.committed; g != li {\n\t\tt.Errorf(\"committed = %d, want %d\", g, li)\n\t}\n\tmsgs := r.readMessages()\n\tsort.Sort(messageSlice(msgs))\n\twents := []pb.Entry{{Index: li + 1, Term: 1, Data: []byte(\"some data\")}}\n\twmsgs := []pb.Message{\n\t\t{From: 1, FromGroup: pb.Group{NodeId: 1, GroupId: 1, RaftReplicaId: 1},\n\t\t\tTo: 2, ToGroup: pb.Group{NodeId: 2, GroupId: 1, RaftReplicaId: 2}, Term: 1, Type: pb.MsgApp, Index: li, LogTerm: 1, Entries: wents, Commit: li},\n\t\t{From: 1, FromGroup: pb.Group{NodeId: 1, GroupId: 1, RaftReplicaId: 1},\n\t\t\tTo: 3, ToGroup: pb.Group{NodeId: 3, GroupId: 1, RaftReplicaId: 3}, Term: 1, Type: pb.MsgApp, Index: li, LogTerm: 1, Entries: wents, Commit: li},\n\t}\n\tif !reflect.DeepEqual(msgs, wmsgs) {\n\t\tt.Errorf(\"msgs = %+v, want %+v\", msgs, wmsgs)\n\t}\n\tif g := r.raftLog.unstableEntries(); !reflect.DeepEqual(g, wents) {\n\t\tt.Errorf(\"ents = %+v, want %+v\", g, wents)\n\t}\n}", "func (s *store) open(raftln net.Listener) error {\n\ts.logger.Info(fmt.Sprintf(\"Using data dir: %v\", s.path))\n\n\tjoinPeers, err := s.filterAddr(s.config.JoinPeers, s.httpAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjoinPeers = s.config.JoinPeers\n\n\tvar initializePeers []string\n\tif len(joinPeers) > 0 {\n\t\tc := NewClient()\n\t\tc.SetMetaServers(joinPeers)\n\t\tc.SetTLS(s.config.HTTPSEnabled)\n\t\tfor {\n\t\t\tpeers := c.peers()\n\t\t\tif !Peers(peers).Contains(s.raftAddr) {\n\t\t\t\tpeers = append(peers, s.raftAddr)\n\t\t\t}\n\n\t\t\ts.logger.Info(fmt.Sprintf(\"len : %d, %d \\r\\n\" ,len(s.config.JoinPeers),len(peers)))\n\t\t\tif len(s.config.JoinPeers)-len(peers) == 0 {\n\t\t\t\tinitializePeers = peers\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif len(peers) > len(s.config.JoinPeers) {\n\t\t\t\ts.logger.Info(fmt.Sprintf(\"waiting for join peers to match config specified. found %v, config specified %v\", peers, s.config.JoinPeers))\n\t\t\t} else {\n\t\t\t\ts.logger.Info(fmt.Sprintf(\"Waiting for %d join peers. Have %v. Asking nodes: %v\", len(s.config.JoinPeers)-len(peers), peers, joinPeers))\n\t\t\t}\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}\n\n\tif err := s.setOpen(); err != nil {\n\t\treturn err\n\t}\n\n\t// Create the root directory if it doesn't already exist.\n\tif err := os.MkdirAll(s.path, 0777); err != nil {\n\t\treturn fmt.Errorf(\"mkdir all: %s\", err)\n\t}\n\n\t// Open the raft store.\n\tif err := s.openRaft(initializePeers, raftln); err != nil {\n\t\treturn fmt.Errorf(\"raft: %s\", err)\n\t}\n\n\ts.logger.Info(fmt.Sprintf(\"open raft done. %d\", len(joinPeers)))\n\tif len(joinPeers) > 0 {\n\t\tc := NewClient()\n\t\tc.SetMetaServers(joinPeers)\n\t\tc.SetTLS(s.config.HTTPSEnabled)\n\t\tif err := c.Open(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer c.Close()\n\n\t\t_, err := c.JoinMetaServer(s.httpAddr, s.raftAddr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Wait for a leader to be elected so we know the raft log is loaded\n\t// and up to date\n\tif err := s.waitForLeader(0); err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure this server is in the list of metanodes\n\tpeers, err := s.raftState.peers()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(fmt.Sprintf(\"peers count= %d\", len(peers)))\n\tif len(peers) <= 1 {\n\t\t// we have to loop here because if the hostname has changed\n\t\t// raft will take a little bit to normalize so that this host\n\t\t// will be marked as the leader\n\t\tfor {\n\t\t\terr := s.setMetaNode(s.httpAddr, s.raftAddr)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}else{\n\t\t\t\ts.logger.Error(err.Error())\n\t\t\t}\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}\n\n\tgo func() { s.rebalance(s.closing) }()\n\ts.logger.Info(\"open store done\")\n\treturn nil\n}", "func TestActiveReplicatorEdgeCheckpointNameCollisions(t *testing.T) {\n\n\tbase.RequireNumTestBuckets(t, 3)\n\n\tbase.SetUpTestLogging(t, logger.LevelDebug, logger.KeyReplicate, logger.KeyHTTP, logger.KeyHTTPResp, logger.KeySync, logger.KeySyncMsg)\n\n\tconst (\n\t\tchangesBatchSize = 10\n\t\tnumRT1DocsInitial = 13 // 2 batches of changes\n\t)\n\n\t// Central cluster\n\ttb1 := base.GetTestBucket(t)\n\trt1 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: tb1,\n\t\tDatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{\n\t\t\tUsers: map[string]*db.PrincipalConfig{\n\t\t\t\t\"alice\": {\n\t\t\t\t\tPassword: base.StringPtr(\"pass\"),\n\t\t\t\t\tExplicitChannels: utils.SetOf(\"alice\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t})\n\tdefer rt1.Close()\n\n\t// Create first batch of docs\n\tdocIDPrefix := t.Name() + \"rt1doc\"\n\tfor i := 0; i < numRT1DocsInitial; i++ {\n\t\tresp := rt1.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, i), `{\"source\":\"rt1\",\"channels\":[\"alice\"]}`)\n\t\tassertStatus(t, resp, http.StatusCreated)\n\t}\n\n\t// Make rt1 listen on an actual HTTP port, so it can receive the blipsync request from edges\n\tsrv := httptest.NewServer(rt1.TestPublicHandler())\n\tdefer srv.Close()\n\n\t// Build rt1DBURL with basic auth creds\n\trt1DBURL, err := url.Parse(srv.URL + \"/db\")\n\trequire.NoError(t, err)\n\trt1DBURL.User = url.UserPassword(\"alice\", \"pass\")\n\n\t// Edge 1\n\tedge1Bucket := base.GetTestBucket(t)\n\tedge1 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: edge1Bucket,\n\t})\n\tdefer edge1.Close()\n\n\tarConfig := db.ActiveReplicatorConfig{\n\t\tID: \"edge-repl\",\n\t\tDirection: db.ActiveReplicatorTypePull,\n\t\tRemoteDBURL: rt1DBURL,\n\t\tActiveDB: &db.Database{\n\t\t\tDatabaseContext: edge1.GetDatabase(),\n\t\t},\n\t\tContinuous: true,\n\t\tChangesBatchSize: changesBatchSize,\n\t}\n\tarConfig.SetCheckpointPrefix(t, \"cluster1:\")\n\n\t// Create the first active replicator to pull from seq:0\n\tarConfig.ReplicationStatsMap = base.SyncGatewayStats.NewDBStats(t.Name()+\"edge1\", false, false, false).DBReplicatorStats(t.Name())\n\tedge1Replicator := db.NewActiveReplicator(&arConfig)\n\n\tstartNumChangesRequestedFromZeroTotal := rt1.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tstartNumRevsHandledTotal := edge1Replicator.Pull.GetStats().HandleRevCount.Value()\n\n\tassert.NoError(t, edge1Replicator.Start())\n\n\t// wait for all of the documents originally written to rt1 to arrive at edge1\n\tchangesResults, err := edge1.WaitForChanges(numRT1DocsInitial, \"/db/_changes?since=0\", \"\", true)\n\trequire.NoError(t, err)\n\tedge1LastSeq := changesResults.Last_Seq\n\trequire.Len(t, changesResults.Results, numRT1DocsInitial)\n\tdocIDsSeen := make(map[string]bool, numRT1DocsInitial)\n\tfor _, result := range changesResults.Results {\n\t\tdocIDsSeen[result.ID] = true\n\t}\n\tfor i := 0; i < numRT1DocsInitial; i++ {\n\t\tdocID := fmt.Sprintf(\"%s%d\", docIDPrefix, i)\n\t\tassert.True(t, docIDsSeen[docID])\n\n\t\tdoc, err := edge1.GetDatabase().GetDocument(logger.TestCtx(t), docID, db.DocUnmarshalAll)\n\t\tassert.NoError(t, err)\n\n\t\tbody, err := doc.GetDeepMutableBody()\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, \"rt1\", body[\"source\"])\n\t}\n\n\tedge1Replicator.Pull.Checkpointer.CheckpointNow()\n\n\t// one _changes from seq:0 with initial number of docs sent\n\tnumChangesRequestedFromZeroTotal := rt1.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tassert.Equal(t, startNumChangesRequestedFromZeroTotal+1, numChangesRequestedFromZeroTotal)\n\n\t// rev assertions\n\tnumRevsHandledTotal := edge1Replicator.Pull.GetStats().HandleRevCount.Value()\n\tassert.Equal(t, startNumRevsHandledTotal+numRT1DocsInitial, numRevsHandledTotal)\n\tassert.Equal(t, int64(numRT1DocsInitial), edge1Replicator.Pull.Checkpointer.Stats().ProcessedSequenceCount)\n\tassert.Equal(t, int64(numRT1DocsInitial), edge1Replicator.Pull.Checkpointer.Stats().ExpectedSequenceCount)\n\n\t// checkpoint assertions\n\tassert.Equal(t, int64(0), edge1Replicator.Pull.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(1), edge1Replicator.Pull.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(1), edge1Replicator.Pull.Checkpointer.Stats().SetCheckpointCount)\n\n\tassert.NoError(t, edge1Replicator.Stop())\n\n\t// Edge 2\n\tedge2Bucket := base.GetTestBucket(t)\n\tedge2 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: edge2Bucket,\n\t})\n\tdefer edge2.Close()\n\n\t// Create a new replicator using the same ID, which should NOT use the checkpoint set by the first edge.\n\tarConfig.ReplicationStatsMap = base.SyncGatewayStats.NewDBStats(t.Name()+\"edge2\", false, false, false).DBReplicatorStats(t.Name())\n\tarConfig.ActiveDB = &db.Database{\n\t\tDatabaseContext: edge2.GetDatabase(),\n\t}\n\tarConfig.SetCheckpointPrefix(t, \"cluster2:\")\n\tedge2Replicator := db.NewActiveReplicator(&arConfig)\n\tassert.NoError(t, edge2Replicator.Start())\n\n\tchangesResults, err = edge2.WaitForChanges(numRT1DocsInitial, \"/db/_changes?since=0\", \"\", true)\n\trequire.NoError(t, err)\n\n\tedge2Replicator.Pull.Checkpointer.CheckpointNow()\n\n\t// make sure that edge 2 didn't use a checkpoint\n\tassert.Equal(t, int64(0), edge2Replicator.Pull.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(1), edge2Replicator.Pull.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(1), edge2Replicator.Pull.Checkpointer.Stats().SetCheckpointCount)\n\n\tassert.NoError(t, edge2Replicator.Stop())\n\n\tresp := rt1.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, numRT1DocsInitial), `{\"source\":\"rt1\",\"channels\":[\"alice\"]}`)\n\tassertStatus(t, resp, http.StatusCreated)\n\trequire.NoError(t, rt1.WaitForPendingChanges())\n\n\t// run a replicator on edge1 again to make sure that edge2 didn't blow away its checkpoint\n\tarConfig.ReplicationStatsMap = base.SyncGatewayStats.NewDBStats(t.Name()+\"edge1\", false, false, false).DBReplicatorStats(t.Name())\n\tarConfig.ActiveDB = &db.Database{\n\t\tDatabaseContext: edge1.GetDatabase(),\n\t}\n\tarConfig.SetCheckpointPrefix(t, \"cluster1:\")\n\n\tedge1Replicator2 := db.NewActiveReplicator(&arConfig)\n\trequire.NoError(t, edge1Replicator2.Start())\n\n\tchangesResults, err = edge1.WaitForChanges(1, fmt.Sprintf(\"/db/_changes?since=%v\", edge1LastSeq), \"\", true)\n\trequire.NoErrorf(t, err, \"changesResults: %v\", changesResults)\n\tchangesResults.requireDocIDs(t, []string{fmt.Sprintf(\"%s%d\", docIDPrefix, numRT1DocsInitial)})\n\n\tedge1Replicator2.Pull.Checkpointer.CheckpointNow()\n\n\tassert.Equal(t, int64(1), edge1Replicator2.Pull.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(0), edge1Replicator2.Pull.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(1), edge1Replicator2.Pull.Checkpointer.Stats().SetCheckpointCount)\n\n\trequire.NoError(t, edge1Replicator2.Stop())\n}", "func (kss *keyspaceState) ensureConsistentLocked() {\n\t// if this keyspace is consistent, there's no ongoing availability event\n\tif kss.consistent {\n\t\treturn\n\t}\n\n\tif kss.moveTablesState != nil && kss.moveTablesState.Typ != MoveTablesNone && kss.moveTablesState.State != MoveTablesSwitched {\n\t\treturn\n\t}\n\n\t// get the topology metadata for our primary from `lastKeyspace`; this value is refreshed\n\t// from our topology watcher whenever a change is detected, so it should always be up to date\n\tprimary := topoproto.SrvKeyspaceGetPartition(kss.lastKeyspace, topodatapb.TabletType_PRIMARY)\n\n\t// if there's no primary, the keyspace is unhealthy;\n\t// if there are ShardTabletControls active, the keyspace is undergoing a topology change;\n\t// either way, the availability event is still ongoing\n\tif primary == nil || len(primary.ShardTabletControls) > 0 {\n\t\treturn\n\t}\n\n\tactiveShardsInPartition := make(map[string]bool)\n\n\t// iterate through all the primary shards that the topology server knows about;\n\t// for each shard, if our HealthCheck stream hasn't found the shard yet, or\n\t// if the HealthCheck stream still thinks the shard is unhealthy, this\n\t// means the availability event is still ongoing\n\tfor _, shard := range primary.ShardReferences {\n\t\tsstate := kss.shards[shard.Name]\n\t\tif sstate == nil || !sstate.serving {\n\t\t\treturn\n\t\t}\n\t\tactiveShardsInPartition[shard.Name] = true\n\t}\n\n\t// iterate through all the shards as seen by our HealthCheck stream. if there are any\n\t// shards that HealthCheck thinks are healthy, and they haven't been seen by the topology\n\t// watcher, it means the keyspace is not fully consistent yet\n\tfor shard, sstate := range kss.shards {\n\t\tif sstate.serving && !activeShardsInPartition[shard] {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// clone the current moveTablesState, if any, to handle race conditions where it can get updated while we're broadcasting\n\tvar moveTablesState MoveTablesState\n\tif kss.moveTablesState != nil {\n\t\tmoveTablesState = *kss.moveTablesState\n\t}\n\n\tksevent := &KeyspaceEvent{\n\t\tCell: kss.kew.localCell,\n\t\tKeyspace: kss.keyspace,\n\t\tShards: make([]ShardEvent, 0, len(kss.shards)),\n\t\tMoveTablesState: moveTablesState,\n\t}\n\n\t// we haven't found any inconsistencies between the HealthCheck stream and the topology\n\t// watcher. this means the ongoing availability event has been resolved, so we can broadcast\n\t// a resolution event to all listeners\n\tkss.consistent = true\n\n\tkss.moveTablesState = nil\n\n\tfor shard, sstate := range kss.shards {\n\t\tksevent.Shards = append(ksevent.Shards, ShardEvent{\n\t\t\tTablet: sstate.currentPrimary,\n\t\t\tTarget: sstate.target,\n\t\t\tServing: sstate.serving,\n\t\t})\n\n\t\tlog.Infof(\"keyspace event resolved: %s/%s is now consistent (serving: %v)\",\n\t\t\tsstate.target.Keyspace, sstate.target.Keyspace,\n\t\t\tsstate.serving,\n\t\t)\n\n\t\tif !sstate.serving {\n\t\t\tdelete(kss.shards, shard)\n\t\t}\n\t}\n\n\tkss.kew.broadcast(ksevent)\n}", "func TestInconsistentReads(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\n\t// Mock out DistSender's sender function to check the read consistency for\n\t// outgoing BatchRequests and return an empty reply.\n\tvar senderFn client.SenderFunc\n\tsenderFn = func(_ context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, *roachpb.Error) {\n\t\tif ba.ReadConsistency != roachpb.INCONSISTENT {\n\t\t\treturn nil, roachpb.NewErrorf(\"BatchRequest has unexpected ReadConsistency %s\",\n\t\t\t\tba.ReadConsistency)\n\t\t}\n\t\treturn ba.CreateReply(), nil\n\t}\n\tdb := client.NewDB(senderFn)\n\n\tprepInconsistent := func() *client.Batch {\n\t\tb := &client.Batch{}\n\t\tb.Header.ReadConsistency = roachpb.INCONSISTENT\n\t\treturn b\n\t}\n\n\t// Perform inconsistent reads through the mocked sender function.\n\t{\n\t\tkey := roachpb.Key([]byte(\"key\"))\n\t\tb := prepInconsistent()\n\t\tb.Get(key)\n\t\tif err := db.Run(b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t{\n\t\tb := prepInconsistent()\n\t\tkey1 := roachpb.Key([]byte(\"key1\"))\n\t\tkey2 := roachpb.Key([]byte(\"key2\"))\n\t\tb.Scan(key1, key2)\n\t\tif err := db.Run(b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t{\n\t\tkey := roachpb.Key([]byte(\"key\"))\n\t\tb := &client.Batch{}\n\t\tb.Header.ReadConsistency = roachpb.INCONSISTENT\n\t\tb.Get(key)\n\t\tif err := db.Run(b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func Leader(Conn []*net.Conn) {\n\tcP := make(chan network.NetMessage)\n\t/*//connect to client\n\tfmt.Println(\"begin connect to client\")\n\tclientset := Readclientcfg()\n\tconnecttoclient(clientset, cP)*/\n\tfmt.Println(\"begin listen to client port\")\n\tgo Listentoclient(8007, cP)\n\t//load znode\n\tif root == nil {\n\t\troot = datatree.NewZnode()\n\t}\n\n\tfmt.Println(\"load a new node\")\n\t//sync with follower\n\n\t//deal with message by select\n\tfmt.Println(\"begin dealing message\")\n\tfor {\n\t\tselect {\n\t\tcase Message := <-cP:\n\t\t\tif Message.Type >= 5 {\n\t\t\t\tdatatree.DealWithMessage(Message, root)\n\t\t\t\tfmt.Printf(\"deal with message %d-%s\\n\", Message.Type, Message.Str)\n\t\t\t\tfor i := 0; i < len(Conn); i++ {\n\t\t\t\t\tnetwork.SendDataMessage(Conn[i], Message.Id, Message.Type, Message.Info, Message.Str)\n\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif Message.Type == 7 {\n\t\t\t\tstr := datatree.LookZnode(Message.Str, root)\n\t\t\t\tnetwork.SendOnetimeMessage(Message.Info, Message.Id, Message.Type, Message.Info, str)\n\t\t\t\tfmt.Printf(\"deal with message %d-%s\\n\", Message.Type, Message.Str)\n\t\t\t}\n\t\tcase Message := <-network.CR:\n\t\t\tif Message.Type <= 3 {\n\t\t\t\tfmt.Printf(\"deal with message %d-%s\\n\", Message.Type, Message.Str)\n\t\t\t\tfor i := 0; i < len(Conn); i++ {\n\t\t\t\t\tnetwork.SendMessage(Conn[i], network.Winner, 3, network.Winner)\n\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif Message.Type == 9 {\n\t\t\t\tfmt.Printf(\"deal with message %d-%s\\n\", Message.Type, Message.Str)\n\t\t\t\tfor j := 0; j < 2; j++ {\n\t\t\t\t\tif network.Peerset[j].Sid == Message.Id {\n\t\t\t\t\t\tfor i := Message.Info + 1; i <= replicalog.Lognum; i++ {\n\t\t\t\t\t\t\tnetwork.SendDataMessage(Conn[j], network.Winner, replicalog.Getlog(i).Action, replicalog.Getlog(i).Info, replicalog.Getlog(i).Str)\n\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\n}", "func (s *HTTPServer) parseConsistency(resp http.ResponseWriter, req *http.Request, b *structs.QueryOptions) bool {\n\tquery := req.URL.Query()\n\tdefaults := true\n\tif _, ok := query[\"stale\"]; ok {\n\t\tb.AllowStale = true\n\t\tdefaults = false\n\t}\n\tif _, ok := query[\"consistent\"]; ok {\n\t\tb.RequireConsistent = true\n\t\tdefaults = false\n\t}\n\tif _, ok := query[\"leader\"]; ok {\n\t\tdefaults = false\n\t}\n\tif _, ok := query[\"cached\"]; ok {\n\t\tb.UseCache = true\n\t\tdefaults = false\n\t}\n\tif maxStale := query.Get(\"max_stale\"); maxStale != \"\" {\n\t\tdur, err := time.ParseDuration(maxStale)\n\t\tif err != nil {\n\t\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\t\tfmt.Fprintf(resp, \"Invalid max_stale value %q\", maxStale)\n\t\t\treturn true\n\t\t}\n\t\tb.MaxStaleDuration = dur\n\t\tif dur.Nanoseconds() > 0 {\n\t\t\tb.AllowStale = true\n\t\t\tdefaults = false\n\t\t}\n\t}\n\t// No specific Consistency has been specified by caller\n\tif defaults {\n\t\tpath := req.URL.Path\n\t\tif strings.HasPrefix(path, \"/v1/catalog\") || strings.HasPrefix(path, \"/v1/health\") {\n\t\t\tif s.agent.config.DiscoveryMaxStale.Nanoseconds() > 0 {\n\t\t\t\tb.MaxStaleDuration = s.agent.config.DiscoveryMaxStale\n\t\t\t\tb.AllowStale = true\n\t\t\t}\n\t\t}\n\t}\n\tif b.AllowStale && b.RequireConsistent {\n\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(resp, \"Cannot specify ?stale with ?consistent, conflicting semantics.\")\n\t\treturn true\n\t}\n\tif b.UseCache && b.RequireConsistent {\n\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(resp, \"Cannot specify ?cached with ?consistent, conflicting semantics.\")\n\t\treturn true\n\t}\n\treturn false\n}", "func Test_releaseLock_Update(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tf func(t *testing.T, internalClient *kubefake.Clientset, isLeader *isLeaderTracker, cancel context.CancelFunc)\n\t}{\n\t\t{\n\t\t\tname: \"renewal fails on update\",\n\t\t\tf: func(t *testing.T, internalClient *kubefake.Clientset, isLeader *isLeaderTracker, cancel context.CancelFunc) {\n\t\t\t\tinternalClient.PrependReactor(\"update\", \"*\", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\t\t\tlease := action.(kubetesting.UpdateAction).GetObject().(*coordinationv1.Lease)\n\t\t\t\t\tif len(ptr.Deref(lease.Spec.HolderIdentity, \"\")) == 0 {\n\t\t\t\t\t\trequire.False(t, isLeader.canWrite(), \"client must release in-memory leader status before Kube API call\")\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil, errors.New(\"cannot renew\")\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"renewal fails due to context\",\n\t\t\tf: func(t *testing.T, internalClient *kubefake.Clientset, isLeader *isLeaderTracker, cancel context.CancelFunc) {\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.False(t, isLeader.canWrite(), \"client must release in-memory leader status when context is canceled\")\n\t\t\t\t})\n\t\t\t\tstart := time.Now()\n\t\t\t\tinternalClient.PrependReactor(\"update\", \"*\", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\t\t\t// keep going for a bit\n\t\t\t\t\tif time.Since(start) < 5*time.Second {\n\t\t\t\t\t\treturn false, nil, nil\n\t\t\t\t\t}\n\n\t\t\t\t\tcancel()\n\t\t\t\t\treturn false, nil, nil\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\ttt := tt\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tinternalClient := kubefake.NewSimpleClientset()\n\t\t\tisLeader := &isLeaderTracker{tracker: &atomic.Bool{}}\n\n\t\t\tleaderElectorCtx, cancel := context.WithCancel(context.Background())\n\n\t\t\ttt.f(t, internalClient, isLeader, cancel)\n\n\t\t\tleaderElectionConfig := newLeaderElectionConfig(\"ns-001\", \"lease-001\", \"foo-001\", internalClient, isLeader)\n\n\t\t\t// make the tests run quicker\n\t\t\tleaderElectionConfig.LeaseDuration = 2 * time.Second\n\t\t\tleaderElectionConfig.RenewDeadline = 1 * time.Second\n\t\t\tleaderElectionConfig.RetryPeriod = 250 * time.Millisecond\n\n\t\t\t// note that this will block until it exits on its own or tt.f calls cancel()\n\t\t\tleaderelection.RunOrDie(leaderElectorCtx, leaderElectionConfig)\n\t\t})\n\t}\n}", "func TestGetPeerPersistent(t *testing.T) {\n\tseeds := []string {\"127.0.0.1:6000\",}\n\tmanager1 := CreatePeerManager(6000, 6001, nil, FullMode)\n\tmanager2 := CreatePeerManager(7000, 7001, seeds, FullMode)\n\tmanager3 := CreatePeerManager(8000, 8001, seeds, FullMode)\n\tmanager1.StatusUpdatePeriod=100*time.Millisecond\n\tmanager2.StatusUpdatePeriod=100*time.Millisecond\n\tmanager3.StatusUpdatePeriod=100*time.Millisecond\n\n\tmarkPeer := func(t *testing.T) {\n\t\tpeer1, err := manager1.GetPeerPersistent(\"client1\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetPeerPersistent(): %v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tpeer2, err := manager1.GetPeerPersistent(\"client1\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetPeerPersistent(): %v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif peer1 != peer2 {\n\t\t\tt.Errorf(\"GetPeerPersistent(): returned two different peers for the same client %v %v\\n\",\n\t\t\t\tpeer1, peer2)\n\t\t}\n\t\tmanager1.MarkPeerUnreachable(peer1)\n\t\tmanager1.MarkPeerUnreachable(peer1)\n\t\tmanager1.MarkPeerUnreachable(peer1)\n\t\ttime.Sleep(5*time.Millisecond)\n\n\t\t// after marking first peer unreachable it should return a different one\n\t\tpeer3, err := manager1.GetPeerPersistent(\"client1\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"GetPeerPersistent(): %v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif peer1 == peer3 {\n\t\t\tt.Errorf(\"GetPeerPersistent(): After marking a peer unreachable it should have returned a different one\\n\")\n\t\t}\n\t}\n\n\t// After some time has passed all the peers should be available again\n\tallPeers := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\", \"127.0.0.1:8001\"}\n\tPeerManagerPropagationHelper(t, manager1, manager2, manager3,\n\t\tallPeers, allPeers, allPeers, markPeer, 3200*time.Millisecond, 8*time.Second)\n}", "func TestClusteringRestartClusterWithSnapshotOfDeletedChannel(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\trestoreMsgsAttempts = 2\n\trestoreMsgsRcvTimeout = 50 * time.Millisecond\n\trestoreMsgsSleepBetweenAttempts = 0\n\tdefer func() {\n\t\trestoreMsgsAttempts = defaultRestoreMsgsAttempts\n\t\trestoreMsgsRcvTimeout = defaultRestoreMsgsRcvTimeout\n\t\trestoreMsgsSleepBetweenAttempts = defaultRestoreMsgsSleepBetweenAttempts\n\t}()\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\tmaxInactivity := 250 * time.Millisecond\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1sOpts.Clustering.TrailingLogs = 0\n\ts1sOpts.MaxInactivity = maxInactivity\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2sOpts.Clustering.TrailingLogs = 0\n\ts2sOpts.MaxInactivity = maxInactivity\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3sOpts.Clustering.TrailingLogs = 0\n\ts3sOpts.MaxInactivity = maxInactivity\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\n\t// Wait for leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Send a message, which will create the channel\n\tchannel := \"foo\"\n\texpectedMsg := make(map[uint64]msg)\n\texpectedMsg[1] = msg{sequence: 1, data: []byte(\"first\")}\n\texpectedMsg[2] = msg{sequence: 2, data: []byte(\"second\")}\n\texpectedMsg[3] = msg{sequence: 3, data: []byte(\"third\")}\n\tfor i := 1; i < 4; i++ {\n\t\tif err := sc.Publish(channel, expectedMsg[uint64(i)].data); err != nil {\n\t\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t\t}\n\t}\n\tsc.Close()\n\t// Wait for channel to be replicated in all servers\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 3, expectedMsg, servers...)\n\n\t// Perform snapshot on all servers.\n\tfor _, s := range servers {\n\t\tif err := s.raft.Snapshot().Error(); err != nil {\n\t\t\tt.Fatalf(\"Error during snapshot: %v\", err)\n\t\t}\n\t}\n\n\t// Wait for channel to be removed due to inactivity..\n\ttime.Sleep(2 * maxInactivity)\n\n\t// Restart all servers\n\tservers = restartServers(t, servers)\n\tdefer shutdownServers(servers)\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Now send a single message. The channel will be recreated.\n\tsc, err = stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\texpectedMsg = make(map[uint64]msg)\n\texpectedMsg[1] = msg{sequence: 1, data: []byte(\"new first\")}\n\tif err := sc.Publish(channel, expectedMsg[1].data); err != nil {\n\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t}\n\tsc.Close()\n\n\t// Wait for channel to be replicated in all servers\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 1, expectedMsg, servers...)\n\n\t// Shutdown all servers and restart them\n\tservers = restartServers(t, servers)\n\tdefer shutdownServers(servers)\n\t// Make sure they succeed\n\tgetLeader(t, 10*time.Second, servers...)\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 1, expectedMsg, servers...)\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n persister *Persister, applyCh chan ApplyMsg) *Raft {\n rf := &Raft{}\n rf.peers = peers\n rf.persister = persister\n rf.me = me\n\n // Your initialization code here (2A, 2B, 2C).\n rf.state = StateFollower\n rf.commitIndex = 0\n rf.votedFor = nilIndex\n rf.lastApplied = 0\n rf.currentTerm = 0\n // rf.log contains a dummy head\n rf.log = []LogEntry{LogEntry{rf.currentTerm, nil}}\n\n // initialize from state persisted before a crash\n rf.readPersist(persister.ReadRaftState())\n\n rf.print(\"Initialize\")\n // All servers\n go func() {\n for {\n if rf.isKilled {\n return\n }\n rf.mu.Lock()\n for rf.commitIndex > rf.lastApplied {\n rf.lastApplied++\n applyMsg := ApplyMsg{rf.lastApplied, rf.log[rf.lastApplied].Command, false, nil}\n applyCh <- applyMsg\n rf.print(\"applied log entry %d:%v\", rf.lastApplied, rf.log[rf.lastApplied])\n // Apply rf.log[lastApplied] into its state machine\n }\n rf.mu.Unlock()\n time.Sleep(50 * time.Millisecond)\n }\n }()\n\n // candidate thread\n go func() {\n var counterLock sync.Mutex\n for {\n if rf.isKilled {\n return\n }\n rf.mu.Lock()\n\t\t\tif rf.state == StateFollower { // ONLY follower would have election timeout\n\t\t\t\trf.state = StateCandidate\n\t\t\t}\n rf.mu.Unlock()\n duration := time.Duration(electionTimeout +\n Random(-electionRandomFactor, electionRandomFactor))\n time.Sleep(duration * time.Millisecond)\n rf.mu.Lock()\n\n if rf.state == StateCandidate {\n rf.print(\"start to request votes for term %d\", rf.currentTerm+1)\n counter := 0\n logLen := len(rf.log)\n lastTerm := 0\n lastIndex := logLen-1\n requestTerm := rf.currentTerm+1\n if logLen > 0 {\n lastTerm = rf.log[logLen-1].Term\n }\n rvArgs := RequestVoteArgs{requestTerm, rf.me, lastIndex, lastTerm}\n rvReplies := make([]RequestVoteReply, len(rf.peers))\n\n for index := range rf.peers {\n go func(index int) {\n ok := rf.sendRequestVote(index, &rvArgs, &rvReplies[index])\n rf.mu.Lock()\n if rvReplies[index].Term > rf.currentTerm {\n rf.currentTerm = rvReplies[index].Term\n rf.state = StateFollower\n rf.persist()\n }else if ok && (rvArgs.Term == rf.currentTerm) && rvReplies[index].VoteGranted {\n counterLock.Lock()\n counter++\n if counter > len(rf.peers)/2 && rf.state != StateLeader {\n rf.state = StateLeader\n rf.currentTerm = requestTerm\n rf.nextIndex = make([]int, len(rf.peers))\n rf.matchIndex = make([]int, len(rf.peers))\n // immediately send heartbeats to others to stop election\n for i := range rf.peers {\n rf.nextIndex[i] = len(rf.log)\n }\n rf.persist()\n\n rf.print(\"become leader for term %d, nextIndex = %v, rvArgs = %v\", rf.currentTerm, rf.nextIndex, rvArgs)\n }\n counterLock.Unlock()\n }\n rf.mu.Unlock()\n }(index)\n }\n }\n rf.mu.Unlock()\n }\n }()\n\n // leader thread\n go func(){\n for {\n if rf.isKilled {\n return\n }\n time.Sleep(heartbeatTimeout * time.Millisecond)\n rf.mu.Lock()\n // send AppendEntries(as heartbeats) RPC\n if rf.state == StateLeader {\n currentTerm := rf.currentTerm\n for index := range rf.peers {\n go func(index int) {\n // decrease rf.nextIndex[index] in loop till append success\n for {\n if index == rf.me || rf.state != StateLeader {\n break\n }\n // if rf.nextIndex[index] <= 0 || rf.nextIndex[index] > len(rf.log){\n // rf.print(\"Error: rf.nextIndex[%d] = %d, logLen = %d\", index, rf.nextIndex[index], len(rf.log))\n // }\n rf.mu.Lock()\n logLen := len(rf.log)\n appendEntries := rf.log[rf.nextIndex[index]:]\n prevIndex := rf.nextIndex[index]-1\n aeArgs := AppendEntriesArgs{currentTerm, rf.me,\n prevIndex, rf.log[prevIndex].Term,\n appendEntries, rf.commitIndex}\n aeReply := AppendEntriesReply{}\n rf.mu.Unlock()\n\n ok := rf.sendAppendEntries(index, &aeArgs, &aeReply)\n rf.mu.Lock()\n if ok && rf.currentTerm == aeArgs.Term { // ensure the reply is not outdated\n if aeReply.Success {\n rf.matchIndex[index] = logLen-1\n rf.nextIndex[index] = logLen\n rf.mu.Unlock()\n break\n }else {\n if aeReply.Term > rf.currentTerm { // this leader node is outdated\n rf.currentTerm = aeReply.Term\n rf.state = StateFollower\n rf.persist()\n rf.mu.Unlock()\n break\n }else{ // prevIndex not match, decrease prevIndex\n // rf.nextIndex[index]--\n // if aeReply.ConflictFromIndex <= 0 || aeReply.ConflictFromIndex >= logLen{\n // rf.print(\"Error: aeReply.ConflictFromIndex from %d = %d, logLen = %d\", aeReply.ConflictFromIndex, index, logLen)\n // }\n rf.nextIndex[index] = aeReply.ConflictFromIndex\n }\n }\n }\n rf.mu.Unlock()\n }\n }(index)\n }\n\n // Find logs that has appended to majority and update commitIndex\n for N := rf.commitIndex+1; N<len(rf.log); N++ {\n // To eliminate problems like the one in Figure 8,\n // Raft never commits log entries from previous terms by count- ing replicas. \n if rf.log[N].Term < rf.currentTerm{\n continue\n }else if rf.log[N].Term > rf.currentTerm{\n break\n }\n followerHas := 0\n for index := range rf.peers {\n if rf.matchIndex[index] >= N{\n followerHas++\n }\n }\n // If majority has the log entry of index N\n if followerHas > len(rf.peers) / 2 {\n rf.print(\"set commitIndex to %d, matchIndex = %v\", N, rf.matchIndex)\n rf.commitIndex = N\n }\n }\n }\n rf.mu.Unlock()\n }\n }()\n\n return rf\n}", "func (mp *metaPartition) HandleLeaderChange(leader uint64) {\n\texporter.Warning(fmt.Sprintf(\"metaPartition(%v) changeLeader to (%v)\", mp.config.PartitionId, leader))\n\tif mp.config.NodeId == leader {\n\t\tconn, err := net.DialTimeout(\"tcp\", net.JoinHostPort(\"127.0.0.1\", serverPort), time.Second)\n\t\tif err != nil {\n\t\t\tlog.LogErrorf(fmt.Sprintf(\"HandleLeaderChange serverPort not exsit ,error %v\", err))\n\t\t\tgo mp.raftPartition.TryToLeader(mp.config.PartitionId)\n\t\t\treturn\n\t\t}\n\t\tlog.LogDebugf(\"[metaPartition] HandleLeaderChange close conn %v, nodeId: %v, leader: %v\", serverPort, mp.config.NodeId, leader)\n\t\tconn.(*net.TCPConn).SetLinger(0)\n\t\tconn.Close()\n\t}\n\tif mp.config.NodeId != leader {\n\t\tlog.LogDebugf(\"[metaPartition] pid: %v HandleLeaderChange become unleader nodeId: %v, leader: %v\", mp.config.PartitionId, mp.config.NodeId, leader)\n\t\tmp.storeChan <- &storeMsg{\n\t\t\tcommand: stopStoreTick,\n\t\t}\n\t\treturn\n\t}\n\tmp.storeChan <- &storeMsg{\n\t\tcommand: startStoreTick,\n\t}\n\tlog.LogDebugf(\"[metaPartition] pid: %v HandleLeaderChange become leader conn %v, nodeId: %v, leader: %v\", mp.config.PartitionId, serverPort, mp.config.NodeId, leader)\n\tif mp.config.Start == 0 && mp.config.Cursor == 0 {\n\t\tid, err := mp.nextInodeID()\n\t\tif err != nil {\n\t\t\tlog.LogFatalf(\"[HandleLeaderChange] init root inode id: %s.\", err.Error())\n\t\t}\n\t\tino := NewInode(id, proto.Mode(os.ModePerm|os.ModeDir))\n\t\tgo mp.initInode(ino)\n\t}\n}", "func waitForConsistency() {\n\ttime.Sleep(500 * time.Millisecond)\n}", "func (s *Server) forward(method string, info structs.RPCInfo, args interface{}, reply interface{}) (bool, error) {\n\tvar firstCheck time.Time\n\n\t// Handle DC forwarding\n\tdc := info.RequestDatacenter()\n\tif dc != s.config.Datacenter {\n\t\terr := s.forwardDC(method, dc, args, reply)\n\t\treturn true, err\n\t}\n\n\t// Check if we can allow a stale read, ensure our local DB is initialized\n\tif info.IsRead() && info.AllowStaleRead() && !s.raft.LastContact().IsZero() {\n\t\treturn false, nil\n\t}\n\nCHECK_LEADER:\n\t// Fail fast if we are in the process of leaving\n\tselect {\n\tcase <-s.leaveCh:\n\t\treturn true, structs.ErrNoLeader\n\tdefault:\n\t}\n\n\t// Find the leader\n\tisLeader, leader := s.getLeader()\n\n\t// Handle the case we are the leader\n\tif isLeader {\n\t\treturn false, nil\n\t}\n\n\t// Handle the case of a known leader\n\trpcErr := structs.ErrNoLeader\n\tif leader != nil {\n\t\trpcErr = s.connPool.RPC(s.config.Datacenter, leader.Addr,\n\t\t\tleader.Version, method, leader.UseTLS, args, reply)\n\t\tif rpcErr != nil && canRetry(info, rpcErr) {\n\t\t\tgoto RETRY\n\t\t}\n\t\treturn true, rpcErr\n\t}\n\nRETRY:\n\t// Gate the request until there is a leader\n\tif firstCheck.IsZero() {\n\t\tfirstCheck = time.Now()\n\t}\n\tif time.Since(firstCheck) < s.config.RPCHoldTimeout {\n\t\tjitter := lib.RandomStagger(s.config.RPCHoldTimeout / jitterFraction)\n\t\tselect {\n\t\tcase <-time.After(jitter):\n\t\t\tgoto CHECK_LEADER\n\t\tcase <-s.leaveCh:\n\t\tcase <-s.shutdownCh:\n\t\t}\n\t}\n\n\t// No leader found and hold time exceeded\n\treturn true, rpcErr\n}", "func TestRaftNewLeader(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tclusterPrefix := \"TestRaftNewLeader\"\n\n\t// Create n1 node.\n\tstorage := NewStorage(NewMemSnapshotMgr(), NewMemLog(), NewMemState(0))\n\tfsm1 := newTestFSM(ID1)\n\t// NOTE we use different cluster ID for nodes within same cluster to avoid\n\t// registering same metric path twice. This should never happen in real world\n\t// because we'll never run nodes of a same cluster within one process.\n\tn1 := testCreateRaftNode(getTestConfig(ID1, clusterPrefix+ID1), storage)\n\t// Create n2 node.\n\tstorage = NewStorage(NewMemSnapshotMgr(), NewMemLog(), NewMemState(0))\n\tfsm2 := newTestFSM(ID2)\n\tn2 := testCreateRaftNode(getTestConfig(ID2, clusterPrefix+ID2), storage)\n\tconnectAllNodes(n1, n2)\n\tn1.Start(fsm1)\n\tn2.Start(fsm2)\n\tn2.ProposeInitialMembership([]string{ID1, ID2})\n\n\t// Wait until a leader is elected.\n\tselect {\n\tcase <-fsm1.leaderCh:\n\tcase <-fsm2.leaderCh:\n\t}\n}", "func hasStalePrimary(fsm fsm, srv description.Server) bool {\n\t// Compare the election ID values of the server and the topology lexicographically.\n\tcompRes := bytes.Compare(srv.ElectionID[:], fsm.maxElectionID[:])\n\n\tif wireVersion := srv.WireVersion; wireVersion != nil && wireVersion.Max >= 17 {\n\t\t// In the Post-6.0 case, a primary is considered \"stale\" if the server's election ID is greather than the\n\t\t// topology's max election ID. In these versions, the primary is also considered \"stale\" if the server's\n\t\t// election ID is LTE to the topologies election ID and the server's \"setVersion\" is less than the topology's\n\t\t// max \"setVersion\".\n\t\treturn compRes == -1 || (compRes != 1 && srv.SetVersion < fsm.maxSetVersion)\n\t}\n\n\t// If the server's election ID is less than the topology's max election ID, the primary is considered\n\t// \"stale\". Similarly, if the server's \"setVersion\" is less than the topology's max \"setVersion\", the\n\t// primary is considered stale.\n\treturn compRes == -1 || fsm.maxSetVersion > srv.SetVersion\n}", "func TestConnection(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\n\tname := \"sharded_message\"\n\n\t// 1 sec sleep added to avoid invalid connection count\n\ttime.Sleep(time.Second)\n\n\t// create two grpc connection with vtgate and verify\n\t// client connection count in vttablet of the master\n\tassert.Equal(t, 0, getClientCount(shard0Master))\n\tassert.Equal(t, 0, getClientCount(shard1Master))\n\n\tctx := context.Background()\n\t// first connection with vtgate\n\tstream, err := VtgateGrpcConn(ctx, clusterInstance)\n\trequire.Nil(t, err)\n\t_, err = stream.MessageStream(userKeyspace, \"\", nil, name)\n\trequire.Nil(t, err)\n\t// validate client count of vttablet\n\tassert.Equal(t, 1, getClientCount(shard0Master))\n\tassert.Equal(t, 1, getClientCount(shard1Master))\n\t// second connection with vtgate, secont connection\n\t// will only be used for client connection counts\n\tstream1, err := VtgateGrpcConn(ctx, clusterInstance)\n\trequire.Nil(t, err)\n\t_, err = stream1.MessageStream(userKeyspace, \"\", nil, name)\n\trequire.Nil(t, err)\n\t// validate client count of vttablet\n\tassert.Equal(t, 2, getClientCount(shard0Master))\n\tassert.Equal(t, 2, getClientCount(shard1Master))\n\n\t// insert data in master and validate that we receive this\n\t// in message stream\n\tsession := stream.Session(\"@master\", nil)\n\t// insert data in master\n\tcluster.ExecuteQueriesUsingVtgate(t, session, \"insert into sharded_message (id, message) values (2,'hello world 2')\")\n\tcluster.ExecuteQueriesUsingVtgate(t, session, \"insert into sharded_message (id, message) values (5,'hello world 5')\")\n\t// validate in msg stream\n\t_, err = stream.Next()\n\trequire.Nil(t, err)\n\t_, err = stream.Next()\n\trequire.Nil(t, err)\n\n\t_, err = stream.MessageAck(ctx, userKeyspace, name, keyRange(2, 5))\n\trequire.Nil(t, err)\n\t// After closing one stream, ensure vttablets have dropped it.\n\tstream.Close()\n\ttime.Sleep(time.Second)\n\tassert.Equal(t, 1, getClientCount(shard0Master))\n\tassert.Equal(t, 1, getClientCount(shard1Master))\n\n\tstream1.Close()\n}", "func TestAddNodeCheckQuorum(t *testing.T) {\n\tr := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(r)\n\tr.pendingConf = true\n\tr.checkQuorum = true\n\n\tr.becomeCandidate()\n\tr.becomeLeader()\n\n\tfor i := 0; i < r.electionTimeout-1; i++ {\n\t\tr.tick()\n\t}\n\tgrp := pb.Group{\n\t\tNodeId: 2,\n\t\tGroupId: 1,\n\t\tRaftReplicaId: 2,\n\t}\n\tr.addNode(2, grp)\n\n\t// This tick will reach electionTimeout, which triggers a quorum check.\n\tr.tick()\n\n\t// Node 1 should still be the leader after a single tick.\n\tif r.state != StateLeader {\n\t\tt.Errorf(\"state = %v, want %v\", r.state, StateLeader)\n\t}\n\n\t// After another electionTimeout ticks without hearing from node 2,\n\t// node 1 should step down.\n\tfor i := 0; i < r.electionTimeout; i++ {\n\t\tr.tick()\n\t}\n\n\tif r.state != StateFollower {\n\t\tt.Errorf(\"state = %v, want %v\", r.state, StateFollower)\n\t}\n}", "func (c *consulClient) AcquireLeadership(key string, session *string) (acquired bool) {\n\n\t// Attempt to inspect the leadership key if it is available and present.\n\tk, _, err := c.consul.KV().Get(key, nil)\n\n\tif err != nil {\n\t\tlogging.Error(\"client/consul: unable to read the leader key at %s\", key)\n\t\treturn false\n\t}\n\n\t// Check we have a valid session.\n\ts, _, err := c.consul.Session().Info(*session, nil)\n\tif err != nil {\n\t\tlogging.Error(\"client/consul: unable to read the leader key at %s\", key)\n\t\treturn false\n\t}\n\n\t// If the session is not valid, set our state to default\n\tif s == nil {\n\t\tlogging.Error(\"client/consul: the Consul session %s has expired, revoking from Replicator\", *session)\n\t\t*session = \"\"\n\t\treturn false\n\t}\n\n\t// On a fresh cluster the KV might not exist yet, so we need to check for nil\n\t// return. If the leadership lock is tied to our session then we can exit and\n\t// confirm we are running as the replicator leader without having to make on\n\t// further calls.\n\tif k != nil && k.Session == *session {\n\t\treturn true\n\t}\n\n\tkp := &consul.KVPair{\n\t\tKey: key,\n\t\tSession: *session,\n\t}\n\n\tlogging.Debug(\"client/consul: attempting to acquire leadership lock at %s\", key)\n\tresp, _, err := c.consul.KV().Acquire(kp, nil)\n\n\tif err != nil {\n\t\tlogging.Error(\"client/consul: issue requesting leadership lock: %v\", err)\n\t\treturn false\n\t}\n\n\t// We have successfully obtained the leadership and can now be considered as\n\t// the replicator leader.\n\tif resp {\n\t\tlogging.Info(\"client/consul: leadership lock successfully obtained at %s\", key)\n\t\tmetrics.IncrCounter([]string{\"cluster\", \"leadership\", \"election\"}, 1)\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestRaft1(t *testing.T) {\n\n\t//Remove any state recovery files\n\tfor i := 0; i < 5; i++ {\n\t\tos.Remove(fmt.Sprintf(\"%s_S%d.state\", raft.FILENAME, i))\n\t}\n\n\tgo main() //Starts all servers\n\n\tvar leaderId1, leaderId2 int\n\tack := make(chan bool)\n\n\ttime.AfterFunc(1*time.Second, func() {\n\t\tcheckIfLeaderExist(t)\n\t\tleaderId1 = raft.KillLeader() //Kill leader\n\t\tlog.Print(\"Killed leader:\", leaderId1)\n\t})\n\n\ttime.AfterFunc(2*time.Second, func() {\n\t\tcheckIfLeaderExist(t)\n\t\tleaderId2 = raft.KillLeader() //Kill current leader again\n\t\tlog.Print(\"Killed leader:\", leaderId2)\n\t})\n\n\ttime.AfterFunc(3*time.Second, func() {\n\t\tcheckIfLeaderExist(t)\n\t\traft.ResurrectServer(leaderId2) //Resurrect last killed as follower\n\t\tlog.Print(\"Resurrected previous leader:\", leaderId2)\n\t})\n\n\ttime.AfterFunc(4*time.Second, func() {\n\t\tcheckIfLeaderExist(t)\n\t\traft.ResurrectServerAsLeader(leaderId1) //Ressurect first one as leader\n\t\tlog.Print(\"Resurrected previous leader:\", leaderId1)\n\t})\n\n\ttime.AfterFunc(5*time.Second, func() {\n\t\tcheckIfLeaderExist(t)\n\t\tack <- true\n\t})\n\n\t<-ack\n}", "func (r *Raft) becomeLeader() {\n\t// Your Code Here (2A).\n\t// NOTE: Leader should propose a noop entry on its term\n\tif _, ok := r.Prs[r.id]; !ok {\n\t\treturn\n\t}\n\tlog.DInfo(\"r %d becomes the leader in term %d\", r.id, r.Term)\n\tr.State = StateLeader\n\tr.Lead = r.id\n\tr.Vote = r.id\n\tr.heartbeatElapsed = 0\n\tr.electionElapsed = 0\n\tr.actualElectionTimeout = rand.Intn(r.electionTimeout) + r.electionTimeout\n\t// 成为 leader 以后要重新设置日志同步信息,注意自己的日志同步信息应该一直是最新的,否则会影响 commit 计算\n\tfor k := range r.Prs {\n\t\tif k == r.id { // 不可以超出 peers 的范围\n\t\t\tr.Prs[r.id] = &Progress{\n\t\t\t\tMatch: r.RaftLog.LastIndex(),\n\t\t\t\tNext: r.RaftLog.LastIndex() + 1,\n\t\t\t}\n\t\t} else {\n\t\t\tr.Prs[k] = &Progress{\n\t\t\t\tMatch: 0,\n\t\t\t\tNext: r.RaftLog.LastIndex() + 1,\n\t\t\t}\n\t\t}\n\t}\n\t// raft 要求 leader 不能提交之前任期的日志条目,或者说,提交的日志条目必须包含自己的任期\n\t// 为了在本任期没有收到同步请求的情况下也要能提交之前的日志,应当在成为 leader 的时候立刻 propose 一个空条目并 append 下去\n\t_ = r.Step(pb.Message{\n\t\tMsgType: pb.MessageType_MsgPropose,\n\t\tTo: r.id,\n\t\tFrom: r.id,\n\t\tTerm: r.Term,\n\t\tEntries: []*pb.Entry{{\n\t\t\tEntryType: pb.EntryType_EntryNormal,\n\t\t\tTerm: 0,\n\t\t\tIndex: 0,\n\t\t\tData: nil,\n\t\t}},\n\t})\n}", "func (ml *MultiLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error) {\n\tprimary, primaryRaw, err := ml.Primary.Get(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsecondary, secondaryRaw, err := ml.Secondary.Get(ctx)\n\tif err != nil {\n\t\t// Lock is held by old client\n\t\tif apierrors.IsNotFound(err) && primary.HolderIdentity != ml.Identity() {\n\t\t\treturn primary, primaryRaw, nil\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\tif primary.HolderIdentity != secondary.HolderIdentity {\n\t\tprimary.HolderIdentity = UnknownLeader\n\t\tprimaryRaw, err = json.Marshal(primary)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn primary, ConcatRawRecord(primaryRaw, secondaryRaw), nil\n}", "func TestPartition(t *testing.T) {\n\traftConf := &RaftConfig{MemberRegSocket: \"127.0.0.1:8124\", PeerSocket: \"127.0.0.1:9987\", TimeoutInMillis: 1500, HbTimeoutInMillis: 150, LogDirectoryPath: \"logs1\", StableStoreDirectoryPath: \"./stable1\", RaftLogDirectoryPath: \"../LocalLog1\"}\n\n\t// delete stored state to avoid unnecessary effect on following test cases\n\tinitState(raftConf.StableStoreDirectoryPath, raftConf.LogDirectoryPath, raftConf.RaftLogDirectoryPath)\n\n\t// launch cluster proxy servers\n\tcluster.NewProxyWithConfig(RaftToClusterConf(raftConf))\n\n\tfmt.Println(\"Started Proxy\")\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\tserverCount := 5\n\traftServers := make([]raft.Raft, serverCount+1)\n\tpseudoClusters := make([]*test.PseudoCluster, serverCount+1)\n\n\tfor i := 1; i <= serverCount; i += 1 {\n\t\t// create cluster.Server\n\t\tclusterServer, err := cluster.NewWithConfig(i, \"127.0.0.1\", 8500+i, RaftToClusterConf(raftConf))\n\t\tpseudoCluster := test.NewPseudoCluster(clusterServer)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error in creating cluster server. \" + err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tlogStore, err := llog.Create(raftConf.RaftLogDirectoryPath + \"/\" + strconv.Itoa(i))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error in creating log. \" + err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ts, err := NewWithConfig(pseudoCluster, logStore, raftConf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error in creating Raft servers. \" + err.Error())\n\t\t\treturn\n\t\t}\n\t\traftServers[i] = s\n\t\tpseudoClusters[i] = pseudoCluster\n\t}\n\n\t// wait for leader to be elected\n\ttime.Sleep(20 * time.Second)\n\tcount := 0\n\toldLeader := 0\n\tfor i := 1; i <= serverCount; i += 1 {\n\t\tif raftServers[i].Leader() == raftServers[i].Pid() {\n\t\t\toldLeader = i\n\t\t\tcount++\n\t\t}\n\t}\n\tif count != 1 {\n\t\tt.Errorf(\"No leader was chosen in 1 minute\")\n\t\treturn\n\t}\n\n\t// isolate Leader and any one follower\n\tfollower := 0\n\tfor i := 1; i <= serverCount; i += 1 {\n\t\tif i != oldLeader {\n\t\t\tfollower = i\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println(\"Server \" + strconv.Itoa(follower) + \" was chosen as follower in minority partition\")\n\tfor i := 1; i <= serverCount; i += 1 {\n\t\tpseudoClusters[oldLeader].AddToInboxFilter(raftServers[i].Pid())\n\t\tpseudoClusters[oldLeader].AddToOutboxFilter(raftServers[i].Pid())\n\t\tpseudoClusters[follower].AddToInboxFilter(raftServers[i].Pid())\n\t\tpseudoClusters[follower].AddToOutboxFilter(raftServers[i].Pid())\n\t}\n\n\tpseudoClusters[oldLeader].AddToOutboxFilter(cluster.BROADCAST)\n\tpseudoClusters[follower].AddToOutboxFilter(cluster.BROADCAST)\n\n\t// wait for other servers to discover that leader\n\t// has crashed and to elect a new leader\n\ttime.Sleep(20 * time.Second)\n\n\tcount = 0\n\tfor i := 1; i <= serverCount; i += 1 {\n\n\t\tif i != oldLeader && i != follower && raftServers[i].Leader() == raftServers[i].Pid() {\n\t\t\tfmt.Println(\"Server \" + strconv.Itoa(i) + \" was chosen as new leader in majority partition.\")\n\t\t\tcount++\n\t\t}\n\t}\n\t// new leader must be chosen\n\tif count != 1 {\n\t\tt.Errorf(\"No leader was chosen in majority partition\")\n\t}\n}", "func (rf *Raft) Start(command interface{}) (int, int, bool) {\n\tDPrintf(\"peer-%d ----------------------Start()-----------------------\", rf.me)\n\tindex := -1\n\tterm := -1\n\tisLeader := true\n\n\t// Your code here (2B).\n\t//term, isLeader = rf.GetState()\n\trf.mu.Lock()\n\tterm = rf.currentTerm\n\tif rf.state != Leader {\n\t\tisLeader = false\n\t}\n\tif isLeader {\n\t\t// Append the command into its own rf.log\n\t\tvar newlog LogEntry\n\t\tnewlog.Term = rf.currentTerm\n\t\tnewlog.Command = command\n\t\trf.log = append(rf.log, newlog)\n\t\trf.persist()\n\t\tindex = len(rf.log) // the 3rd return value.\n\t\trf.repCount[index] = 1\n\t\t// now the log entry is appended into leader's log.\n\t\trf.mu.Unlock()\n\n\t\t// start agreement and return immediately.\n\t\tfor peer_index, _ := range rf.peers {\n\t\t\tif peer_index == rf.me {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// send AppendEntries RPC to each peer. And decide when it is safe to apply a log entry to the state machine.\n\t\t\tgo func(i int) {\n\t\t\t\trf.mu.Lock()\n\t\t\t\tnextIndex_copy := make([]int, len(rf.peers))\n\t\t\t\tcopy(nextIndex_copy, rf.nextIndex)\n\t\t\t\trf.mu.Unlock()\n\t\t\t\tfor {\n\t\t\t\t\t// make a copy of current leader's state.\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t// we should not send RPC if rf.currentTerm != term, the log entry will be sent in later AE-RPCs in args.Entries.\n\t\t\t\t\tif rf.state != Leader || rf.currentTerm != term {\n\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// make a copy of leader's raft state.\n\t\t\t\t\tcommitIndex_copy := rf.commitIndex // during the agreement, commitIndex may increase.\n\t\t\t\t\tlog_copy := make([]LogEntry, len(rf.log)) // during the agreement, log could grow.\n\t\t\t\t\tcopy(log_copy, rf.log)\n\t\t\t\t\trf.mu.Unlock()\n\n\t\t\t\t\tvar args AppendEntriesArgs\n\t\t\t\t\tvar reply AppendEntriesReply\n\t\t\t\t\targs.Term = term\n\t\t\t\t\targs.LeaderId = rf.me\n\t\t\t\t\targs.LeaderCommit = commitIndex_copy\n\t\t\t\t\t// If last log index >= nextIndex for a follower: send AppendEntries RPC with log entries starting at nextIndex\n\t\t\t\t\t// NOTE: nextIndex is just a predication. not a precise value.\n\t\t\t\t\targs.PrevLogIndex = nextIndex_copy[i] - 1\n\t\t\t\t\tif args.PrevLogIndex > 0 {\n\t\t\t\t\t\t// FIXME: when will this case happen??\n\t\t\t\t\t\tif args.PrevLogIndex > len(log_copy) {\n\t\t\t\t\t\t\t// TDPrintf(\"adjust PrevLogIndex.\")\n\t\t\t\t\t\t\t//return\n\t\t\t\t\t\t\targs.PrevLogIndex = len(log_copy)\n\t\t\t\t\t\t}\n\t\t\t\t\t\targs.PrevLogTerm = log_copy[args.PrevLogIndex-1].Term\n\t\t\t\t\t}\n\t\t\t\t\targs.Entries = make([]LogEntry, len(log_copy)-args.PrevLogIndex)\n\t\t\t\t\tcopy(args.Entries, log_copy[args.PrevLogIndex:len(log_copy)])\n\t\t\t\t\tok := rf.sendAppendEntries(i, &args, &reply)\n\t\t\t\t\t// handle RPC reply in the same goroutine.\n\t\t\t\t\tif ok == true {\n\t\t\t\t\t\tif reply.Success == true {\n\t\t\t\t\t\t\t// this case means that the log entry is replicated successfully.\n\t\t\t\t\t\t\tDPrintf(\"peer-%d AppendEntries success!\", rf.me)\n\t\t\t\t\t\t\t// re-establish the assumption.\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\tif rf.state != Leader || rf.currentTerm != term {\n\t\t\t\t\t\t\t\t//Figure-8 and p-8~9: never commits log entries from previous terms by counting replicas!\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// NOTE: TA's QA: nextIndex[i] should not decrease, so check and set.\n\t\t\t\t\t\t\tif index >= rf.nextIndex[i] {\n\t\t\t\t\t\t\t\trf.nextIndex[i] = index + 1\n\t\t\t\t\t\t\t\t// TA's QA\n\t\t\t\t\t\t\t\trf.matchIndex[i] = args.PrevLogIndex + len(args.Entries) // matchIndex is not used in my implementation.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// test whether we can update the leader's commitIndex.\n\t\t\t\t\t\t\trf.repCount[index]++\n\t\t\t\t\t\t\t// update leader's commitIndex! We can determine that Figure-8's case will not occur now,\n\t\t\t\t\t\t\t// because we have test rf.currentTerm == term_copy before, so we will never commit log entries from previous terms.\n\t\t\t\t\t\t\tif rf.commitIndex < index && rf.repCount[index] > len(rf.peers)/2 {\n\t\t\t\t\t\t\t\t// apply the command.\n\t\t\t\t\t\t\t\tDPrintf(\"peer-%d Leader moves its commitIndex from %d to %d.\", rf.me, rf.commitIndex, index)\n\t\t\t\t\t\t\t\t// NOTE: the Leader should commit one by one.\n\t\t\t\t\t\t\t\trf.commitIndex = index\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\t// now the command at commitIndex is committed.\n\t\t\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\t\t\trf.canApplyCh <- true\n\t\t\t\t\t\t\t\t}()\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn // jump out of the loop.\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// AppendEntries RPC fails because of log inconsistency: Decrement nextIndex and retry\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\t// re-establish the assumption.\n\t\t\t\t\t\t\tif rf.state != Leader || rf.currentTerm != term {\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif reply.Term > rf.currentTerm {\n\t\t\t\t\t\t\t\trf.state = Follower\n\t\t\t\t\t\t\t\trf.currentTerm = reply.Term\n\t\t\t\t\t\t\t\trf.persist()\n\t\t\t\t\t\t\t\trf.resetElectionTimeout()\n\t\t\t\t\t\t\t\tDPrintf(\"peer-%d degenerate from Leader into Follower!!!\", rf.me)\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\trf.nonleaderCh <- true\n\t\t\t\t\t\t\t\t// don't try to send AppendEntries RPC to others then, rf is not the leader.\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// NOTE: the nextIndex[i] should never < 1\n\t\t\t\t\t\t\t\tconflict_term := reply.ConflictTerm\n\t\t\t\t\t\t\t\tconflict_index := reply.ConflictIndex\n\t\t\t\t\t\t\t\t// refer to TA's guide blog.\n\t\t\t\t\t\t\t\t// first, try to find the first index of conflict_term in leader's log.\n\t\t\t\t\t\t\t\tfound := false\n\t\t\t\t\t\t\t\tnew_next_index := conflict_index // at least 1\n\t\t\t\t\t\t\t\tfor j := 0; j < len(rf.log); j++ {\n\t\t\t\t\t\t\t\t\tif rf.log[j].Term == conflict_term {\n\t\t\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\t\t} else if rf.log[j].Term > conflict_term {\n\t\t\t\t\t\t\t\t\t\tif found {\n\t\t\t\t\t\t\t\t\t\t\tnew_next_index = j + 1\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnextIndex_copy[i] = new_next_index\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\t// now retry to send AppendEntries RPC to peer-i.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// RPC fails. Retry!\n\t\t\t\t\t\t// when network partition\n\t\t\t\t\t\ttime.Sleep(time.Millisecond * time.Duration(100))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(peer_index)\n\t\t}\n\t} else {\n\t\trf.mu.Unlock()\n\t}\n\n\treturn index, term, isLeader\n}", "func (cfg *config) checkOneLeader() int {\n\tfor iters := 0; iters < 10; iters++ {\n\t\tms := 450 + (rand.Int63() % 100)\n\t\ttime.Sleep(time.Duration(ms) * time.Millisecond)\n\n\t\tleaders := make(map[int][]int)\n\t\tfor i := 0; i < cfg.n; i++ {\n\t\t\tif cfg.connected[i] {\n\t\t\t\tif term, leader := cfg.rafts[i].GetState(); leader {\n\t\t\t\t\tleaders[term] = append(leaders[term], i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlastTermWithLeader := -1\n\t\tfor term, leaders := range leaders {\n\t\t\tif len(leaders) > 1 {\n\t\t\t\tcfg.t.Fatalf(\"term %d has %d (>1) leaders\", term, len(leaders))\n\t\t\t}\n\t\t\tif term > lastTermWithLeader {\n\t\t\t\tlastTermWithLeader = term\n\t\t\t}\n\t\t}\n\n\t\tif len(leaders) != 0 {\n\t\t\treturn leaders[lastTermWithLeader][0]\n\t\t}\n\t}\n\tcfg.t.Fatalf(\"expected one leader, got none\")\n\treturn -1\n}", "func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tnt.isolate(3)\n\n\tlead := nt.peers[1].(*raft)\n\n\tnt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})\n\tif lead.leadTransferee != 3 {\n\t\tt.Fatalf(\"wait transferring, leadTransferee = %v, want %v\", lead.leadTransferee, 3)\n\t}\n\n\tfor i := 0; i < lead.heartbeatTimeout; i++ {\n\t\tlead.tick()\n\t}\n\t// Second transfer leadership request to the same node.\n\tnt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})\n\n\tfor i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {\n\t\tlead.tick()\n\t}\n\n\tcheckLeaderTransferState(t, lead, StateLeader, 1)\n}", "func TestClusteringFollowerDeleteChannelNotInSnapshot(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\tmaxInactivity := 250 * time.Millisecond\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1sOpts.Clustering.TrailingLogs = 0\n\ts1sOpts.MaxInactivity = maxInactivity\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2sOpts.Clustering.TrailingLogs = 0\n\ts2sOpts.MaxInactivity = maxInactivity\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3sOpts.Clustering.TrailingLogs = 0\n\ts3sOpts.MaxInactivity = maxInactivity\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\tfor _, s := range servers {\n\t\tcheckState(t, s, Clustered)\n\t}\n\n\t// Wait for leader to be elected.\n\tleader := getLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Send a message, which will create the channel\n\tchannel := \"foo\"\n\texpectedMsg := make(map[uint64]msg)\n\texpectedMsg[1] = msg{sequence: 1, data: []byte(\"first\")}\n\tif err := sc.Publish(channel, expectedMsg[1].data); err != nil {\n\t\tt.Fatalf(\"Error on publish: %v\", err)\n\t}\n\tsc.Close()\n\t// Wait for channel to be replicated in all servers\n\tverifyChannelConsistency(t, channel, 5*time.Second, 1, 1, expectedMsg, servers...)\n\n\t// Kill a follower.\n\tvar follower *StanServer\n\tfor _, s := range servers {\n\t\tif leader != s {\n\t\t\tfollower = s\n\t\t\tbreak\n\t\t}\n\t}\n\tservers = removeServer(servers, follower)\n\tfollower.Shutdown()\n\n\t// Wait for more than the MaxInactivity\n\ttime.Sleep(2 * maxInactivity)\n\t// Check channel is no longer in leader\n\tverifyChannelExist(t, leader, channel, false, 5*time.Second)\n\t// Perform a snapshot after the channel has been deleted\n\tif err := leader.raft.Snapshot().Error(); err != nil {\n\t\tt.Fatalf(\"Error on snapshot: %v\", err)\n\t}\n\n\t// Restart the follower\n\tfollower = runServerWithOpts(t, follower.opts, nil)\n\tdefer follower.Shutdown()\n\tservers = append(servers, follower)\n\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// The follower will have recovered foo (from streaming store), but then from\n\t// the snapshot should realize that the channel no longer exits and should delete it.\n\tverifyChannelExist(t, follower, channel, false, 5*time.Second)\n}", "func TestActiveReplicatorRecoverFromLocalFlush(t *testing.T) {\n\n\tbase.RequireNumTestBuckets(t, 3)\n\n\tbase.SetUpTestLogging(t, logger.LevelInfo, logger.KeyReplicate, logger.KeyHTTP, logger.KeyHTTPResp, logger.KeySync, logger.KeySyncMsg)\n\n\t// Passive\n\trt2 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: base.GetTestBucket(t),\n\t\tDatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{\n\t\t\tUsers: map[string]*db.PrincipalConfig{\n\t\t\t\t\"alice\": {\n\t\t\t\t\tPassword: base.StringPtr(\"pass\"),\n\t\t\t\t\tExplicitChannels: utils.SetOf(\"alice\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t})\n\tdefer rt2.Close()\n\n\t// Create doc on rt2\n\tdocID := t.Name() + \"rt2doc\"\n\tresp := rt2.SendAdminRequest(http.MethodPut, \"/db/\"+docID, `{\"source\":\"rt2\",\"channels\":[\"alice\"]}`)\n\tassertStatus(t, resp, http.StatusCreated)\n\n\tassert.NoError(t, rt2.WaitForPendingChanges())\n\n\t// Make rt2 listen on an actual HTTP port, so it can receive the blipsync request from rt1\n\tsrv := httptest.NewServer(rt2.TestPublicHandler())\n\tdefer srv.Close()\n\n\t// Build passiveDBURL with basic auth creds\n\tpassiveDBURL, err := url.Parse(srv.URL + \"/db\")\n\trequire.NoError(t, err)\n\tpassiveDBURL.User = url.UserPassword(\"alice\", \"pass\")\n\n\t// Active\n\trt1 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: base.GetTestBucket(t),\n\t})\n\n\tarConfig := db.ActiveReplicatorConfig{\n\t\tID: t.Name(),\n\t\tDirection: db.ActiveReplicatorTypePull,\n\t\tRemoteDBURL: passiveDBURL,\n\t\tActiveDB: &db.Database{\n\t\t\tDatabaseContext: rt1.GetDatabase(),\n\t\t},\n\t\tContinuous: true,\n\t\tReplicationStatsMap: base.SyncGatewayStats.NewDBStats(t.Name(), false, false, false).DBReplicatorStats(t.Name()),\n\t}\n\n\t// Create the first active replicator to pull from seq:0\n\tar := db.NewActiveReplicator(&arConfig)\n\trequire.NoError(t, err)\n\n\tstartNumChangesRequestedFromZeroTotal := rt2.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tstartNumRevsSentTotal := rt2.GetDatabase().DbStats.CBLReplicationPull().RevSendCount.Value()\n\n\tassert.NoError(t, ar.Start())\n\n\t// wait for document originally written to rt2 to arrive at rt1\n\tchangesResults, err := rt1.WaitForChanges(1, \"/db/_changes?since=0\", \"\", true)\n\trequire.NoError(t, err)\n\trequire.Len(t, changesResults.Results, 1)\n\tassert.Equal(t, docID, changesResults.Results[0].ID)\n\n\tdoc, err := rt1.GetDatabase().GetDocument(logger.TestCtx(t), docID, db.DocUnmarshalAll)\n\tassert.NoError(t, err)\n\n\tbody, err := doc.GetDeepMutableBody()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"rt2\", body[\"source\"])\n\n\t// one _changes from seq:0 with initial number of docs sent\n\tnumChangesRequestedFromZeroTotal := rt2.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tassert.Equal(t, startNumChangesRequestedFromZeroTotal+1, numChangesRequestedFromZeroTotal)\n\n\t// rev assertions\n\tnumRevsSentTotal := rt2.GetDatabase().DbStats.CBLReplicationPull().RevSendCount.Value()\n\tassert.Equal(t, startNumRevsSentTotal+1, numRevsSentTotal)\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().ProcessedSequenceCount)\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().ExpectedSequenceCount)\n\n\t// checkpoint assertions\n\tassert.Equal(t, int64(0), ar.Pull.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().GetCheckpointMissCount)\n\t// Since we bumped the checkpointer interval, we're only setting checkpoints on replicator close.\n\tassert.Equal(t, int64(0), ar.Pull.Checkpointer.Stats().SetCheckpointCount)\n\tar.Pull.Checkpointer.CheckpointNow()\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().SetCheckpointCount)\n\n\tassert.NoError(t, ar.Stop())\n\n\t// close rt1, and release the underlying bucket back to the pool.\n\trt1.Close()\n\n\t// recreate rt1 with a new bucket\n\trt1 = NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: base.GetTestBucket(t),\n\t})\n\tdefer rt1.Close()\n\n\t// Create a new replicator using the same config, which should use the checkpoint set from the first.\n\t// Have to re-set ActiveDB because we recreated it with the new rt1.\n\tarConfig.ActiveDB = &db.Database{\n\t\tDatabaseContext: rt1.GetDatabase(),\n\t}\n\tar = db.NewActiveReplicator(&arConfig)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, ar.Start())\n\n\t// we pulled the remote checkpoint, but the local checkpoint wasn't there to match it.\n\tassert.Equal(t, int64(0), ar.Pull.Checkpointer.Stats().GetCheckpointHitCount)\n\n\t// wait for document originally written to rt2 to arrive at rt1\n\tchangesResults, err = rt1.WaitForChanges(1, \"/db/_changes?since=0\", \"\", true)\n\trequire.NoError(t, err)\n\trequire.Len(t, changesResults.Results, 1)\n\tassert.Equal(t, docID, changesResults.Results[0].ID)\n\n\tdoc, err = rt1.GetDatabase().GetDocument(logger.TestCtx(t), docID, db.DocUnmarshalAll)\n\trequire.NoError(t, err)\n\n\tbody, err = doc.GetDeepMutableBody()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"rt2\", body[\"source\"])\n\n\t// one _changes from seq:0 with initial number of docs sent\n\tendNumChangesRequestedFromZeroTotal := rt2.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tassert.Equal(t, numChangesRequestedFromZeroTotal+1, endNumChangesRequestedFromZeroTotal)\n\n\t// make sure rt2 thinks it has sent all of the revs via a 2.x replicator\n\tnumRevsSentTotal = rt2.GetDatabase().DbStats.CBLReplicationPull().RevSendCount.Value()\n\tassert.Equal(t, startNumRevsSentTotal+2, numRevsSentTotal)\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().ProcessedSequenceCount)\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().ExpectedSequenceCount)\n\n\t// assert the second active replicator stats\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(0), ar.Pull.Checkpointer.Stats().SetCheckpointCount)\n\tar.Pull.Checkpointer.CheckpointNow()\n\tassert.Equal(t, int64(1), ar.Pull.Checkpointer.Stats().SetCheckpointCount)\n\n\tassert.NoError(t, ar.Stop())\n}", "func TestRaftAddOneNode(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tclusterPrefix := \"TestRaftAddOneNode\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tn1 := testCreateRaftNode(getTestConfig(ID1, clusterPrefix+ID1), newStorage())\n\n\t// Create n2 node.\n\tfsm2 := newTestFSM(ID2)\n\tn2 := testCreateRaftNode(getTestConfig(ID2, clusterPrefix+ID2), newStorage())\n\tconnectAllNodes(n1, n2)\n\n\t// The cluster starts with only one node -- n1.\n\tn1.Start(fsm1)\n\tn1.ProposeInitialMembership([]string{ID1})\n\n\t// Wait it to be elected as leader.\n\t<-fsm1.leaderCh\n\n\t// Propose two commands to the cluster. Now the cluster only contains node n1.\n\tn1.Propose([]byte(\"data1\"))\n\tpending := n1.Propose([]byte(\"data2\"))\n\t<-pending.Done\n\n\t// Add node n2 to the cluster.\n\tpending = n1.AddNode(ID2)\n\n\t// The reconfiguration will be blocked until n2 starts. Because the\n\t// new configuration needs to be committed in new quorum\n\tselect {\n\tcase <-pending.Done:\n\t\t// The node might step down, in that case 'ErrNotLeaderAnymore' will be\n\t\t// returned.\n\t\tif pending.Err == nil {\n\t\t\tt.Fatalf(\"the proposed command should fail as the cluster doesn't have a quorum\")\n\t\t}\n\tcase <-time.After(10 * time.Millisecond):\n\t}\n\n\t// Start n2 as a joiner.\n\tn2.Start(fsm2)\n\n\t// Two FSMs should apply all 2 commands, eventually.\n\tif !testEntriesEqual(fsm1.appliedCh, fsm2.appliedCh, 2) {\n\t\tt.Fatal(\"two FSMs in same group applied different sequence of commands.\")\n\t}\n}", "func (le *LeaderElector) becomeLeader() {\n\thighestTS := -1\n\tlock := new(sync.Mutex)\n\tacceptanceCount := 1 //To accomodate for the failing leader\n\t//Notify Other Servers,and also poll for the highest TS seen\n\tfor SID, serv := range le.ThisServer.GroupInfoPtr.GroupMembers {\n\t\tts := -1\n\t\tif SID > le.ThisServer.SID {\n\t\t\tif ok := call(serv, \"LeaderElector.NotifyLeaderChange\", &le.ThisServer.SID, &ts); !ok || ts == -1 {\n\t\t\t\tdebug_err(\"Error : LeaderElector : %s %s\", \"LeaderElector.NotifyLeaderChange Failed For Server :\", serv)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlock.Lock()\n\t\t\tif ts > highestTS {\n\t\t\t\thighestTS = ts\n\t\t\t}\n\t\t\tacceptanceCount++\n\t\t\tlock.Unlock()\n\t\t}\n\t}\n\tif le.makeTSAdjustments(highestTS, acceptanceCount) {\n\t\tdebug(\"[*] Info : LeaderElector : This server is The Leader.\")\n\t\treturn\n\t}\n\tle.Lock()\n\tle.CurrentLeader = \"\"\n\tle.LeaderSID = NO_LEADER\n\tle.Unlock()\n\tdebug(\"[*] Info : LeaderElector : Did not become the leader. Majority Connected To previous leader or Have Failed. \")\n}", "func (r *Raft) runLeader() {\n\tstate := leaderState{\n\t\tcommitCh: make(chan *DeferLog, 128),\n\t\treplicationState: make(map[string]*followerReplication),\n\t}\n\tdefer state.Release()\n\n\t// Initialize inflight tracker\n\tstate.inflight = NewInflight(state.commitCh)\n\n\tr.peerLock.Lock()\n\t// Start a replication routine for each peer\n\tfor _, peer := range r.peers {\n\t\tr.startReplication(&state, peer)\n\t}\n\tr.peerLock.Unlock()\n\n\t// seal leadership\n\tgo r.leaderNoop()\n\n\ttransition := false\n\tfor !transition {\n\t\tselect {\n\t\tcase applyLog := <-r.applyCh:\n\t\t\t// Prepare log\n\t\t\tapplyLog.log.Index = r.getLastLogIndex() + 1\n\t\t\tapplyLog.log.Term = r.getCurrentTerm()\n\t\t\t// Write the log entry locally\n\t\t\tif err := r.logs.StoreLog(&applyLog.log); err != nil {\n\t\t\t\tr.logE.Printf(\"Failed to commit log: %w\", err)\n\t\t\t\tapplyLog.response = err\n\t\t\t\tapplyLog.Response()\n\t\t\t\tr.setState(Follower)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Add this to the inflight logs\n\t\t\tstate.inflight.Start(applyLog, r.quorumSize())\n\t\t\tstate.inflight.Commit(applyLog.log.Index)\n\t\t\t// Update the last log since it's on disk now\n\t\t\tr.setLastLogIndex(applyLog.log.Index)\n\n\t\t\t// Notify the replicators of the new log\n\t\t\tfor _, f := range state.replicationState {\n\t\t\t\tasyncNotifyCh(f.triggerCh)\n\t\t\t}\n\n\t\tcase commitLog := <-state.commitCh:\n\t\t\t// Increment the commit index\n\t\t\tidx := commitLog.log.Index\n\t\t\tr.setCommitIndex(idx)\n\n\t\t\t// Perform leader-specific processing\n\t\t\ttransition = r.leaderProcessLog(&state, &commitLog.log)\n\n\t\t\t// Trigger applying logs locally\n\t\t\tr.commitCh <- commitTuple{idx, commitLog}\n\n\t\tcase rpc := <-r.rpcCh:\n\t\t\tswitch cmd := rpc.Command.(type) {\n\t\t\tcase *AppendEntriesRequest:\n\t\t\t\ttransition = r.appendEntries(rpc, cmd)\n\t\t\tcase *RequestVoteRequest:\n\t\t\t\ttransition = r.requestVote(rpc, cmd)\n\t\t\tdefault:\n\t\t\t\tr.logE.Printf(\"Leader state, got unexpected command: %#v\",\n\t\t\t\t\trpc.Command)\n\t\t\t\trpc.Respond(nil, fmt.Errorf(\"unexpected command\"))\n\t\t\t}\n\t\tcase <-r.shutdownCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s) TestResourceResolverChangePriority(t *testing.T) {\n\tfakeClient := fakeclient.NewClient()\n\trr := newResourceResolver(&clusterResolverBalancer{xdsClient: fakeClient})\n\trr.updateMechanisms([]DiscoveryMechanism{\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[0],\n\t\t},\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[1],\n\t\t},\n\t})\n\tctx, ctxCancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer ctxCancel()\n\tgotEDSName1, err := fakeClient.WaitForWatchEDS(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotEDSName1 != testClusterNames[0] {\n\t\tt.Fatalf(\"xdsClient.WatchEDS called for cluster: %v, want: %v\", gotEDSName1, testClusterNames[0])\n\t}\n\tgotEDSName2, err := fakeClient.WaitForWatchEDS(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotEDSName2 != testClusterNames[1] {\n\t\tt.Fatalf(\"xdsClient.WatchEDS called for cluster: %v, want: %v\", gotEDSName2, testClusterNames[1])\n\t}\n\n\t// Invoke callback, should get an update.\n\tfakeClient.InvokeWatchEDSCallback(gotEDSName1, testEDSUpdates[0], nil)\n\t// Shouldn't send update, because only one resource received an update.\n\tshortCtx, shortCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shortCancel()\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tt.Fatalf(\"get unexpected update %+v\", u)\n\tcase <-shortCtx.Done():\n\t}\n\tfakeClient.InvokeWatchEDSCallback(gotEDSName2, testEDSUpdates[1], nil)\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tif diff := cmp.Diff(u.priorities, []priorityConfig{\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[0],\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[0],\n\t\t\t\tchildNameGen: newNameGenerator(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[1],\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[1],\n\t\t\t\tchildNameGen: newNameGenerator(1),\n\t\t\t},\n\t\t}, cmp.AllowUnexported(priorityConfig{}, nameGenerator{})); diff != \"\" {\n\t\t\tt.Fatalf(\"got unexpected resource update, diff (-got, +want): %v\", diff)\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t}\n\n\t// Send the same resources with different priorities, shouldn't trigger\n\t// watch, but should trigger an update with the new priorities.\n\trr.updateMechanisms([]DiscoveryMechanism{\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[1],\n\t\t},\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[0],\n\t\t},\n\t})\n\tshortCtx, shortCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shortCancel()\n\tif n, err := fakeClient.WaitForWatchEDS(shortCtx); err == nil {\n\t\tt.Fatalf(\"unexpected watch started for EDS: %v\", n)\n\t}\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tif diff := cmp.Diff(u.priorities, []priorityConfig{\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[1],\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[1],\n\t\t\t\tchildNameGen: newNameGenerator(1),\n\t\t\t},\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[0],\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[0],\n\t\t\t\tchildNameGen: newNameGenerator(0),\n\t\t\t},\n\t\t}, cmp.AllowUnexported(priorityConfig{}, nameGenerator{})); diff != \"\" {\n\t\t\tt.Fatalf(\"got unexpected resource update, diff (-got, +want): %v\", diff)\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t}\n\n\t// Close the resource resolver. Should stop EDS watch.\n\trr.stop()\n\tedsNameCanceled1, err := fakeClient.WaitForCancelEDSWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\tif edsNameCanceled1 != gotEDSName1 && edsNameCanceled1 != gotEDSName2 {\n\t\tt.Fatalf(\"xdsClient.CancelEDS called for %v, want: %v or %v\", edsNameCanceled1, gotEDSName1, gotEDSName2)\n\t}\n\tedsNameCanceled2, err := fakeClient.WaitForCancelEDSWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\tif edsNameCanceled2 != gotEDSName2 && edsNameCanceled2 != gotEDSName1 {\n\t\tt.Fatalf(\"xdsClient.CancelEDS called for %v, want: %v or %v\", edsNameCanceled2, gotEDSName1, gotEDSName2)\n\t}\n}", "func StrictDNSLRCluster(name, svcAddress string, port uint32, timeoutms int, circuitBreaker *cluster.CircuitBreakers, outlierDetection *cluster.OutlierDetection) *v2.Cluster {\n\tendpointAddress := TCPAddress(svcAddress, port)\n\treturn &v2.Cluster{\n\t\tName: name,\n\t\tConnectTimeout: time.Duration(timeoutms) * time.Millisecond,\n\t\tClusterDiscoveryType: &v2.Cluster_Type{Type: v2.Cluster_STRICT_DNS},\n\t\tDnsLookupFamily: v2.Cluster_V4_ONLY,\n\t\tLbPolicy: v2.Cluster_LEAST_REQUEST,\n\t\tLoadAssignment: &v2.ClusterLoadAssignment{\n\t\t\tClusterName: name,\n\t\t\tEndpoints: []endpoint.LocalityLbEndpoints{{\n\t\t\t\tLbEndpoints: []endpoint.LbEndpoint{{\n\t\t\t\t\tHostIdentifier: &endpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\tEndpoint: &endpoint.Endpoint{\n\t\t\t\t\t\t\tAddress: &endpointAddress,\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\tCircuitBreakers: circuitBreaker,\n\t\tOutlierDetection: outlierDetection,\n\t}\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\t// create a channel in Raft\n\trf.applyCh = applyCh\n\trf.state = Follower\n\trf.nonleaderCh = make(chan bool, 20)\n\trf.leaderCh = make(chan bool, 20)\n\trf.canApplyCh = make(chan bool, 20)\n\t// set election timeout\n\trf.voteCount = 0\n\trf.resetElectionTimeout()\n\n\t// Initialize volatile state on all servers.\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\trf.log = make([]LogEntry, 0)\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\t// seperate goroutine to apply command to statemachine.\n\tgo func() {\n\t\tfor {\n\t\t\t<-rf.canApplyCh\n\t\t\t// apply\n\t\t\trf.mu.Lock()\n\t\t\tcommitIndex_copy := rf.commitIndex\n\t\t\tlastApplied_copy := rf.lastApplied\n\t\t\tlog_copy := make([]LogEntry, len(rf.log))\n\t\t\tcopy(log_copy, rf.log)\n\t\t\trf.mu.Unlock()\n\t\t\tfor curr_index := lastApplied_copy + 1; curr_index <= commitIndex_copy; curr_index++ {\n\t\t\t\tDPrintf(\"peer-%d apply command-%d at index-%d.\", rf.me, log_copy[curr_index-1].Command.(int), curr_index)\n\t\t\t\tvar curr_command ApplyMsg\n\t\t\t\tcurr_command.CommandValid = true\n\t\t\t\tcurr_command.Command = log_copy[curr_index-1].Command\n\t\t\t\tcurr_command.CommandIndex = curr_index\n\t\t\t\trf.applyCh <- curr_command\n\t\t\t\trf.lastApplied = curr_index\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Leader's heartbeat long-running goroutine.\n\tgo func() {\n\t\tfor {\n\t\t\tif rf.state == Leader {\n\t\t\t\t// send heartbeats\n\t\t\t\trf.broadcastHeartbeats()\n\t\t\t\ttime.Sleep(time.Millisecond * time.Duration(100)) // 100ms per heartbeat. (heartbeat time interval << election timeout)\n\t\t\t} else {\n\t\t\t\t// block until be elected as the new leader.\n\t\t\t\tDPrintf(\"peer-%d leader's heartbeat long-running goroutine. block.\", rf.me)\n\t\t\t\t<-rf.leaderCh\n\t\t\t\tDPrintf(\"peer-%d leader's heartbeat long-running goroutine. get up.\", rf.me)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Nonleader's election timeout long-running goroutine.\n\tgo func() {\n\t\tfor {\n\t\t\t// check rf.state == Follower\n\t\t\tif rf.state != Leader {\n\t\t\t\t// begin tic-toc\n\t\t\t\ttime.Sleep(time.Millisecond * time.Duration(10))\n\t\t\t\tif rf.electionTimeout() {\n\t\t\t\t\tDPrintf(\"peer-%d kicks off an election!\\n\", rf.me)\n\t\t\t\t\t// election timeout! kick off an election.\n\t\t\t\t\t// convertion to a Candidate.\n\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\tDPrintf(\"peer-%d becomes a Candidate!!!\\n\", rf.me)\n\t\t\t\t\trf.state = Candidate\n\t\t\t\t\trf.currentTerm += 1\n\t\t\t\t\trf.persist()\n\t\t\t\t\tterm_copy := rf.currentTerm // create a copy of the term and it'll be used in RequestVote RPC.\n\t\t\t\t\t// vote for itself.\n\t\t\t\t\trf.voteCount = 1\n\t\t\t\t\trf.resetElectionTimeout()\n\t\t\t\t\t// send RequestVote RPCs to all other peers in seperate goroutines.\n\t\t\t\t\tlast_log_index_copy := len(rf.log)\n\t\t\t\t\tlast_log_term_copy := -1\n\t\t\t\t\tif last_log_index_copy > 0 {\n\t\t\t\t\t\tlast_log_term_copy = rf.log[last_log_index_copy-1].Term\n\t\t\t\t\t}\n\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\tfor peer_index, _ := range rf.peers {\n\t\t\t\t\t\tif peer_index == rf.me {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// create goroutine.\n\t\t\t\t\t\tgo func(i int) {\n\t\t\t\t\t\t\t// use a copy of the state of the rf peer\n\t\t\t\t\t\t\tvar args RequestVoteArgs\n\t\t\t\t\t\t\targs.Term = term_copy\n\t\t\t\t\t\t\targs.CandidateId = rf.me\n\t\t\t\t\t\t\targs.LastLogIndex = last_log_index_copy\n\t\t\t\t\t\t\targs.LastLogTerm = last_log_term_copy\n\t\t\t\t\t\t\tvar reply RequestVoteReply\n\t\t\t\t\t\t\tDPrintf(\"peer-%d send a sendRequestVote RPC to peer-%d\", rf.me, i)\n\t\t\t\t\t\t\t// reduce RPCs....\n\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\tif rf.state != Candidate || rf.currentTerm != term_copy {\n\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\tok := rf.sendRequestVote(i, &args, &reply)\n\t\t\t\t\t\t\t// handle the RPC reply in the same goroutine.\n\t\t\t\t\t\t\tif ok == true {\n\t\t\t\t\t\t\t\tif reply.VoteGranted == true {\n\t\t\t\t\t\t\t\t\t// whether the peer is still a Candidate and the previous term? if yes, increase rf.voteCount; if no, ignore.\n\t\t\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\t\t\t// re-establish the assumption.\n\t\t\t\t\t\t\t\t\tif rf.state == Candidate && term_copy == rf.currentTerm {\n\t\t\t\t\t\t\t\t\t\trf.voteCount += 1\n\t\t\t\t\t\t\t\t\t\tDPrintf(\"peer-%d gets a vote!\", rf.me)\n\t\t\t\t\t\t\t\t\t\tif rf.voteCount > len(rf.peers)/2 {\n\t\t\t\t\t\t\t\t\t\t\trf.convertToLeader()\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trf.mu.Lock()\n\t\t\t\t\t\t\t\t\t// re-establish the assumption.\n\t\t\t\t\t\t\t\t\tif rf.state == Candidate && term_copy == rf.currentTerm {\n\t\t\t\t\t\t\t\t\t\tif reply.Term > rf.currentTerm {\n\t\t\t\t\t\t\t\t\t\t\trf.state = Follower\n\t\t\t\t\t\t\t\t\t\t\trf.currentTerm = reply.Term\n\t\t\t\t\t\t\t\t\t\t\trf.persist()\n\t\t\t\t\t\t\t\t\t\t\trf.voteCount = 0\n\t\t\t\t\t\t\t\t\t\t\tDPrintf(\"peer-%d calm down from a Candidate to a Follower!!!\", rf.me)\n\t\t\t\t\t\t\t\t\t\t\trf.resetElectionTimeout()\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\trf.mu.Unlock()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}(peer_index)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// block until become a Follower or Candidate.\n\t\t\t\tDPrintf(\"peer-%d non-leader's election timeout long-running goroutine. block.\", rf.me)\n\t\t\t\t<-rf.nonleaderCh\n\t\t\t\tDPrintf(\"peer-%d non-leader's election timeout long-running goroutine. get up.\", rf.me)\n\t\t\t\trf.resetElectionTimeout()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func TestPreVoteWithSplitVote(t *testing.T) {\n\tn1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(n1)\n\tdefer closeAndFreeRaft(n2)\n\tdefer closeAndFreeRaft(n3)\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\tn3.becomeFollower(1, None)\n\n\tn1.preVote = true\n\tn2.preVote = true\n\tn3.preVote = true\n\n\tnt := newNetwork(n1, n2, n3)\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\t// simulate leader down. followers start split vote.\n\tnt.isolate(1)\n\tnt.send([]pb.Message{\n\t\t{From: 2, To: 2, Type: pb.MsgHup},\n\t\t{From: 3, To: 3, Type: pb.MsgHup},\n\t}...)\n\n\t// check whether the term values are expected\n\t// n2.Term == 3\n\t// n3.Term == 3\n\tsm := nt.peers[2].(*raft)\n\tif sm.Term != 3 {\n\t\tt.Errorf(\"peer 2 term: %d, want %d\", sm.Term, 3)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.Term != 3 {\n\t\tt.Errorf(\"peer 3 term: %d, want %d\", sm.Term, 3)\n\t}\n\n\t// check state\n\t// n2 == candidate\n\t// n3 == candidate\n\tsm = nt.peers[2].(*raft)\n\tif sm.state != StateCandidate {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", sm.state, StateCandidate)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.state != StateCandidate {\n\t\tt.Errorf(\"peer 3 state: %s, want %s\", sm.state, StateCandidate)\n\t}\n\n\t// node 2 election timeout first\n\tnt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})\n\n\t// check whether the term values are expected\n\t// n2.Term == 4\n\t// n3.Term == 4\n\tsm = nt.peers[2].(*raft)\n\tif sm.Term != 4 {\n\t\tt.Errorf(\"peer 2 term: %d, want %d\", sm.Term, 4)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.Term != 4 {\n\t\tt.Errorf(\"peer 3 term: %d, want %d\", sm.Term, 4)\n\t}\n\n\t// check state\n\t// n2 == leader\n\t// n3 == follower\n\tsm = nt.peers[2].(*raft)\n\tif sm.state != StateLeader {\n\t\tt.Errorf(\"peer 2 state: %s, want %s\", sm.state, StateLeader)\n\t}\n\tsm = nt.peers[3].(*raft)\n\tif sm.state != StateFollower {\n\t\tt.Errorf(\"peer 3 state: %s, want %s\", sm.state, StateFollower)\n\t}\n}", "func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tlead := nt.peers[1].(*raft)\n\n\tif lead.lead != 1 {\n\t\tt.Fatalf(\"after election leader is %x, want 1\", lead.lead)\n\t}\n\n\t// Transfer leadership to 2.\n\tnt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateFollower, 2)\n\n\t// After some log replication, transfer leadership back to 1.\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateLeader, 1)\n}", "func (cfg *config) checkNoLeader() {\n\tfor i := 0; i < cfg.n; i++ {\n\t\tif cfg.connected[i] {\n\t\t\t_, is_leader := cfg.rafts[i].GetState()\n\t\t\tif is_leader {\n\t\t\t\tcfg.t.Fatalf(\"expected no leader, but %v claims to be leader\", i)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *leaseController) sync(ctx context.Context, syncCtx factory.SyncContext) error {\n\tclusters, err := c.clusterLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil\n\t}\n\tfor _, cluster := range clusters {\n\t\t// cluster is not accepted, skip it.\n\t\tif !meta.IsStatusConditionTrue(cluster.Status.Conditions, clusterv1.ManagedClusterConditionHubAccepted) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// get the lease of a cluster, if the lease is not found, create it\n\t\tleaseName := \"managed-cluster-lease\"\n\t\tobservedLease, err := c.leaseLister.Leases(cluster.Name).Get(leaseName)\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\tlease := &coordv1.Lease{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: leaseName,\n\t\t\t\t\tNamespace: cluster.Name,\n\t\t\t\t\tLabels: map[string]string{\"open-cluster-management.io/cluster-name\": cluster.Name},\n\t\t\t\t},\n\t\t\t\tSpec: coordv1.LeaseSpec{\n\t\t\t\t\tHolderIdentity: pointer.StringPtr(leaseName),\n\t\t\t\t\tRenewTime: &metav1.MicroTime{Time: time.Now()},\n\t\t\t\t},\n\t\t\t}\n\t\t\tif _, err := c.kubeClient.CoordinationV1().Leases(cluster.Name).Create(ctx, lease, metav1.CreateOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\tcase err != nil:\n\t\t\treturn err\n\t\t}\n\n\t\tleaseDurationSeconds := cluster.Spec.LeaseDurationSeconds\n\t\t// for backward compatible, release-2.1 has mutating admission webhook to mutate this field,\n\t\t// but release-2.0 does not have the mutating admission webhook\n\t\tif leaseDurationSeconds == 0 {\n\t\t\tleaseDurationSeconds = 60\n\t\t}\n\n\t\tgracePeriod := time.Duration(leaseDurationTimes*leaseDurationSeconds) * time.Second\n\t\t// the lease is constantly updated, do nothing\n\t\tnow := time.Now()\n\t\tif now.Before(observedLease.Spec.RenewTime.Add(gracePeriod)) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// for backward compatible, before release-2.3, the format of lease name is cluster-lease-<managed-cluster-name>\n\t\t// TODO: after release-2.3, we will eliminate these\n\t\toldVersionLeaseName := fmt.Sprintf(\"cluster-lease-%s\", cluster.Name)\n\t\toldVersionLease, err := c.leaseLister.Leases(cluster.Name).Get(oldVersionLeaseName)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tif time.Now().Before(oldVersionLease.Spec.RenewTime.Add(gracePeriod)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase errors.IsNotFound(err):\n\t\t\t// the old version does not exist, create a new one\n\t\t\toldVersionLease := &coordv1.Lease{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: oldVersionLeaseName,\n\t\t\t\t\tNamespace: cluster.Name,\n\t\t\t\t\tLabels: map[string]string{\"open-cluster-management.io/cluster-name\": cluster.Name},\n\t\t\t\t},\n\t\t\t\tSpec: coordv1.LeaseSpec{\n\t\t\t\t\tHolderIdentity: pointer.StringPtr(oldVersionLeaseName),\n\t\t\t\t\tRenewTime: &metav1.MicroTime{Time: time.Now()},\n\t\t\t\t},\n\t\t\t}\n\t\t\tif _, err := c.kubeClient.CoordinationV1().Leases(cluster.Name).Create(ctx, oldVersionLease, metav1.CreateOptions{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\tcase err != nil:\n\t\t\treturn err\n\t\t}\n\n\t\t// the lease is not constantly updated, update it to unknown\n\t\tconditionUpdateFn := helpers.UpdateManagedClusterConditionFn(metav1.Condition{\n\t\t\tType: clusterv1.ManagedClusterConditionAvailable,\n\t\t\tStatus: metav1.ConditionUnknown,\n\t\t\tReason: \"ManagedClusterLeaseUpdateStopped\",\n\t\t\tMessage: fmt.Sprintf(\"Registration agent stopped updating its lease.\"),\n\t\t})\n\t\t_, updated, err := helpers.UpdateManagedClusterStatus(ctx, c.clusterClient, cluster.Name, conditionUpdateFn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif updated {\n\t\t\tsyncCtx.Recorder().Eventf(\"ManagedClusterAvailableConditionUpdated\",\n\t\t\t\t\"update managed cluster %q available condition to unknown, due to its lease is not updated constantly\",\n\t\t\t\tcluster.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (rf *Raft) convertToLeader() {\n rf.mu.Lock()\n DLCPrintf(\"Server (%d)[state=%s, term=%d, votedFor=%d] convert to Leader\", rf.me, rf.state, rf.currentTerm, rf.votedFor)\n rf.electionTimer.Stop() \n rf.state = \"Leader\"\n for i:=0; i<len(rf.peers); i++ {\n rf.nextIndex[i] = rf.convertToGlobalViewIndex(len(rf.log))\n rf.matchIndex[i] = rf.convertToGlobalViewIndex(0)\n }\n rf.mu.Unlock()\n // 启动一个线程,定时给各个Follower发送HeartBeat Request \n time.Sleep(50 * time.Millisecond)\n go rf.sendAppendEntriesToMultipleFollowers()\n}", "func (c *Cluster) run() {\n\n\tticker := time.NewTicker(c.fo.heartBeat)\n\n\tmissed := 0\n\t// Don't rehash immediately on the first ping. If this node just came onlyne, leader will\n\t// account it on the next ping. Otherwise it will be rehashing twice.\n\trehashSkipped := false\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif c.fo.leader == c.thisNodeName {\n\t\t\t\t// I'm the leader, send pings\n\t\t\t\tc.sendPings()\n\t\t\t} else {\n\t\t\t\tmissed++\n\t\t\t\tif missed >= c.fo.voteTimeout {\n\t\t\t\t\t// Elect the leader\n\t\t\t\t\tmissed = 0\n\t\t\t\t\tc.electLeader()\n\t\t\t\t}\n\t\t\t}\n\t\tcase ping := <-c.fo.leaderPing:\n\t\t\t// Ping from a leader.\n\n\t\t\tif ping.Term < c.fo.term {\n\t\t\t\t// This is a ping from a stale leader. Ignore.\n\t\t\t\tlog.Println(\"cluster: ping from a stale leader\", ping.Term, c.fo.term, ping.Leader, c.fo.leader)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ping.Term > c.fo.term {\n\t\t\t\tc.fo.term = ping.Term\n\t\t\t\tc.fo.leader = ping.Leader\n\t\t\t\tlog.Printf(\"cluster: leader '%s' elected\", c.fo.leader)\n\t\t\t} else if ping.Leader != c.fo.leader {\n\t\t\t\tif c.fo.leader != \"\" {\n\t\t\t\t\t// Wrong leader. It's a bug, should never happen!\n\t\t\t\t\tlog.Printf(\"cluster: wrong leader '%s' while expecting '%s'; term %d\",\n\t\t\t\t\t\tping.Leader, c.fo.leader, ping.Term)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Printf(\"cluster: leader set to '%s'\", ping.Leader)\n\t\t\t\t}\n\t\t\t\tc.fo.leader = ping.Leader\n\t\t\t}\n\n\t\t\tmissed = 0\n\t\t\tif ping.Signature != c.ring.Signature() {\n\t\t\t\tif rehashSkipped {\n\t\t\t\t\tlog.Println(\"cluster: rehashing at a request of\",\n\t\t\t\t\t\tping.Leader, ping.Nodes, ping.Signature, c.ring.Signature())\n\t\t\t\t\tc.rehash(ping.Nodes)\n\t\t\t\t\trehashSkipped = false\n\n\t\t\t\t\t//globals.hub.rehash <- true\n\t\t\t\t} else {\n\t\t\t\t\trehashSkipped = true\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase vreq := <-c.fo.electionVote:\n\t\t\tif c.fo.term < vreq.req.Term {\n\t\t\t\t// This is a new election. This node has not voted yet. Vote for the requestor and\n\t\t\t\t// clear the current leader.\n\t\t\t\tlog.Printf(\"Voting YES for %s, my term %d, vote term %d\", vreq.req.Node, c.fo.term, vreq.req.Term)\n\t\t\t\tc.fo.term = vreq.req.Term\n\t\t\t\tc.fo.leader = \"\"\n\t\t\t\tvreq.resp <- ClusterVoteResponse{Result: true, Term: c.fo.term}\n\t\t\t} else {\n\t\t\t\t// This node has voted already or stale election, reject.\n\t\t\t\tlog.Printf(\"Voting NO for %s, my term %d, vote term %d\", vreq.req.Node, c.fo.term, vreq.req.Term)\n\t\t\t\tvreq.resp <- ClusterVoteResponse{Result: false, Term: c.fo.term}\n\t\t\t}\n\t\tcase <-c.fo.done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (crc *clusterReconcileContext) reconcile() error {\n\tif crc.tinkerbellCluster.Spec.ControlPlaneEndpoint.Host == \"\" {\n\t\tif err := crc.populateControlplaneHost(); err != nil {\n\t\t\treturn fmt.Errorf(\"populating controlplane host: %w\", err)\n\t\t}\n\t}\n\n\t// TODO: How can we support changing that?\n\tif crc.tinkerbellCluster.Spec.ControlPlaneEndpoint.Port != KubernetesAPIPort {\n\t\tcrc.tinkerbellCluster.Spec.ControlPlaneEndpoint.Port = KubernetesAPIPort\n\t}\n\n\tcrc.tinkerbellCluster.Status.Ready = true\n\n\tcontrollerutil.AddFinalizer(crc.tinkerbellCluster, infrastructurev1alpha3.ClusterFinalizer)\n\n\tcrc.log.Info(\"Setting cluster status to ready\")\n\n\tif err := crc.patchHelper.Patch(crc.ctx, crc.tinkerbellCluster); err != nil {\n\t\treturn fmt.Errorf(\"patching cluster object: %w\", err)\n\t}\n\n\treturn nil\n}", "func (a *Airlock) checkConsistency(ctx context.Context, group string, maxSlots uint64) {\n\tif a == nil {\n\t\tlogrus.Error(\"consistency check, nil Airlock\")\n\t\treturn\n\t}\n\n\tinnerCtx, cancel := context.WithTimeout(ctx, a.EtcdTxnTimeout)\n\tdefer cancel()\n\n\t// TODO(lucab): re-arrange so that the manager can be re-used.\n\tmanager, err := lock.NewManager(innerCtx, a.EtcdEndpoints, a.ClientCertPubPath, a.ClientCertKeyPath, a.EtcdTxnTimeout, group, maxSlots)\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"reason\": err.Error(),\n\t\t}).Warn(\"consistency check, manager creation failed\")\n\t\treturn\n\t}\n\tdefer manager.Close()\n\n\tsemaphore, err := manager.FetchSemaphore(innerCtx)\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"reason\": err.Error(),\n\t\t}).Warn(\"consistency check, semaphore fetch failed\")\n\t\treturn\n\t}\n\n\t// Update metrics.\n\tdatabaseLocksGauge.WithLabelValues(group).Set(float64(len(semaphore.Holders)))\n\tdatabaseSlotsGauge.WithLabelValues(group).Set(float64(semaphore.TotalSlots))\n\n\t// Log any inconsistencies.\n\tif semaphore.TotalSlots != maxSlots {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"config\": maxSlots,\n\t\t\t\"database\": semaphore.TotalSlots,\n\t\t\t\"group\": group,\n\t\t}).Warn(\"semaphore max slots consistency check failed\")\n\t}\n\tif semaphore.TotalSlots < uint64(len(semaphore.Holders)) {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"group\": group,\n\t\t\t\"holder\": len(semaphore.Holders),\n\t\t\t\"slots\": semaphore.TotalSlots,\n\t\t}).Warn(\"semaphore locks consistency check failed\")\n\t}\n}", "func (c *managedClusterLeaseController) sync(ctx context.Context, syncCtx factory.SyncContext) error {\n\tcluster, err := c.hubClusterLister.Get(c.clusterName)\n\t// unable to get managed cluster, make sure there is no lease update routine.\n\tif err != nil {\n\t\tc.leaseUpdater.stop()\n\t\treturn fmt.Errorf(\"unable to get managed cluster %q from hub: %w\", c.clusterName, err)\n\t}\n\n\t// the managed cluster is not accepted, make sure there is no lease update routine.\n\tif !meta.IsStatusConditionTrue(cluster.Status.Conditions, clusterv1.ManagedClusterConditionHubAccepted) {\n\t\tc.leaseUpdater.stop()\n\t\treturn nil\n\t}\n\n\tobservedLeaseDurationSeconds := cluster.Spec.LeaseDurationSeconds\n\t// for backward compatible, release-2.1 has mutating admission webhook to mutate this field,\n\t// but release-2.0 does not have the mutating admission webhook\n\tif observedLeaseDurationSeconds == 0 {\n\t\tobservedLeaseDurationSeconds = 60\n\t}\n\n\t// if lease duration is changed, start a new lease update routine.\n\tif c.lastLeaseDurationSeconds != observedLeaseDurationSeconds {\n\t\tc.lastLeaseDurationSeconds = observedLeaseDurationSeconds\n\t\tc.leaseUpdater.stop()\n\t\tc.leaseUpdater.start(ctx, time.Duration(c.lastLeaseDurationSeconds)*time.Second)\n\t}\n\n\treturn nil\n}", "func (ck *Clerk) Get(key string) string {\n\n\t// You will have to modify this function.\n\tgetArgs := &GetArgs{}\n\tgetArgs.Key = key\n\t//get leader first\n\tDPrintf(\"client: %v reqeust get key:%s\", ck.ID, key)\n\tvar leaderNum int\n\tvar ret string\n\tck.mu.Lock()\n\tgetArgs.CommSeq = ck.commSeq\n\tck.commSeq++\n\tck.mu.Unlock()\n\tgetArgs.ClientID = ck.ID\n\tfor true {\n\t\tgetReply := &GetReply{}\n\t\tif ck.LeaderIndex != -1 {\n\t\t\tleaderNum = ck.LeaderIndex\n\t\t} else {\n\t\t\tleaderNum = (int(nrand()) % len(ck.servers))\n\t\t}\n\t\tDPrintf(\"client %v: get leaderNum %d\", ck.ID, leaderNum)\n\t\tok := ck.servers[leaderNum].Call(\"KVServer.Get\", getArgs, getReply)\n\t\tif getReply.WrongLeader || !ok {\n\t\t\tDPrintf(\"client: %v ask %d but wrong leader\", ck.ID, leaderNum)\n\t\t\t//TODO::optimization needed\n\t\t\tck.LeaderIndex = -1\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t} else if getReply.Err != Err(\"\") {\n\t\t\tDPrintf(\"kv %s: get meets err\", string(getReply.Err))\n\t\t} else {\n\t\t\tret = getReply.Value\n\t\t\tck.LeaderIndex = leaderNum\n\t\t\tbreak\n\t\t}\n\t}\n\tDPrintf(\"client: %v end reqeust get key:%s value:%s\", ck.ID, key, ret)\n\treturn ret\n}", "func TestPartitionRecovery(t *testing.T) {\n\t<-seq2\n\tconfig := DefaultConfig()\n\tconfig.ClusterSize = 5\n\twaitTime := 500 * time.Millisecond\n\tnodes, err := CreateLocalCluster(config)\n\tif err != nil {\n\t\tError.Printf(\"Error creating nodes: %v\", err)\n\t\treturn\n\t}\n\ttimeDelay := randomTimeout(waitTime)\n\t<-timeDelay\n\tclient, err := Connect(nodes[0].GetRemoteSelf().Addr)\n\tfor err != nil {\n\t\tclient, err = Connect(nodes[0].GetRemoteSelf().Addr)\n\t}\n\ttimeDelay = randomTimeout(waitTime)\n\t<-timeDelay\n\terr = client.SendRequest(hashmachine.HASH_CHAIN_INIT, []byte(strconv.Itoa(123)))\n\tif err != nil {\n\t\tt.Errorf(\"Client request failed\")\n\t}\n\taddRequests := 10\n\tfor i := 0; i < addRequests; i++ {\n\t\terr = client.SendRequest(hashmachine.HASH_CHAIN_ADD, []byte(strconv.Itoa(i)))\n\t\t//wait briefly after requests\n\t\ttimeDelay = randomTimeout(waitTime)\n\t\t<-timeDelay\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Hash Add Command Failed %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(5 * waitTime)\n\t<-timeDelay\n\t//origLeader will be partitioned with 1 other node and shouldnt commit past index 12\n\torigLeaderIdx := -1\n\tfor idx, node := range nodes {\n\t\tif node.State == LEADER_STATE {\n\t\t\torigLeaderIdx = idx\n\t\t\tbreak\n\t\t}\n\t}\n\t//put origLeader at index 0\n\ttmp := nodes[0]\n\tnodes[0] = nodes[origLeaderIdx]\n\tnodes[origLeaderIdx] = tmp\n\t//now will separate nodes 0 (leader) and 1 from 2,3,4\n\tfor i := 2; i < 5; i++ {\n\t\tnode := nodes[i]\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[0].GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[1].GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[0].GetRemoteSelf(), *node.GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[1].GetRemoteSelf(), *node.GetRemoteSelf(), false)\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\tnode := nodes[i]\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[2].GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[3].GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[4].GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[2].GetRemoteSelf(), *node.GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[3].GetRemoteSelf(), *node.GetRemoteSelf(), false)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[4].GetRemoteSelf(), *node.GetRemoteSelf(), false)\n\t}\n\t//while no new leader, continue waiting\n\tnewLeaderIdx := -1\n\tfor newLeaderIdx == -1 {\n\t\ttimeDelay = randomTimeout(5 * waitTime)\n\t\t<-timeDelay\n\t\tfor i := 2; i < 5; i++ {\n\t\t\tif nodes[i].State == LEADER_STATE {\n\t\t\t\tnewLeaderIdx = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t//put origLeader at index 2\n\ttmp = nodes[2]\n\tnodes[2] = nodes[newLeaderIdx]\n\tnodes[newLeaderIdx] = tmp\n\t//have new client attempt to connect to origCluster (should fail and be appended to origCluster)\n\t_, err = Connect(nodes[1].GetRemoteSelf().Addr)\n\tif err == nil {\n\t\tt.Errorf(\"Should Have Failed to connect\")\n\t\treturn\n\t}\n\ttimeDelay = randomTimeout(waitTime)\n\t<-timeDelay\n\t//have new client attempt to connect to newCluster (should work)\n\tnewClient, err := Connect(nodes[4].GetRemoteSelf().Addr)\n\tif err != nil {\n\t\tt.Errorf(\"Should Have connected\")\n\t}\n\ttimeDelay = randomTimeout(waitTime)\n\t<-timeDelay\n\t//perform new add requests\n\taddRequests = 10\n\tfor i := 0; i < addRequests; i++ {\n\t\terr = newClient.SendRequest(hashmachine.HASH_CHAIN_ADD, []byte(strconv.Itoa(i)))\n\t\t//wait briefly after requests\n\t\ttimeDelay = randomTimeout(waitTime)\n\t\t<-timeDelay\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Hash Add Command Failed %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(10 * waitTime)\n\t<-timeDelay\n\t//verify log entries are in up to index at 23 (1 connect, 10 requests more than before)\n\tfor i := 2; i < 5; i++ {\n\t\tentry := nodes[i].getLogEntry(nodes[i].getLastLogIndex())\n\t\tif entry.Index != 23 || nodes[i].commitIndex != 23 {\n\t\t\tt.Errorf(\"Partitioned nodes failed to handle requests\")\n\t\t\treturn\n\t\t}\n\t}\n\t//also verify commit index at 12 for original Cluster\n\t//note: last entry is 15 cause of client reg request\n\tfor i := 0; i < 2; i++ {\n\t\tentry := nodes[i].getLogEntry(nodes[i].getLastLogIndex())\n\t\tif nodes[i].commitIndex != 12 || entry.Index != 15 {\n\t\t\tt.Errorf(\"Original nodes have bad last log entry\")\n\t\t\treturn\n\t\t}\n\t}\n\t//restore partition and verify all nodes in cluster have same setup (using network policy)\n\tfor i := 2; i < 5; i++ {\n\t\tnode := nodes[i]\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[0].GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[1].GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[0].GetRemoteSelf(), *node.GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[1].GetRemoteSelf(), *node.GetRemoteSelf(), true)\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\tnode := nodes[i]\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[2].GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[3].GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*node.GetRemoteSelf(), *nodes[4].GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[2].GetRemoteSelf(), *node.GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[3].GetRemoteSelf(), *node.GetRemoteSelf(), true)\n\t\tnode.NetworkPolicy.RegisterPolicy(*nodes[4].GetRemoteSelf(), *node.GetRemoteSelf(), true)\n\t}\n\ttimeDelay = randomTimeout(10 * waitTime)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tentry := node.getLogEntry(node.getLastLogIndex())\n\t\tif entry.Index != 23 || node.commitIndex != 23 {\n\t\t\tt.Errorf(\"Partitioned failed to be resolved\")\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, node := range nodes {\n\t\tnode.IsShutdown = true\n\t\ttimeDelay = randomTimeout(3 * waitTime)\n\t\t<-timeDelay\n\t}\n\tseq3 <- true\n}", "func (t TopicInfo) AllLeadersCorrect() bool {\n\tfor _, partition := range t.Partitions {\n\t\tif partition.Leader != partition.Replicas[0] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func TestRaftPending(t *testing.T) {\n\tID1 := \"1\"\n\tID2 := \"2\"\n\tclusterPrefix := \"TestRaftPending\"\n\n\t// Create n1 node.\n\tfsm1 := newTestFSM(ID1)\n\tn1 := testCreateRaftNode(getTestConfig(ID1, clusterPrefix+ID1), newStorage())\n\t// Create n2 node.\n\tfsm2 := newTestFSM(ID2)\n\tn2 := testCreateRaftNode(getTestConfig(ID2, clusterPrefix+ID2), newStorage())\n\tconnectAllNodes(n1, n2)\n\tn1.Start(fsm1)\n\tn2.Start(fsm2)\n\tn2.ProposeInitialMembership([]string{ID1, ID2})\n\n\t// Find out who leader is.\n\tvar leader *Raft\n\tvar follower *Raft\n\tselect {\n\tcase <-fsm1.leaderCh:\n\t\tleader = n1\n\t\tfollower = n2\n\tcase <-fsm2.leaderCh:\n\t\tleader = n2\n\t\tfollower = n1\n\t}\n\n\t// Prpose a command on leader.\n\tpending := leader.Propose([]byte(\"I'm data\"))\n\n\t// Block until the command concludes.\n\t<-pending.Done\n\n\t// \"Apply\" should return the exact command back.\n\tif pending.Err != nil {\n\t\tt.Fatal(\"expected no error returned in pending\")\n\t}\n\tif string(pending.Res.([]byte)) != \"I'm data\" {\n\t\tt.Fatal(\"expected exact command to be returned in pending.\")\n\t}\n\n\t// Propose to non-leader node should result an error.\n\tpending = follower.Propose([]byte(\"I'm data too\"))\n\n\t// Block until the command concludes.\n\t<-pending.Done\n\n\t// Should return an error \"ErrNodeNotLeader\" when propose command to non-leader node.\n\tif pending.Err != ErrNodeNotLeader {\n\t\tt.Fatalf(\"expected to get error %q when propose to non-leader node\", ErrNodeNotLeader)\n\t}\n}", "func (s) TestResourceResolverNoChangeNoUpdate(t *testing.T) {\n\tfakeClient := fakeclient.NewClient()\n\trr := newResourceResolver(&clusterResolverBalancer{xdsClient: fakeClient})\n\trr.updateMechanisms([]DiscoveryMechanism{\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[0],\n\t\t},\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[1],\n\t\t\tMaxConcurrentRequests: newUint32(100),\n\t\t},\n\t})\n\tctx, ctxCancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer ctxCancel()\n\tgotEDSName1, err := fakeClient.WaitForWatchEDS(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotEDSName1 != testClusterNames[0] {\n\t\tt.Fatalf(\"xdsClient.WatchEDS called for cluster: %v, want: %v\", gotEDSName1, testClusterNames[0])\n\t}\n\tgotEDSName2, err := fakeClient.WaitForWatchEDS(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotEDSName2 != testClusterNames[1] {\n\t\tt.Fatalf(\"xdsClient.WatchEDS called for cluster: %v, want: %v\", gotEDSName2, testClusterNames[1])\n\t}\n\n\t// Invoke callback, should get an update.\n\tfakeClient.InvokeWatchEDSCallback(gotEDSName1, testEDSUpdates[0], nil)\n\t// Shouldn't send update, because only one resource received an update.\n\tshortCtx, shortCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shortCancel()\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tt.Fatalf(\"get unexpected update %+v\", u)\n\tcase <-shortCtx.Done():\n\t}\n\tfakeClient.InvokeWatchEDSCallback(gotEDSName2, testEDSUpdates[1], nil)\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tif diff := cmp.Diff(u.priorities, []priorityConfig{\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[0],\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[0],\n\t\t\t\tchildNameGen: newNameGenerator(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tmechanism: DiscoveryMechanism{\n\t\t\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\t\t\tCluster: testClusterNames[1],\n\t\t\t\t\tMaxConcurrentRequests: newUint32(100),\n\t\t\t\t},\n\t\t\t\tedsResp: testEDSUpdates[1],\n\t\t\t\tchildNameGen: newNameGenerator(1),\n\t\t\t},\n\t\t}, cmp.AllowUnexported(priorityConfig{}, nameGenerator{})); diff != \"\" {\n\t\t\tt.Fatalf(\"got unexpected resource update, diff (-got, +want): %v\", diff)\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t}\n\n\t// Send the same resources with the same priorities, shouldn't any change.\n\trr.updateMechanisms([]DiscoveryMechanism{\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[0],\n\t\t},\n\t\t{\n\t\t\tType: DiscoveryMechanismTypeEDS,\n\t\t\tCluster: testClusterNames[1],\n\t\t\tMaxConcurrentRequests: newUint32(100),\n\t\t},\n\t})\n\tshortCtx, shortCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shortCancel()\n\tif n, err := fakeClient.WaitForWatchEDS(shortCtx); err == nil {\n\t\tt.Fatalf(\"unexpected watch started for EDS: %v\", n)\n\t}\n\tshortCtx, shortCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shortCancel()\n\tselect {\n\tcase u := <-rr.updateChannel:\n\t\tt.Fatalf(\"unexpected update: %+v\", u)\n\tcase <-shortCtx.Done():\n\t}\n\n\t// Close the resource resolver. Should stop EDS watch.\n\trr.stop()\n\tedsNameCanceled1, err := fakeClient.WaitForCancelEDSWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\tif edsNameCanceled1 != gotEDSName1 && edsNameCanceled1 != gotEDSName2 {\n\t\tt.Fatalf(\"xdsClient.CancelEDS called for %v, want: %v or %v\", edsNameCanceled1, gotEDSName1, gotEDSName2)\n\t}\n\tedsNameCanceled2, err := fakeClient.WaitForCancelEDSWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\tif edsNameCanceled2 != gotEDSName2 && edsNameCanceled2 != gotEDSName1 {\n\t\tt.Fatalf(\"xdsClient.CancelEDS called for %v, want: %v or %v\", edsNameCanceled2, gotEDSName1, gotEDSName2)\n\t}\n}", "func (c *Configuration) readCorrectable(ctx context.Context, a *ReadRequest, resp *CorrectableState) {\n\tvar ti traceInfo\n\tif c.mgr.opts.trace {\n\t\tti.Trace = trace.New(\"gorums.\"+c.tstring()+\".Sent\", \"ReadCorrectable\")\n\t\tdefer ti.Finish()\n\n\t\tti.firstLine.cid = c.id\n\t\tif deadline, ok := ctx.Deadline(); ok {\n\t\t\tti.firstLine.deadline = deadline.Sub(time.Now())\n\t\t}\n\t\tti.LazyLog(&ti.firstLine, false)\n\t\tti.LazyLog(&payload{sent: true, msg: a}, false)\n\n\t\tdefer func() {\n\t\t\tti.LazyLog(&qcresult{\n\t\t\t\tids: resp.NodeIDs,\n\t\t\t\treply: resp.State,\n\t\t\t\terr: resp.err,\n\t\t\t}, false)\n\t\t\tif resp.err != nil {\n\t\t\t\tti.SetError()\n\t\t\t}\n\t\t}()\n\t}\n\n\texpected := c.n\n\treplyChan := make(chan internalState, expected)\n\tfor _, n := range c.nodes {\n\t\tgo callGRPCReadCorrectable(ctx, n, a, replyChan)\n\t}\n\n\tvar (\n\t\treplyValues = make([]*State, 0, c.n)\n\t\tclevel = LevelNotSet\n\t\treply *State\n\t\trlevel int\n\t\terrCount int\n\t\tquorum bool\n\t)\n\n\tfor {\n\t\tselect {\n\t\tcase r := <-replyChan:\n\t\t\tresp.NodeIDs = append(resp.NodeIDs, r.nid)\n\t\t\tif r.err != nil {\n\t\t\t\terrCount++\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif c.mgr.opts.trace {\n\t\t\t\tti.LazyLog(&payload{sent: false, id: r.nid, msg: r.reply}, false)\n\t\t\t}\n\t\t\treplyValues = append(replyValues, r.reply)\n\t\t\treply, rlevel, quorum = c.qspec.ReadCorrectableQF(replyValues)\n\t\t\tif quorum {\n\t\t\t\tresp.set(reply, rlevel, nil, true)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif rlevel > clevel {\n\t\t\t\tclevel = rlevel\n\t\t\t\tresp.set(reply, rlevel, nil, false)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tresp.set(reply, clevel, QuorumCallError{ctx.Err().Error(), errCount, len(replyValues)}, true)\n\t\t\treturn\n\t\t}\n\n\t\tif errCount+len(replyValues) == expected {\n\t\t\tresp.set(reply, clevel, QuorumCallError{\"incomplete call\", errCount, len(replyValues)}, true)\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestClusteringBasic(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\tfor _, s := range servers {\n\t\tcheckState(t, s, Clustered)\n\t}\n\n\t// Wait for leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Publish a message (this will create the channel and form the Raft group).\n\tchannel := \"foo\"\n\tif err := sc.Publish(channel, []byte(\"hello\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\tch := make(chan *stan.Msg, 100)\n\tsub, err := sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\n\tsub.Unsubscribe()\n\n\tstopped := []*StanServer{}\n\n\t// Take down the leader.\n\tleader := getLeader(t, 10*time.Second, servers...)\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Wait for the new leader to be elected.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Read everything back from the channel.\n\tsub, err = sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tselect {\n\t\tcase msg := <-ch:\n\t\t\tassertMsg(t, msg.MsgProto, []byte(strconv.Itoa(i)), uint64(i+2))\n\t\tcase <-time.After(2 * time.Second):\n\t\t\tt.Fatal(\"expected msg\")\n\t\t}\n\t}\n\n\tsub.Unsubscribe()\n\n\t// Take down the leader.\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Creating a new connection should fail since there should not be a leader.\n\t_, err = stan.Connect(clusterName, clientName+\"-2\", stan.PubAckWait(time.Second), stan.ConnectWait(time.Second))\n\tif err == nil {\n\t\tt.Fatal(\"Expected error on connect\")\n\t}\n\n\t// Bring one node back up.\n\ts := stopped[0]\n\tstopped = stopped[1:]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Wait for the new leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(\"foo-\"+strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Bring the last node back up.\n\ts = stopped[0]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Ensure there is still a leader.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish one more message.\n\tif err := sc.Publish(channel, []byte(\"goodbye\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\t// Verify the server stores are consistent.\n\texpected := make(map[uint64]msg, 12)\n\texpected[1] = msg{sequence: 1, data: []byte(\"hello\")}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+2] = msg{sequence: uint64(i + 2), data: []byte(strconv.Itoa(int(i)))}\n\t}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+7] = msg{sequence: uint64(i + 7), data: []byte(\"foo-\" + strconv.Itoa(int(i)))}\n\t}\n\texpected[12] = msg{sequence: 12, data: []byte(\"goodbye\")}\n\tverifyChannelConsistency(t, channel, 10*time.Second, 1, 12, expected, servers...)\n\n\tsc.Close()\n\t// Speed-up shutdown\n\tleader.Shutdown()\n\ts1.Shutdown()\n\ts2.Shutdown()\n\ts3.Shutdown()\n}", "func (node *RaftNode) Connect_raft_node(ctx context.Context, id int, rep_addrs []string, testing bool) {\n\n\t/*\n\t * Connect the new node to the existing nodes.\n\t * Attempt to gRPC dial to other replicas and obtain corresponding client stubs.\n\t * ConnectToPeerReplicas is defined in raft_node.go.\n\t */\n\tlog.Println(\"Obtaining client stubs of gRPC servers running at peer replicas...\")\n\tnode.ConnectToPeerReplicas(ctx, rep_addrs)\n\n\t// Setting up and running the gRPC server\n\tgrpc_address := \":500\" + strconv.Itoa(id)\n\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp4\", grpc_address)\n\tCheckErrorFatal(err)\n\n\tlistener, err := net.ListenTCP(\"tcp\", tcpAddr)\n\tCheckErrorFatal(err)\n\n\tnode.Meta.grpc_server = grpc.NewServer()\n\n\t/*\n\t * ConsensusService is defined in protos/replica.proto\n\t * RegisterConsensusServiceServer is present in the generated .pb.go file\n\t */\n\tprotos.RegisterConsensusServiceServer(node.Meta.grpc_server, node)\n\n\t// Running the gRPC server\n\tgo node.StartGRPCServer(ctx, grpc_address, listener, testing)\n\n\t// wait till grpc server is up\n\tconnxn, err := grpc.Dial(grpc_address, grpc.WithInsecure())\n\n\t// below block may not be needed\n\tfor err != nil {\n\t\tconnxn, err = grpc.Dial(grpc_address, grpc.WithInsecure())\n\t}\n\n\tfor {\n\n\t\tif connxn.GetState() == connectivity.Ready {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(20 * time.Millisecond)\n\n\t}\n\n\t// Now we can start listening to client requests\n\n\t// Set up the server that listens for client requests.\n\tserver_address := \":400\" + strconv.Itoa(id)\n\tlog.Println(\"Starting raft replica server...\")\n\tgo node.StartRaftServer(ctx, server_address, testing)\n\n\ttest_addr := fmt.Sprintf(\"http://localhost%s/test\", server_address)\n\n\t// Check whether the server is active\n\tfor {\n\n\t\t_, err = http.Get(test_addr)\n\n\t\tif err == nil {\n\t\t\tlog.Printf(\"\\nRaft replica server up and listening at port %s\\n\", server_address)\n\t\t\tbreak\n\t\t}\n\n\t}\n\n}", "func TestLeaderTransferToUpToDateNode(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tlead := nt.peers[1].(*raft)\n\n\tif lead.lead != 1 {\n\t\tt.Fatalf(\"after election leader is %x, want 1\", lead.lead)\n\t}\n\n\t// Transfer leadership to 2.\n\tnt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateFollower, 2)\n\n\t// After some log replication, transfer leadership back to 1.\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})\n\n\tnt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateLeader, 1)\n}", "func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{} //一个raft实例\n\trf.peers = peers //一个raft实例包含的所有servers\n\trf.persister = persister //存放这台机器的持久状态persistent state\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.currentTerm = 0 //initialized to 0 on first boot\n\trf.state = \"follower\"\n\trf.voteFor = -1 // null if none\n\trf.log = make([]Entry, 1)\n\trf.commitIndex = 0 //initialized to 0\n\trf.lastApplied = 0 //initialized to 0\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\t//DPrintf(\"rf.commitIndex:%d, rf.lastApplied:%d\", rf.commitIndex, rf.lastApplied)\n\tr := time.Duration(rand.Int63()) % ElectionTimeout\n\trf.electionTimer = time.NewTimer(ElectionTimeout + r)\n\trf.appendEntriesTimers = make([]*time.Timer, len(rf.peers))\n\tfor peer := range(rf.peers) {\n\t\trf.appendEntriesTimers[peer] = time.NewTimer(ElectionTimeout)\n\t}\n\trf.applySignal = make(chan bool, 100)\n\trf.applyCh = applyCh\n\trf.applyTimer = time.NewTimer(ApplyLogTimeout)\n\n\t// 选举定时器\n\tgo func() {\n\t\t//DPrintf(\"选举定时器\")\n\t\tfor {\n\t\t\t//if rf.state != \"leader\" {\n\t\t\t//\t<-rf.electionTimer.timer.C // 定时器\n\t\t\t//\t//DPrintf(\"%d is %s, and change to candidate\", rf.me, rf.state)\n\t\t\t//\t//if rf.state == \"follower\" {\n\t\t\t//\trf.changeState(\"candidate\")\n\t\t\t//\t//}\n\t\t\t//\t//rf.mu.Unlock()\n\t\t\t//} else {\n\t\t\t//\trf.electionTimer.timer.Stop()\n\t\t\t//}\n\t\t\t// 即使被选为leader,选举定时器也不能停止,因为如果一旦有peer down出现,并且达不到quorum 法定人数,则不允许有leader被选出\n\t\t\t<-rf.electionTimer.C // 定时器\n\t\t\trf.changeState(\"candidate\")\n\t\t}\n\t}()\n\n\t// 发送appendEntries定时器\n\tfor peer := range(rf.peers) {\n\t\tif peer == rf.me {\n\t\t\tcontinue\n\t\t}\n\t\tgo func(peer int) {\n\t\t\tfor {\n\t\t\t\t<-rf.appendEntriesTimers[peer].C\n\t\t\t\tif rf.state == \"leader\" {\n\t\t\t\t\trf.appendEntries2Peer(peer)\n\t\t\t\t}\n\t\t\t}\n\t\t}(peer)\n\t}\n\n\t// commit 定时器\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-rf.applyTimer.C:\n\t\t\t\trf.applySignal <- true\n\t\t\tcase <-rf.applySignal:\n\t\t\t\trf.apply()\n\t\t\t}\n\t\t}\n\n\t}()\n\n\n\tgo func() {\n\t\tfor !rf.killed() {\n\t\t\ttime.Sleep(2000 * time.Millisecond)\n\t\t\tif rf.lockName != \"\" {\n\t\t\t\tDPrintf(\"%d who has lock: %s; iskilled:%v; duration: %v; MaxLockTime is :%v; rf.loclkStart: %v; rf.lockEnd: %v\\n\", rf.me, rf.lockName, rf.killed(), rf.lockEnd.Sub(rf.lockStart).Nanoseconds()/1e6, MaxLockTime, rf.lockStart, rf.lockEnd)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn rf\n}", "func (c *Client) Get(key string) string {\n\ti := c.prefReplica\n\tfor {\n\t\tresp, err := c.raftClients[i].Get(context.Background(), &proto.GetReq{\n\t\t\tKey: key,\n\t\t})\n\t\tif err != nil {\n\t\t\tc.logger.Errorf(\"Error during GET: %s\", err)\n\n\t\t\ti = (i + 1) % len(c.raftClients)\n\t\t\tif i == c.prefReplica {\n\t\t\t\t// Wait if tried all replicas already\n\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t}\n\t\t} else {\n\t\t\treturn resp.Value\n\t\t}\n\t}\n}", "func main() {\n\t// get a bucket and mc.Client connection\n\tbucket, err := getTestConnection(\"default\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// start upr feed\n\tfeed, err := bucket.StartUprFeed(\"index\" /*name*/, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i := 0; i < vbcount; i++ {\n\t\terr := feed.UprRequestStream(\n\t\t\tuint16(i) /*vbno*/, uint16(0) /*opaque*/, 0 /*flag*/, 0, /*vbuuid*/\n\t\t\t0 /*seqStart*/, 0xFFFFFFFFFFFFFFFF /*seqEnd*/, 0 /*snaps*/, 0)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err.Error())\n\t\t}\n\t}\n\n\tvbseqNo := receiveMutations(feed, 20000)\n\n\tvbList := make([]uint16, 0)\n\tfor i := 0; i < vbcount; i++ {\n\t\tvbList = append(vbList, uint16(i))\n\t}\n\tfailoverlogMap, err := bucket.GetFailoverLogs(vbList)\n\tif err != nil {\n\t\tlog.Printf(\" error in failover log request %s\", err.Error())\n\n\t}\n\n\t// get a bucket and mc.Client connection\n\tbucket1, err := getTestConnection(\"default\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// add mutations to the bucket\n\tvar mutationCount = 5000\n\taddKVset(bucket1, mutationCount)\n\n\tlog.Println(\"Restarting ....\")\n\tfeed, err = bucket.StartUprFeed(\"index\" /*name*/, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i := 0; i < vbcount; i++ {\n\t\tlog.Printf(\"Vbucket %d High sequence number %d, Snapshot end sequence %d\", i, vbseqNo[i][0], vbseqNo[i][1])\n\t\tfailoverLog := failoverlogMap[uint16(i)]\n\t\terr := feed.UprRequestStream(\n\t\t\tuint16(i) /*vbno*/, uint16(0) /*opaque*/, 0, /*flag*/\n\t\t\tfailoverLog[0][0], /*vbuuid*/\n\t\t\tvbseqNo[i][0] /*seqStart*/, 0xFFFFFFFFFFFFFFFF, /*seqEnd*/\n\t\t\t0 /*snaps*/, vbseqNo[i][1])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err.Error())\n\t\t}\n\t}\n\n\tvar e, f *memcached.UprEvent\n\tvar mutations int\nloop:\n\tfor {\n\t\tselect {\n\t\tcase f = <-feed.C:\n\t\tcase <-time.After(time.Second):\n\t\t\tbreak loop\n\t\t}\n\n\t\tif f.Opcode == gomemcached.UPR_MUTATION {\n\t\t\tvbseqNo[f.VBucket][0] = f.Seqno\n\t\t\te = f\n\t\t\tmutations += 1\n\t\t}\n\t}\n\n\tlog.Printf(\" got %d mutations\", mutations)\n\n\texptSeq := vbseqNo[e.VBucket][0] + 1\n\n\tif e.Seqno != exptSeq {\n\t\tfmt.Printf(\"Expected seqno %v, received %v\", exptSeq+1, e.Seqno)\n\t\t//panic(err)\n\t}\n\tfeed.Close()\n}", "func TestLessorRecover(t *testing.T) {\n\tlg := zap.NewNop()\n\tdir, be := NewTestBackend(t)\n\tdefer os.RemoveAll(dir)\n\tdefer be.Close()\n\n\tle := newLessor(lg, be, clusterLatest(), LessorConfig{MinLeaseTTL: minLeaseTTL})\n\tdefer le.Stop()\n\tl1, err1 := le.Grant(1, 10)\n\tl2, err2 := le.Grant(2, 20)\n\tif err1 != nil || err2 != nil {\n\t\tt.Fatalf(\"could not grant initial leases (%v, %v)\", err1, err2)\n\t}\n\n\t// Create a new lessor with the same backend\n\tnle := newLessor(lg, be, clusterLatest(), LessorConfig{MinLeaseTTL: minLeaseTTL})\n\tdefer nle.Stop()\n\tnl1 := nle.Lookup(l1.ID)\n\tif nl1 == nil || nl1.ttl != l1.ttl {\n\t\tt.Errorf(\"nl1 = %v, want nl1.ttl= %d\", nl1.ttl, l1.ttl)\n\t}\n\n\tnl2 := nle.Lookup(l2.ID)\n\tif nl2 == nil || nl2.ttl != l2.ttl {\n\t\tt.Errorf(\"nl2 = %v, want nl2.ttl= %d\", nl2.ttl, l2.ttl)\n\t}\n}", "func (r *Raft) leader() int {\n\tr.setNextIndex_All() //so that new leader sets it map\n\tr.sendAppendEntriesRPC() //send Heartbeats\n\twaitTime := 1 //duration between two heartbeats\n\twaitTime_msecs := msecs * time.Duration(waitTime)\n\tHeartbeatTimer := r.StartTimer(HeartbeatTimeout, waitTime) //starts the timer and places timeout object on the channel\n\twaitStepDown := 7\n\tRetryTimer := r.StartTimer(RetryTimeOut, waitStepDown)\n\tresponseCount := 0\n\ttotalCount := 0\n\tfor {\n\t\treq := r.receive() //wait for client append req,extract the msg received on self EventCh\n\t\tswitch req.(type) {\n\t\tcase ClientAppendReq:\n\t\t\t//reset the heartbeat timer, now this sendRPC will maintain the authority of the leader\n\t\t\tHeartbeatTimer.Reset(waitTime_msecs)\n\t\t\trequest := req.(ClientAppendReq)\n\t\t\tData := request.Data\n\t\t\t//No check for semantics of cmd before appending to log?\n\t\t\tr.AppendToLog_Leader(Data) //append to self log as byte array\n\t\t\tr.sendAppendEntriesRPC()\n\t\t\tresponseCount = 0 //for RetryTimer\n\t\tcase AppendEntriesResponse:\n\t\t\tresponse := req.(AppendEntriesResponse)\n\t\t\tresponseCount += 1\n\t\t\tif responseCount >= majority-1 { //excluding self\n\t\t\t\twaitTime_retry := msecs * time.Duration(waitStepDown)\n\t\t\t\tRetryTimer.Reset(waitTime_retry)\n\t\t\t}\n\t\t\tif !response.IsHeartBeat {\n\t\t\t\tretVal := r.serviceAppendEntriesResp(response, HeartbeatTimer, waitTime)\n\t\t\t\tif retVal == follower {\n\t\t\t\t\treturn follower\n\t\t\t\t}\n\t\t\t}\n\t\tcase AppendEntriesReq: // in case some other leader is also in function, it must fall back or remain leader\n\t\t\trequest := req.(AppendEntriesReq)\n\t\t\tif request.Term > r.myCV.CurrentTerm {\n\t\t\t\tr.myCV.CurrentTerm = request.Term //update self Term and step down\n\t\t\t\tr.myCV.VotedFor = -1 //since Term has increased so VotedFor must be reset to reflect for this Term\n\t\t\t\tr.WriteCVToDisk()\n\t\t\t\treturn follower //sender server is the latest leader, become follower\n\t\t\t} else {\n\t\t\t\t//reject the request sending false\n\t\t\t\treply := AppendEntriesResponse{r.myCV.CurrentTerm, false, r.Myconfig.Id, false, r.MyMetaData.LastLogIndex}\n\t\t\t\tr.send(request.LeaderId, reply)\n\t\t\t}\n\n\t\tcase RequestVote:\n\t\t\trequest := req.(RequestVote)\n\t\t\ttotalCount = responseCount + totalCount + 1 //till responses are coming, network is good to go!\n\t\t\tif totalCount >= majority {\n\t\t\t\twaitTime_retry := msecs * time.Duration(waitStepDown)\n\t\t\t\tRetryTimer.Reset(waitTime_retry)\n\t\t\t}\n\t\t\tr.serviceRequestVote(request, leader)\n\n\t\tcase int: //Time out-time to send Heartbeats!\n\t\t\ttimeout := req.(int)\n\t\t\tif timeout == RetryTimeOut { //that means responses are not being received--means partitioned so become follower\n\t\t\t\tRetryTimer.Stop()\n\t\t\t\treturn follower\n\t\t\t}\n\t\t\tif timeout == HeartbeatTimeout {\n\t\t\t\tHeartbeatTimer.Reset(waitTime_msecs)\n\t\t\t\tresponseCount = 0 //since new heartbeat is now being sent\n\t\t\t\t//it depends on nextIndex which is correctly read in prepAE_Req method,since it was AE other than HB(last entry), it would have already modified the nextIndex map\n\t\t\t\tr.sendAppendEntriesRPC()\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Snapshot) Consistent() error {\n\tif s == nil {\n\t\treturn errors.New(\"nil snapshot\")\n\t}\n\tendpoints := GetResourceReferences(s.Resources[types.Cluster].Items)\n\tif len(endpoints) != len(s.Resources[types.Endpoint].Items) {\n\t\treturn fmt.Errorf(\"mismatched endpoint reference and resource lengths: %v != %d\", endpoints, len(s.Resources[types.Endpoint].Items))\n\t}\n\tif err := superset(endpoints, s.Resources[types.Endpoint].Items); err != nil {\n\t\treturn err\n\t}\n\n\troutes := GetResourceReferences(s.Resources[types.Listener].Items)\n\tif len(routes) != len(s.Resources[types.Route].Items) {\n\t\treturn fmt.Errorf(\"mismatched route reference and resource lengths: %v != %d\", routes, len(s.Resources[types.Route].Items))\n\t}\n\treturn superset(routes, s.Resources[types.Route].Items)\n}", "func (kv *ShardKV) ApplyOp(op Op, seqNum int) {\n key := op.Key\n val := op.Value\n doHash := op.DoHash\n id := op.ID\n clientConfigNum := op.ConfigNum\n kvConfigNum := kv.configNum\n shardNum := key2shard(key)\n\n if op.Type != \"Reconfigure\" && (clientConfigNum != kvConfigNum ||\n kv.configs[kvConfigNum].Shards[shardNum] != kv.gid) {\n kv.results[id] = ClientReply{Err:ErrorString}\n return\n }\n\n if op.Type != \"Reconfigure\" {\n DPrintf(\"Group %v servicing shard %v at config %v\", kv.gid, shardNum, kvConfigNum) \n }\n clientID, counter := parseID(id)\n creply, _ := kv.current.dedup[clientID]\n if creply.Counter >= counter && creply.Counter > 0 {\n kv.results[id] = ClientReply{Value:creply.Value, Err:creply.Err, Counter:creply.Counter}\n return\n }\n\n if op.Type == \"Put\" {\n //fmt.Printf(\"Applying put for key %v with value %v at group %v machine %v\\n\", key, val, kv.gid, kv.me)\n prev := kv.storage.Put(key, val, doHash, shardNum, kvConfigNum)\n kv.results[id] = ClientReply{Value:prev, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:prev, Counter: counter, Err:OK}\n } else if op.Type == \"Reconfigure\" {\n _, ok := kv.configs[op.Config.Num]\n if ok || op.Config.Num - kv.configNum != 1 {\n return\n }\n kv.configs[op.Config.Num] = op.Config\n kv.TakeSnapshot(op.Config.Num)\n kv.SyncShards(op.Config.Num)\n } else {\n value := kv.storage.Get(key, shardNum)\n kv.results[id] = ClientReply{Value:value, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:value, Counter: counter, Err:OK}\n }\n}", "func (r *resolver) State(shardName string, cl ConsistencyLevel, directCandidate string) (res rState, err error) {\n\tres.CLevel = cl\n\tm, err := r.Schema.ResolveParentNodes(r.Class, shardName)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tres.NodeMap = m\n\t// count number of valid addr\n\tn := 0\n\tfor name, addr := range m {\n\t\tif name != \"\" && addr != \"\" {\n\t\t\tn++\n\t\t}\n\t}\n\tres.Hosts = make([]string, 0, n)\n\n\t// We must hold the data if candidate is specified hence it must exist\n\t// if specified the direct candidate is alway at index 0\n\tif directCandidate == \"\" {\n\t\tdirectCandidate = r.NodeName\n\t}\n\t// This node should be the first to respond in case if the shard is locally available\n\tif addr := m[directCandidate]; addr != \"\" {\n\t\tres.Hosts = append(res.Hosts, addr)\n\t}\n\tfor name, addr := range m {\n\t\tif name != \"\" && addr != \"\" && name != directCandidate {\n\t\t\tres.Hosts = append(res.Hosts, addr)\n\t\t}\n\t}\n\n\tif res.Len() == 0 {\n\t\treturn res, errNoReplicaFound\n\t}\n\n\tres.Level, err = res.ConsistencyLevel(cl)\n\treturn res, err\n}", "func (f *fakeCluster) Elect() (oldleader *Etcd, err error) {\n\tvar leader *Etcd\n\tfor i, node := range f.nodes {\n\t\tif node.IsLeader() {\n\t\t\tf.tb.Logf(\"leader is node %d, stopping it\", i)\n\t\t\tleader = node\n\t\t\tcopy(f.nodes[i:], f.nodes[i+1:])\n\t\t\tf.nodes = f.nodes[:len(f.nodes)-1]\n\t\t}\n\t}\n\t// close the leader\n\terr = leader.Close()\n\tif err != nil {\n\t\treturn leader, err\n\t}\n\t_, err = f.nodes[0].ClusterState(context.TODO())\n\treturn leader, err\n}", "func (c *RolesChanges) Adjust(leader uint64) (client.NodeRole, []client.NodeInfo) {\n\tif c.size() == 1 {\n\t\treturn -1, nil\n\t}\n\n\t// If the cluster is too small, make sure we have just one voter (us).\n\tif c.size() < minVoters {\n\t\tfor node := range c.State {\n\t\t\tif node.ID == leader || node.Role != client.Voter {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn client.Spare, []client.NodeInfo{node}\n\t\t}\n\t\treturn -1, nil\n\t}\n\n\tonlineVoters := c.list(client.Voter, true)\n\tonlineStandbys := c.list(client.StandBy, true)\n\tofflineVoters := c.list(client.Voter, false)\n\tofflineStandbys := c.list(client.StandBy, false)\n\n\t// If we have exactly the desired number of voters and stand-bys, and they are all\n\t// online, we're good.\n\tif len(offlineVoters) == 0 && len(onlineVoters) == c.Config.Voters && len(offlineStandbys) == 0 && len(onlineStandbys) == c.Config.StandBys {\n\t\treturn -1, nil\n\t}\n\n\t// If we have less online voters than desired, let's try to promote\n\t// some other node.\n\tif n := len(onlineVoters); n < c.Config.Voters {\n\t\tcandidates := c.list(client.StandBy, true)\n\t\tcandidates = append(candidates, c.list(client.Spare, true)...)\n\n\t\tif len(candidates) == 0 {\n\t\t\treturn -1, nil\n\t\t}\n\n\t\tdomains := c.failureDomains(onlineVoters)\n\t\tc.sortCandidates(candidates, domains)\n\n\t\treturn client.Voter, candidates\n\t}\n\n\t// If we have more online voters than desired, let's demote one of\n\t// them.\n\tif n := len(onlineVoters); n > c.Config.Voters {\n\t\tnodes := []client.NodeInfo{}\n\t\tfor _, node := range onlineVoters {\n\t\t\t// Don't demote the leader.\n\t\t\tif node.ID == leader {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodes = append(nodes, node)\n\t\t}\n\n\t\treturn client.Spare, nodes\n\t}\n\n\t// If we have offline voters, let's demote one of them.\n\tif n := len(offlineVoters); n > 0 {\n\t\treturn client.Spare, offlineVoters\n\t}\n\n\t// If we have less online stand-bys than desired, let's try to promote\n\t// some other node.\n\tif n := len(onlineStandbys); n < c.Config.StandBys {\n\t\tcandidates := c.list(client.Spare, true)\n\n\t\tif len(candidates) == 0 {\n\t\t\treturn -1, nil\n\t\t}\n\n\t\tdomains := c.failureDomains(onlineStandbys)\n\t\tc.sortCandidates(candidates, domains)\n\n\t\treturn client.StandBy, candidates\n\t}\n\n\t// If we have more online stand-bys than desired, let's demote one of\n\t// them.\n\tif n := len(onlineStandbys); n > c.Config.StandBys {\n\t\tnodes := []client.NodeInfo{}\n\t\tfor _, node := range onlineStandbys {\n\t\t\t// Don't demote the leader.\n\t\t\tif node.ID == leader {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodes = append(nodes, node)\n\t\t}\n\n\t\treturn client.Spare, nodes\n\t}\n\n\t// If we have offline stand-bys, let's demote one of them.\n\tif n := len(offlineStandbys); n > 0 {\n\t\treturn client.Spare, offlineStandbys\n\t}\n\n\treturn -1, nil\n}", "func TestLearnerReceiveSnapshot(t *testing.T) {\n\t// restore the state machine from a snapshot so it has a compacted log and a snapshot\n\ts := pb.Snapshot{\n\t\tMetadata: pb.SnapshotMetadata{\n\t\t\tIndex: 11, // magic number\n\t\t\tTerm: 11, // magic number\n\t\t\tConfState: pb.ConfState{Nodes: []uint64{1}, Learners: []uint64{2}},\n\t\t},\n\t}\n\n\tstore := NewMemoryStorage()\n\tn1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, store)\n\tn2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(n1)\n\tdefer closeAndFreeRaft(n2)\n\n\tn1.restore(s)\n\tready := newReady(n1, &SoftState{}, pb.HardState{}, true)\n\tstore.ApplySnapshot(ready.Snapshot)\n\tn1.advance(ready)\n\n\t// Force set n1 appplied index.\n\tn1.raftLog.appliedTo(n1.raftLog.committed)\n\n\tnt := newNetwork(n1, n2)\n\n\tsetRandomizedElectionTimeout(n1, n1.electionTimeout)\n\tfor i := 0; i < n1.electionTimeout; i++ {\n\t\tn1.tick()\n\t}\n\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})\n\n\tif n2.raftLog.committed != n1.raftLog.committed {\n\t\tt.Errorf(\"peer 2 must commit to %d, but %d\", n1.raftLog.committed, n2.raftLog.committed)\n\t}\n}", "func ensureClient(config hz.Config) *hz.Client {\n\tfor i := 0; i < 60; i++ {\n\t\tclient, err := hz.StartNewClientWithConfig(context.Background(), config)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, hzerrors.ErrClientNotAllowedInCluster) {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\t\treturn client\n\t}\n\tpanic(\"the client could not connect to the cluster in 60 seconds.\")\n}", "func TestGetSrvKeyspace(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tts, factory := memorytopo.NewServerAndFactory(ctx, \"test_cell\")\n\tsrvTopoCacheTTL = 200 * time.Millisecond\n\tsrvTopoCacheRefresh = 80 * time.Millisecond\n\tdefer func() {\n\t\tsrvTopoCacheTTL = 1 * time.Second\n\t\tsrvTopoCacheRefresh = 1 * time.Second\n\t}()\n\n\trs := NewResilientServer(ctx, ts, \"TestGetSrvKeyspace\")\n\n\t// Ask for a not-yet-created keyspace\n\t_, err := rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\tif !topo.IsErrType(err, topo.NoNode) {\n\t\tt.Fatalf(\"GetSrvKeyspace(not created) got unexpected error: %v\", err)\n\t}\n\n\t// Wait until the cached error expires.\n\ttime.Sleep(srvTopoCacheRefresh + 10*time.Millisecond)\n\n\t// Set SrvKeyspace with value\n\twant := &topodatapb.SrvKeyspace{}\n\terr = ts.UpdateSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\", want)\n\trequire.NoError(t, err, \"UpdateSrvKeyspace(test_cell, test_ks, %s) failed\", want)\n\n\t// wait until we get the right value\n\tvar got *topodatapb.SrvKeyspace\n\texpiry := time.Now().Add(srvTopoCacheRefresh - 20*time.Millisecond)\n\tfor {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgot, err = rs.GetSrvKeyspace(ctx, \"test_cell\", \"test_ks\")\n\t\tcancel()\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"GetSrvKeyspace got unexpected error: %v\", err)\n\t\t}\n\t\tif proto.Equal(want, got) {\n\t\t\tbreak\n\t\t}\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"GetSrvKeyspace() timeout = %+v, want %+v\", got, want)\n\t\t}\n\t\ttime.Sleep(2 * time.Millisecond)\n\t}\n\n\t// Update the value and check it again to verify that the watcher\n\t// is still up and running\n\twant = &topodatapb.SrvKeyspace{Partitions: []*topodatapb.SrvKeyspace_KeyspacePartition{{ServedType: topodatapb.TabletType_REPLICA}}}\n\terr = ts.UpdateSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\", want)\n\trequire.NoError(t, err, \"UpdateSrvKeyspace(test_cell, test_ks, %s) failed\", want)\n\n\t// Wait a bit to give the watcher enough time to update the value.\n\ttime.Sleep(10 * time.Millisecond)\n\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"GetSrvKeyspace got unexpected error: %v\", err)\n\t}\n\tif !proto.Equal(want, got) {\n\t\tt.Fatalf(\"GetSrvKeyspace() = %+v, want %+v\", got, want)\n\t}\n\n\t// make sure the HTML template works\n\tfuncs := map[string]any{}\n\tfor k, v := range StatusFuncs {\n\t\tfuncs[k] = v\n\t}\n\ttempl := template.New(\"\").Funcs(funcs)\n\ttempl, err = templ.Parse(TopoTemplate)\n\tif err != nil {\n\t\tt.Fatalf(\"error parsing template: %v\", err)\n\t}\n\twr := &bytes.Buffer{}\n\tif err := templ.Execute(wr, rs.CacheStatus()); err != nil {\n\t\tt.Fatalf(\"error executing template: %v\", err)\n\t}\n\n\t// Now delete the SrvKeyspace, wait until we get the error.\n\tif err := ts.DeleteSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\"); err != nil {\n\t\tt.Fatalf(\"DeleteSrvKeyspace() failed: %v\", err)\n\t}\n\texpiry = time.Now().Add(5 * time.Second)\n\tfor {\n\t\t_, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif topo.IsErrType(err, topo.NoNode) {\n\t\t\tbreak\n\t\t}\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"timeout waiting for no keyspace error\")\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Now send an updated real value, see it come through.\n\tkeyRange, err := key.ParseShardingSpec(\"-\")\n\tif err != nil || len(keyRange) != 1 {\n\t\tt.Fatalf(\"ParseShardingSpec failed. Expected non error and only one element. Got err: %v, len(%v)\", err, len(keyRange))\n\t}\n\n\twant = &topodatapb.SrvKeyspace{\n\t\tPartitions: []*topodatapb.SrvKeyspace_KeyspacePartition{\n\t\t\t{\n\t\t\t\tServedType: topodatapb.TabletType_PRIMARY,\n\t\t\t\tShardReferences: []*topodatapb.ShardReference{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"-\",\n\t\t\t\t\t\tKeyRange: keyRange[0],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\terr = ts.UpdateSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\", want)\n\trequire.NoError(t, err, \"UpdateSrvKeyspace(test_cell, test_ks, %s) failed\", want)\n\texpiry = time.Now().Add(5 * time.Second)\n\tupdateTime := time.Now()\n\tfor {\n\t\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err == nil && proto.Equal(want, got) {\n\t\t\tbreak\n\t\t}\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"timeout waiting for new keyspace value\")\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Now simulate a topo service error and see that the last value is\n\t// cached for at least half of the expected ttl.\n\terrorTestStart := time.Now()\n\terrorReqsBefore := rs.counts.Counts()[errorCategory]\n\tforceErr := topo.NewError(topo.Timeout, \"test topo error\")\n\tfactory.SetError(forceErr)\n\n\texpiry = time.Now().Add(srvTopoCacheTTL / 2)\n\tfor {\n\t\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err != nil || !proto.Equal(want, got) {\n\t\t\t// On a slow test machine it is possible that we never end up\n\t\t\t// verifying the value is cached because it could take too long to\n\t\t\t// even get into this loop... so log this as an informative message\n\t\t\t// but don't fail the test\n\t\t\tif time.Now().After(expiry) {\n\t\t\t\tt.Logf(\"test execution was too slow -- caching was not verified\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tt.Errorf(\"expected keyspace to be cached for at least %s seconds, got error %v\", time.Since(updateTime), err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Now wait for the TTL to expire and we should get the expected error\n\texpiry = time.Now().Add(1 * time.Second)\n\tfor {\n\t\t_, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err != nil || err == forceErr {\n\t\t\tbreak\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"timed out waiting for error to be returned\")\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Clear the error away and check that the cached error is still returned\n\t// until the refresh interval elapses\n\tfactory.SetError(nil)\n\t_, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\tif err == nil || err != forceErr {\n\t\tt.Errorf(\"expected error to be cached\")\n\t}\n\n\t// Now sleep for the rest of the interval and we should get the value again\n\ttime.Sleep(srvTopoCacheRefresh)\n\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\tif err != nil || !proto.Equal(want, got) {\n\t\tt.Errorf(\"expected value to be restored, got %v\", err)\n\t}\n\n\t// Now sleep for the full TTL before setting the error again to test\n\t// that even when there is no activity on the key, it is still cached\n\t// for the full configured TTL.\n\ttime.Sleep(srvTopoCacheTTL)\n\tforceErr = topo.NewError(topo.Interrupted, \"another test topo error\")\n\tfactory.SetError(forceErr)\n\n\texpiry = time.Now().Add(srvTopoCacheTTL / 2)\n\tfor {\n\t\t_, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"value should have been cached for the full ttl, error %v\", err)\n\t\t}\n\t\tif time.Now().After(expiry) {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Wait again until the TTL expires and we get the error\n\texpiry = time.Now().Add(time.Second)\n\tfor {\n\t\t_, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err != nil {\n\t\t\tif err == forceErr {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.Fatalf(\"expected %v got %v\", forceErr, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"timed out waiting for error\")\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\tfactory.SetError(nil)\n\n\t// Check that the expected number of errors were counted during the\n\t// interval\n\terrorReqs := rs.counts.Counts()[errorCategory]\n\texpectedErrors := int64(time.Since(errorTestStart) / srvTopoCacheRefresh)\n\tif errorReqs-errorReqsBefore > expectedErrors {\n\t\tt.Errorf(\"expected <= %v error requests got %d\", expectedErrors, errorReqs-errorReqsBefore)\n\t}\n\n\t// Check that the watch now works to update the value\n\twant = &topodatapb.SrvKeyspace{}\n\terr = ts.UpdateSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\", want)\n\trequire.NoError(t, err, \"UpdateSrvKeyspace(test_cell, test_ks, %s) failed\", want)\n\texpiry = time.Now().Add(5 * time.Second)\n\tfor {\n\t\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err == nil && proto.Equal(want, got) {\n\t\t\tbreak\n\t\t}\n\t\tif time.Now().After(expiry) {\n\t\t\tt.Fatalf(\"timeout waiting for new keyspace value\")\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Now test with a new error in which the topo service is locked during\n\t// the test which prevents all queries from proceeding.\n\tforceErr = fmt.Errorf(\"test topo error with factory locked\")\n\tfactory.SetError(forceErr)\n\tfactory.Lock()\n\tgo func() {\n\t\ttime.Sleep(srvTopoCacheRefresh * 2)\n\t\tfactory.Unlock()\n\t}()\n\n\texpiry = time.Now().Add(srvTopoCacheTTL / 2)\n\tfor {\n\t\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\t\tif err != nil || !proto.Equal(want, got) {\n\t\t\t// On a slow test machine it is possible that we never end up\n\t\t\t// verifying the value is cached because it could take too long to\n\t\t\t// even get into this loop... so log this as an informative message\n\t\t\t// but don't fail the test\n\t\t\tif time.Now().After(expiry) {\n\t\t\t\tt.Logf(\"test execution was too slow -- caching was not verified\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tt.Errorf(\"expected keyspace to be cached for at least %s seconds, got error %v\", time.Since(updateTime), err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Clear the error, wait for things to proceed again\n\tfactory.SetError(nil)\n\ttime.Sleep(srvTopoCacheTTL)\n\n\tgot, err = rs.GetSrvKeyspace(context.Background(), \"test_cell\", \"test_ks\")\n\tif err != nil || !proto.Equal(want, got) {\n\t\tt.Errorf(\"expected error to clear, got %v\", err)\n\t}\n\n\t// Force another error and lock the topo. Then wait for the TTL to\n\t// expire and verify that the context timeout unblocks the request.\n\n\t// TODO(deepthi): Commenting out this test until we fix https://github.com/vitessio/vitess/issues/6134\n\n\t/*\n\t\tforceErr = fmt.Errorf(\"force long test error\")\n\t\tfactory.SetError(forceErr)\n\t\tfactory.Lock()\n\n\t\ttime.Sleep(*srvTopoCacheTTL)\n\n\t\ttimeoutCtx, cancel := context.WithTimeout(context.Background(), *srvTopoCacheRefresh*2) //nolint\n\t\tdefer cancel()\n\t\t_, err = rs.GetSrvKeyspace(timeoutCtx, \"test_cell\", \"test_ks\")\n\t\twantErr := \"timed out waiting for keyspace\"\n\t\tif err == nil || err.Error() != wantErr {\n\t\t\tt.Errorf(\"expected error '%v', got '%v'\", wantErr, err)\n\t\t}\n\t\tfactory.Unlock()\n\t*/\n}", "func TestRepareting(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tname := \"sharded_message\"\n\n\tctx := context.Background()\n\t// start grpc connection with vtgate and validate client\n\t// connection counts in tablets\n\tstream, err := VtgateGrpcConn(ctx, clusterInstance)\n\trequire.Nil(t, err)\n\tdefer stream.Close()\n\t_, err = stream.MessageStream(userKeyspace, \"\", nil, name)\n\trequire.Nil(t, err)\n\n\tassert.Equal(t, 1, getClientCount(shard0Master))\n\tassert.Equal(t, 0, getClientCount(shard0Replica))\n\tassert.Equal(t, 1, getClientCount(shard1Master))\n\n\t// do planned reparenting, make one replica as master\n\t// and validate client connection count in correspond tablets\n\tclusterInstance.VtctlclientProcess.ExecuteCommandWithOutput(\n\t\t\"PlannedReparentShard\",\n\t\t\"-keyspace_shard\", userKeyspace+\"/-80\",\n\t\t\"-new_master\", shard0Replica.Alias)\n\t// validate topology\n\terr = clusterInstance.VtctlclientProcess.ExecuteCommand(\"Validate\")\n\trequire.Nil(t, err)\n\n\t// Verify connection has migrated.\n\t// The wait must be at least 6s which is how long vtgate will\n\t// wait before retrying: that is 30s/5 where 30s is the default\n\t// message_stream_grace_period.\n\ttime.Sleep(10 * time.Second)\n\tassert.Equal(t, 0, getClientCount(shard0Master))\n\tassert.Equal(t, 1, getClientCount(shard0Replica))\n\tassert.Equal(t, 1, getClientCount(shard1Master))\n\tsession := stream.Session(\"@master\", nil)\n\tcluster.ExecuteQueriesUsingVtgate(t, session, \"insert into sharded_message (id, message) values (3,'hello world 3')\")\n\n\t// validate that we have received inserted message\n\tstream.Next()\n\n\t// make old master again as new master\n\tclusterInstance.VtctlclientProcess.ExecuteCommandWithOutput(\n\t\t\"PlannedReparentShard\",\n\t\t\"-keyspace_shard\", userKeyspace+\"/-80\",\n\t\t\"-new_master\", shard0Master.Alias)\n\t// validate topology\n\terr = clusterInstance.VtctlclientProcess.ExecuteCommand(\"Validate\")\n\trequire.Nil(t, err)\n\ttime.Sleep(10 * time.Second)\n\tassert.Equal(t, 1, getClientCount(shard0Master))\n\tassert.Equal(t, 0, getClientCount(shard0Replica))\n\tassert.Equal(t, 1, getClientCount(shard1Master))\n\n\t_, err = stream.MessageAck(ctx, userKeyspace, name, keyRange(3))\n\trequire.Nil(t, err)\n}", "func TestRestoreWithLearner(t *testing.T) {\n\ts := pb.Snapshot{\n\t\tMetadata: pb.SnapshotMetadata{\n\t\t\tIndex: 11, // magic number\n\t\t\tTerm: 11, // magic number\n\t\t\tConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},\n\t\t},\n\t}\n\n\tstorage := NewMemoryStorage()\n\tsm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)\n\tdefer closeAndFreeRaft(sm)\n\tif ok := sm.restore(s); !ok {\n\t\tt.Error(\"restore fail, want succeed\")\n\t}\n\n\tif sm.raftLog.lastIndex() != s.Metadata.Index {\n\t\tt.Errorf(\"log.lastIndex = %d, want %d\", sm.raftLog.lastIndex(), s.Metadata.Index)\n\t}\n\tif mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {\n\t\tt.Errorf(\"log.lastTerm = %d, want %d\", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)\n\t}\n\tif !sm.isLearner {\n\t\tt.Errorf(\"%x is not learner, want yes\", sm.id)\n\t}\n\tsg := sm.nodes()\n\tif len(sg)+len(sm.learnerNodes()) != len(s.Metadata.ConfState.Nodes)+len(s.Metadata.ConfState.Learners) {\n\t\tt.Errorf(\"sm.Nodes = %+v, length not equal with %+v\", sg, s.Metadata.ConfState)\n\t}\n\tfor _, n := range s.Metadata.ConfState.Nodes {\n\t\tif sm.prs[n].IsLearner {\n\t\t\tt.Errorf(\"sm.Node %x isLearner = %s, want %t\", n, sm.prs[n], false)\n\t\t}\n\t}\n\tif len(s.Metadata.ConfState.Nodes) != len(sm.prs) {\n\t\tt.Errorf(\"sm.Nodes = %+v, length not equal with %+v\", sm.prs, s.Metadata.ConfState.Nodes)\n\t}\n\tfor _, n := range s.Metadata.ConfState.Learners {\n\t\tif !sm.learnerPrs[n].IsLearner {\n\t\t\tt.Errorf(\"sm.Node %x isLearner = %s, want %t\", n, sm.prs[n], true)\n\t\t}\n\t}\n\tif len(s.Metadata.ConfState.Learners) != len(sm.learnerPrs) {\n\t\tt.Errorf(\"sm.Nodes = %+v, length not equal with %+v\", sm.learnerPrs, s.Metadata.ConfState.Learners)\n\t}\n\n\tif ok := sm.restore(s); ok {\n\t\tt.Error(\"restore succeed, want fail\")\n\t}\n}", "func (c *Cluster) Leader() *Store {\n\tfor _, s := range c.Stores {\n\t\tif s.IsLeader() {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.66211784", "0.6423465", "0.5926223", "0.5894299", "0.5792348", "0.57678336", "0.55496424", "0.5541377", "0.55259955", "0.5486153", "0.5483181", "0.54630363", "0.5452382", "0.538989", "0.5353664", "0.53503656", "0.5334872", "0.53203416", "0.53153723", "0.53076434", "0.5301672", "0.52907753", "0.5245764", "0.52404493", "0.5240209", "0.5217516", "0.520703", "0.52020097", "0.5201554", "0.51975596", "0.51615566", "0.5155675", "0.51320606", "0.5113254", "0.5098062", "0.5095415", "0.50922763", "0.50879294", "0.50844455", "0.5069136", "0.5054054", "0.5039695", "0.5031711", "0.502883", "0.5020026", "0.50115204", "0.50079924", "0.49969396", "0.4988691", "0.49883395", "0.49869224", "0.49795648", "0.4973761", "0.49712893", "0.49666318", "0.49620202", "0.49615163", "0.4957547", "0.49573365", "0.4952648", "0.49455255", "0.49398655", "0.49334303", "0.49295834", "0.4921277", "0.49117622", "0.49116927", "0.4911295", "0.49106175", "0.4905401", "0.49053174", "0.48974058", "0.48904657", "0.48826006", "0.48792744", "0.48773643", "0.4868221", "0.48606747", "0.485332", "0.4843218", "0.4840426", "0.48397452", "0.48382172", "0.48347354", "0.4834595", "0.48276004", "0.48260581", "0.48160407", "0.4815152", "0.4814396", "0.48136407", "0.48113313", "0.4805454", "0.480143", "0.48013753", "0.48011035", "0.47997305", "0.47957096", "0.479096", "0.47891665", "0.4787262" ]
0.0
-1
Single path ClearPath of a participant.
func (g *game) ClearPath(participant int) { g.paths[participant] = *NewPathEmpty() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Path) Clear() {\n\tp.Components = p.Components[0:0]\n\tp.Points = p.Points[0:0]\n\treturn\n}", "func (g *game) ResetPath(participant int) {\r\n\t// GeneratePath contains a path-finding algorithm. This function is used as a path finder.\r\n\tGeneratePath := func(g *game, participant int) Path {\r\n\t\tconst icol int = 0 // level\r\n\t\tirow := participant // participant\r\n\t\tgrid := g.ladder.grid\r\n\t\troute := []pixel.Vec{}\r\n\t\tprize := -1\r\n\t\tfor level := icol; level < g.ladder.nLevel; level++ {\r\n\t\t\troute = append(route, grid[irow][level])\r\n\t\t\tprize = irow\r\n\t\t\tif irow+1 < g.ladder.nParticipants {\r\n\t\t\t\tif g.ladder.bridges[irow][level] {\r\n\t\t\t\t\tirow++ // cross the bridge ... to the left (south)\r\n\t\t\t\t\troute = append(route, grid[irow][level])\r\n\t\t\t\t\tprize = irow\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif irow-1 >= 0 {\r\n\t\t\t\tif g.ladder.bridges[irow-1][level] {\r\n\t\t\t\t\tirow-- // cross the bridge ... to the right (north)\r\n\t\t\t\t\troute = append(route, grid[irow][level])\r\n\t\t\t\t\tprize = irow\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// log.Println(participant, prize, irow) //\r\n\r\n\t\t// A path found here is called a route or roads.\r\n\t\treturn *NewPath(route, &prize) // val, not ptr\r\n\t}\r\n\r\n\tg.paths[participant] = GeneratePath(g, participant) // path-find\r\n\tg.paths[participant].OnPassedEachPoint = func(pt pixel.Vec, dir pixel.Vec) {\r\n\t\tg.explosions.ExplodeAt(pt, dir.Scaled(2))\r\n\t}\r\n}", "func (c *Client) Path() string {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn c.path\n}", "func (*CaVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}", "func (c *Client) Path() string {\n\treturn Path\n}", "func (duo *DatumUpdateOne) ClearParticipant() *DatumUpdateOne {\n\tduo.mutation.ClearParticipant()\n\treturn duo\n}", "func Path() string {\n\treturn c.Path\n}", "func (c *container) Path() *Path {\n\tp := &Path{}\n\tc.contents = append(c.contents, p)\n\n\treturn p\n}", "func (c *Client) PathDestroy(i *PathInput) error {\n\tvar err error\n\n\t// Initialize the input\n\ti.opType = \"destroy\"\n\terr = c.InitPathInput(i)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to init destroy path %s: %w\", i.Path, err)\n\t}\n\n\t// Do the actual destroy\n\t_, err = c.Logical().Delete(i.opPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to destroy secret at %s: %w\", i.opPath, err)\n\t}\n\n\treturn err\n}", "func (o ArgoCDSpecServerGrpcIngressOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerGrpcIngress) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (id ID) Path() string {\n\treturn id.path\n}", "func (o IopingSpecVolumeVolumeSourceCephfsOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceCephfs) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (el *Fill) Path() {}", "func (c *Client) Path() (string, error) {\n\treturn c.GetProperty(\"path\")\n}", "func (*CaHttpVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/http_verification_ca/%s\", ref)\n}", "func (hc *HealthCheckArgsOrString) Path() *string {\n\tif hc.IsBasic() {\n\t\treturn aws.String(hc.Basic)\n\t}\n\treturn hc.Advanced.Path\n}", "func (i *Instance) Path() (string, error) {\n\tref, _, _, err := i.GetAsAny(WmiPathKey)\n\treturn ref.(string), err\n}", "func (piuo *ProviderIDUpdateOne) ClearParticpant() *ProviderIDUpdateOne {\n\tpiuo.mutation.ClearParticpant()\n\treturn piuo\n}", "func (tc *TrafficCapture) Path() (string, error) {\n\ttc.RLock()\n\tdefer tc.RUnlock()\n\n\treturn tc.writer.Path()\n}", "func (o ApplicationOperationSyncSourceOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSource) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (m *FileMutation) ResetPath() {\n\tm._path = nil\n}", "func (o ArgoCDSpecServerGrpcIngressPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecServerGrpcIngress) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookieOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConsistentHashLoadBalancerSettingsHttpCookie) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (a *PhonebookAccess1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func (c *CaVerificationCa) GetPath() string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", c.Reference)\n}", "func (s *SimpleHealthCheck) Path() string {\n\treturn s.path\n}", "func (*CaCrl) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/crl/%s\", ref)\n}", "func (*CaHostKeyCert) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_key_cert/%s\", ref)\n}", "func (*CaHostCert) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_cert/%s\", ref)\n}", "func (f *Flock) Path() string {\n\treturn f.path\n}", "func (o FioSpecVolumeVolumeSourceCephfsOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceCephfs) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookieResponseOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConsistentHashLoadBalancerSettingsHttpCookieResponse) string { return v.Path }).(pulumi.StringOutput)\n}", "func (r *experimentalRoute) Path() string {\n\treturn r.local.Path()\n}", "func (o ExcludedPathResponseOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExcludedPathResponse) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (*CaRsa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/rsa/%s\", ref)\n}", "func (o ExcludedPathOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExcludedPath) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (cookie *Cookie) Path(path string) *Cookie {\n\tcookie.path = &path\n\treturn cookie\n}", "func (*CaSigningCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/signing_ca/%s\", ref)\n}", "func (c *Cookie) Path() string {\n\treturn c.path\n}", "func (o ApplicationOperationSyncSourcePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationOperationSyncSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (o IopingSpecVolumeVolumeSourceCephfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceCephfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (cv *Canvas) ClosePath() {\n\tcv.path.ClosePath()\n}", "func (*InterfacePppmodem) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppmodem/%s\", ref)\n}", "func (o ApplicationStatusOperationStateOperationSyncSourceOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSyncSource) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (cd ChildData) Path() string {\n\treturn cd.path\n}", "func (o ArgoCDSpecServerIngressOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerIngress) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (du *DatumUpdate) ClearParticipant() *DatumUpdate {\n\tdu.mutation.ClearParticipant()\n\treturn du\n}", "func (*CaMetaCrl) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/meta_crl/%s\", ref)\n}", "func (o ArgoCDSpecPrometheusRouteOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecPrometheusRoute) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (o IncludedPathResponseOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IncludedPathResponse) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (piu *ProviderIDUpdate) ClearParticpant() *ProviderIDUpdate {\n\tpiu.mutation.ClearParticpant()\n\treturn piu\n}", "func (server *SingleInstance) Path() string {\n\treturn server.path\n}", "func (o ArgoCDSpecServerRouteOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerRoute) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func clearPath(path string, gopath []string) string {\n\tpaths := []string{}\n\nSearchLoop:\n\tfor _, p := range filepath.SplitList(path) {\n\t\tfor _, gopath := range gopath {\n\t\t\tif p == filepath.Join(gopath, \"bin\") {\n\t\t\t\tcontinue SearchLoop\n\t\t\t}\n\t\t}\n\n\t\tpaths = append(paths, p)\n\t}\n\n\treturn strings.Join(paths, \":\")\n}", "func (ge *GollumEvent) Path() string {\n\treturn \"\"\n}", "func (c *CaHttpVerificationCa) GetPath() string {\n\treturn fmt.Sprintf(\"/api/objects/ca/http_verification_ca/%s\", c.Reference)\n}", "func (o FioSpecVolumeVolumeSourceCephfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceCephfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (j *Jail) Path() string {\n\treturn j.path\n}", "func (c *CaGroup) GetPath() string { return fmt.Sprintf(\"/api/objects/ca/group/%s\", c.Reference) }", "func (c *CaCrl) GetPath() string { return fmt.Sprintf(\"/api/objects/ca/crl/%s\", c.Reference) }", "func (dw *DrawingWand) PathClose() {\n\tC.MagickDrawPathClose(dw.dw)\n}", "func SetPath(p string) {\n\tcurrentPath = \"\"\n\tbeginPath = p\n\tdirsAmount = 0\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsStartupProbeHttpGet) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (s *Surface) ClipPath(p *Path) {\n\ts.Ctx.Call(\"clip\", p.obj)\n}", "func (o LocalCopyOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LocalCopy) string { return v.Path }).(pulumi.StringOutput)\n}", "func Path() string {\n\tif path := envPeers(); path != \"\" {\n\t\treturn path\n\t}\n\n\tif path := userPeers(); path != \"\" {\n\t\treturn path\n\t}\n\n\treturn systemPeers()\n}", "func (o LocalCopyResponseOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LocalCopyResponse) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o ArgoCDSpecServerIngressPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecServerIngress) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookiePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConsistentHashLoadBalancerSettingsHttpCookie) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (c classy) Path(path string) Classy {\n\tc.path = path\n\treturn c\n}", "func (o ArgoCDSpecPrometheusRoutePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecPrometheusRoute) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func Path(file *descriptor.FileDescriptorProto) string {\n\treturn strings.Replace(Namespace(file), \"\\\\\", \"/\", -1)\n}", "func (o OfflineNotaryRepository) ClearDelegationPaths(data.RoleName) error {\n\treturn nil\n}", "func (*CaMetaX509) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/meta_x509/%s\", ref)\n}", "func (*CaGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/group/%s\", ref)\n}", "func (c *baseClient) Path(path string) *baseClient {\n\tbaseURL, baseErr := url.Parse(c.url)\n\tpathURL, pathErr := url.Parse(path)\n\t// Bail on parsing error leaving the client's url unmodified\n\tif baseErr != nil || pathErr != nil {\n\t\treturn c\n\t}\n\n\tc.url = baseURL.ResolveReference(pathURL).String()\n\treturn c\n}", "func (o IopingSpecVolumeVolumeSourceHostPathOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceHostPath) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o IncludedPathOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IncludedPath) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (*HttpCffProfile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/cff_profile/%s\", ref)\n}", "func (o ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsStartupProbeHttpGet) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (s *LEAdvertisement1) Path() dbus.ObjectPath {\n\treturn s.config.objectPath\n}", "func (s *switchPortAllocations) Path() string {\n\treturn s.path\n}", "func (c *Cookie) Path(path string) *Cookie { c.path = path; return c }", "func (r *ServiceLinkedRole) Path() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"path\"])\n}", "func (ds *Datastore) stringPath(path string) string {\n\treturn strings.TrimLeft(ds.Path+path, \"/\")\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookieResponsePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConsistentHashLoadBalancerSettingsHttpCookieResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (s *GattDescriptor1) Path() dbus.ObjectPath {\n\treturn s.config.objectPath\n}", "func (m *mountPoint) Path() string {\n\tif m.Volume != nil {\n\t\treturn m.Volume.Path()\n\t}\n\n\treturn m.Source\n}", "func (o ArgoCDSpecServerRoutePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecServerRoute) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (s *session) Path() dbus.ObjectPath {\n\treturn s.path\n}", "func (o FioSpecVolumeVolumeSourceHostPathOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceHostPath) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o BuildStrategySpecBuildStepsLifecyclePreStopHttpGetOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsLifecyclePreStopHttpGet) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (s *sysCC) Path() string {\n\treturn s.path\n}", "func (r Route) Path() string {\n\treturn r.path\n}", "func (p Path) UnencryptedPath() paths.Unencrypted { return p.unencPath }", "func (*CaVerificationCas) GetPath() string { return \"/api/objects/ca/verification_ca/\" }", "func (*InterfacePppoe) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoe/%s\", ref)\n}", "func (m *InviteeMutation) ClearParty() {\n\tm.clearedparty = true\n}", "func (l *LessonTut) Path() base.FilePath { return l.path }", "func (c *clientHandler) Path() string {\n\treturn c.path\n}" ]
[ "0.62280947", "0.57256985", "0.54862976", "0.5433992", "0.5411144", "0.5378296", "0.53192234", "0.5312423", "0.5310817", "0.5300578", "0.5296787", "0.5288634", "0.5287906", "0.5284339", "0.5282591", "0.52736807", "0.52375746", "0.5223153", "0.5210946", "0.5193968", "0.51917934", "0.5186803", "0.517741", "0.5172976", "0.51723087", "0.51712215", "0.5170367", "0.5162209", "0.5156226", "0.51558536", "0.51505864", "0.51504165", "0.5137513", "0.512443", "0.511912", "0.51156884", "0.51127106", "0.5103375", "0.51016027", "0.508902", "0.5067817", "0.50580835", "0.50568527", "0.5052005", "0.5049804", "0.5027989", "0.50270724", "0.50268877", "0.50196123", "0.5004499", "0.4998111", "0.499772", "0.49944556", "0.49891433", "0.4975466", "0.49747428", "0.497223", "0.49699268", "0.49655265", "0.49652484", "0.49613422", "0.49611583", "0.49576482", "0.49553382", "0.49548677", "0.49502075", "0.494969", "0.49488965", "0.49475014", "0.4940938", "0.49284938", "0.49241847", "0.49240276", "0.4921829", "0.4918505", "0.49127492", "0.49123073", "0.49070954", "0.4904568", "0.49044582", "0.48992842", "0.48975864", "0.48961017", "0.48935932", "0.48934525", "0.4890247", "0.48887643", "0.4886973", "0.48868465", "0.48850188", "0.48805392", "0.48738042", "0.48717663", "0.48652628", "0.48627174", "0.48617777", "0.486011", "0.4858825", "0.48538902", "0.48520327" ]
0.7931326
0
ResetPath of a participant.
func (g *game) ResetPath(participant int) { // GeneratePath contains a path-finding algorithm. This function is used as a path finder. GeneratePath := func(g *game, participant int) Path { const icol int = 0 // level irow := participant // participant grid := g.ladder.grid route := []pixel.Vec{} prize := -1 for level := icol; level < g.ladder.nLevel; level++ { route = append(route, grid[irow][level]) prize = irow if irow+1 < g.ladder.nParticipants { if g.ladder.bridges[irow][level] { irow++ // cross the bridge ... to the left (south) route = append(route, grid[irow][level]) prize = irow continue } } if irow-1 >= 0 { if g.ladder.bridges[irow-1][level] { irow-- // cross the bridge ... to the right (north) route = append(route, grid[irow][level]) prize = irow continue } } } // log.Println(participant, prize, irow) // // A path found here is called a route or roads. return *NewPath(route, &prize) // val, not ptr } g.paths[participant] = GeneratePath(g, participant) // path-find g.paths[participant].OnPassedEachPoint = func(pt pixel.Vec, dir pixel.Vec) { g.explosions.ExplodeAt(pt, dir.Scaled(2)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (g *game) ClearPath(participant int) {\r\n\tg.paths[participant] = *NewPathEmpty()\r\n}", "func (r *reaper) resetPath(path string) {\n\tr.pathsMtx.Lock()\n\tr.paths[path] = 0\n\tr.pathsMtx.Unlock()\n}", "func (m *FileMutation) ResetPath() {\n\tm._path = nil\n}", "func SetPath(p string) {\n\tcurrentPath = \"\"\n\tbeginPath = p\n\tdirsAmount = 0\n}", "func SetPath(newpath string) {\n\tpath = newpath\n}", "func (c *Client) SetPath(path string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.path = path\n}", "func (p *Path) Clear() {\n\tp.Components = p.Components[0:0]\n\tp.Points = p.Points[0:0]\n\treturn\n}", "func (m *Message) SetPath(s []string) {\n\tm.Options = m.Options.Minus(URIPath)\n\tfor _, p := range s {\n\t\tm.Options = append(m.Options, Option{URIPath, p})\n\t}\n}", "func (m *Resource) SetPath(name string) error {\n\tif len(m.name) > 0 {\n\t\treturn errors.New(\"name already set\")\n\t}\n\tname = strings.TrimSpace(strings.ToLower(s))\n\tmatched, err := regexp.MatchString(\"^[a-z]{4,15}$\", name)\n\tif err == nil && matched {\n\t\tm.name = name\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(\"name does not match requirements and has not been set: must be ^[a-z]{4-15}$\")\n\t}\n}", "func (d *DeploymentCoreStruct) restorePath() (err error) {\n\tif d.savedPath == \"\" {\n\t\treturn\n\t}\n\terr = os.Chdir(d.savedPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgotrace.Trace(\"GIT: Restored to '%s'\", d.savedPath)\n\td.savedPath = \"\"\n\tgit.UnIndent()\n\treturn\n}", "func (c *CmdReal) SetPath(path string) {\n\tc.cmd.Path = path\n}", "func (o *GetNdmpSettingsVariableParams) SetPath(path *string) {\n\to.Path = path\n}", "func (_m *requestHeaderMapUpdatable) SetPath(path string) {\n\t_m.Called(path)\n}", "func (r *Input) SetPath(path string) error {\n\tquery, err := fetch.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Lock()\n\tr.Path = query\n\tr.Unlock()\n\treturn nil\n}", "func SetPath(path string) {\n\tc.setPath(path)\n}", "func (p Path) UnencryptedPath() paths.Unencrypted { return p.unencPath }", "func (f *LogFile) SetPath(path string) { f.path = path }", "func (m *InviteeMutation) ResetParty() {\n\tm.party = nil\n\tm.clearedparty = false\n}", "func (duo *DatumUpdateOne) ClearParticipant() *DatumUpdateOne {\n\tduo.mutation.ClearParticipant()\n\treturn duo\n}", "func (req *Request) SetPath(parts ...string) *Request {\n\treq.path = \"/\" + strings.Join(parts, \"/\")\n\treturn req\n}", "func (b *Binary) SetPath(pathStr string) {\n\tif pathStr == \"\" {\n\t\treturn\n\t}\n\tref, err := url.Parse(pathStr)\n\tif err != nil {\n\t\treturn\n\t}\n\tb.url = b.url.ResolveReference(ref)\n}", "func (k *Item) SetPath(s string) {\n\tk.SetString(PathKey, s)\n}", "func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetPath(p string) error {\n\tif info, err := os.Stat(p); err != nil {\n\t\treturn err\n\t} else if !info.IsDir() {\n\t\treturn fmt.Errorf(\"path for persistence is not directory\")\n\t}\n\tdataPath = p\n\treturn nil\n}", "func (o OfflineNotaryRepository) ClearDelegationPaths(data.RoleName) error {\n\treturn nil\n}", "func (c *Cookie) SetPath(path string) {\n\tc.path = path\n}", "func (m *wasiSnapshotPreview1Impl) pathRemoveDirectory(pfd wasiFd, ppath list) (err wasiErrno) {\n\tpath, err := m.loadPath(ppath)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tdir, err := m.files.getDirectory(pfd, wasiRightsPathRemoveDirectory)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := dir.Rmdir(path); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func (*CaRsa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/rsa/%s\", ref)\n}", "func (r *Route) Reset() {\n\tr.index = 0\n}", "func (m *RestaurantMutation) ResetURI() {\n\tm.uri = nil\n\tdelete(m.clearedFields, restaurant.FieldURI)\n}", "func (*InterfacePppmodem) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppmodem/%s\", ref)\n}", "func (m *FileMutation) SetPath(s string) {\n\tm._path = &s\n}", "func (*InterfacePppmodem) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppmodem/%s\", ref)\n}", "func (c *clientHandler) SetPath(path string) {\n\tc.path = path\n}", "func SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() // This will still keep the permissions themselves in memory\n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}", "func (c *Quago) setPath(path string) {\n\tc.path = path\n}", "func setPath(path []string, sessionID string) {\n\tdecisionTable := make(map[string][]string)\n\tdecisionTable[\"0001000100010001\"] = path\n\tDecisionTable = decisionTable\n\n\tpacketData := DecisionTableToByteArray(DecisionTable)\n\tblinkPacket := MakeBlinkPacket(\"0001000100010001\", oracleAddr, oracleAddr, DecisionTableType, packetData)\n\n\t// Send the decision table to all the nodes\n\tfor _, nodeAddrString := range nodesTable {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", nodeAddrString)\n\t\tCheckError(err)\n\n\t\t_, err = conn.WriteToUDP(blinkPacket, addr)\n\t\tCheckError(err)\n\t}\n\n\tfmt.Println(\"Paths set\")\n}", "func (m *Message) SetPathString(s string) {\n\tm.SetPath(strings.Split(s, \"/\"))\n}", "func (self *Path) SetPath(src string, des string) {\n\tself.srcPath = src\n\tself.desPath = des\n}", "func (f *IndexFile) SetPath(path string) { f.path = path }", "func clearPath(path string, gopath []string) string {\n\tpaths := []string{}\n\nSearchLoop:\n\tfor _, p := range filepath.SplitList(path) {\n\t\tfor _, gopath := range gopath {\n\t\t\tif p == filepath.Join(gopath, \"bin\") {\n\t\t\t\tcontinue SearchLoop\n\t\t\t}\n\t\t}\n\n\t\tpaths = append(paths, p)\n\t}\n\n\treturn strings.Join(paths, \":\")\n}", "func (m *NametitleMutation) ResetPatient() {\n\tm.patient = nil\n\tm.removedpatient = nil\n}", "func (m *EmployeeMutation) ResetPatient() {\n\tm.patient = nil\n\tm.removedpatient = nil\n}", "func (*CaRsa) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/rsa/%s\", ref)\n}", "func (mc *MenuCreate) SetPath(s string) *MenuCreate {\n\tmc.mutation.SetPath(s)\n\treturn mc\n}", "func (*ItfparamsGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/group/%s\", ref)\n}", "func (fv *FileView) UpdatePath() {\n\tif fv.DirPath == \"\" {\n\t\tfv.DirPath, _ = os.Getwd()\n\t}\n\tfv.DirPath, _ = homedir.Expand(fv.DirPath)\n\tfv.DirPath, _ = filepath.Abs(fv.DirPath)\n}", "func (*SnmpGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/group/%s\", ref)\n}", "func (g *GitLocal) Reset(dir string, commitish string, hard bool) error {\n\treturn g.GitCLI.Reset(dir, commitish, true)\n}", "func (v *Peer) Reset() {\n\tv.Metadata = v.Metadata[:0]\n\tv.PeerID = \"\"\n}", "func (m *GenderMutation) ResetPatient() {\n\tm.patient = nil\n\tm.removedpatient = nil\n}", "func (*SpxGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/group/%s\", ref)\n}", "func (m *OperativerecordMutation) ResetExaminationroom() {\n\tm._Examinationroom = nil\n\tm.cleared_Examinationroom = false\n}", "func (self *RouteBuilder) Path(subPath string) *RouteBuilder {\n\tself.currentPath = subPath\n\treturn self\n}", "func (*InterfacePppoa) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoa/%s\", ref)\n}", "func (*HttpProfile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/profile/%s\", ref)\n}", "func (options *EditLoadBalancerMonitorOptions) SetPath(path string) *EditLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func (*HttpProfile) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/profile/%s\", ref)\n}", "func (*InterfacePppoa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoa/%s\", ref)\n}", "func (*InterfacePppoe) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoe/%s\", ref)\n}", "func (du *DatumUpdate) ClearParticipant() *DatumUpdate {\n\tdu.mutation.ClearParticipant()\n\treturn du\n}", "func UnregisterPath(path string) {\n\troot.unregisterPath(newPathSpec(path))\n}", "func (*InterfacePppoe) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoe/%s\", ref)\n}", "func (j *JSONData) SetPath(v interface{}, path ...string) error {\n\tjson, err := sj.NewJson(j.data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjson.SetPath(path, v)\n\tbt, err := json.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\tj.data = bt\n\treturn nil\n}", "func (a *Agent) Reset() {\n\ta.Sketch.Reset()\n\ta.Buf = nil // TODO: pool\n}", "func (m *ExaminationroomMutation) ResetExaminationroomName() {\n\tm.examinationroom_name = nil\n}", "func (*CaVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}", "func (*SnmpGroup) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/group/%s\", ref)\n}", "func (c *Client) PathDestroy(i *PathInput) error {\n\tvar err error\n\n\t// Initialize the input\n\ti.opType = \"destroy\"\n\terr = c.InitPathInput(i)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to init destroy path %s: %w\", i.Path, err)\n\t}\n\n\t// Do the actual destroy\n\t_, err = c.Logical().Delete(i.opPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to destroy secret at %s: %w\", i.opPath, err)\n\t}\n\n\treturn err\n}", "func (_AnchorChain *AnchorChainTransactor) SetTargetChainPath(opts *bind.TransactOpts, _path string, _method string, _callbackPath string, _callbackMethod string, _crossChainType string) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"setTargetChainPath\", _path, _method, _callbackPath, _callbackMethod, _crossChainType)\n}", "func (*SpxGroup) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/group/%s\", ref)\n}", "func (c *Client) TorrentRenamePath(payload *TorrentRenamePathPayload) (err error) {\n\t// Validate\n\tif payload == nil {\n\t\treturn errors.New(\"payload can't be nil\")\n\t}\n\tif len(payload.IDs) == 0 {\n\t\treturn errors.New(\"there must be at least one ID\")\n\t}\n\t// Send payload\n\tif err = c.rpcCall(\"torrent-rename-path\", payload, nil); err != nil {\n\t\terr = fmt.Errorf(\"'torrent-rename-path' rpc method failed: %v\", err)\n\t}\n\treturn\n}", "func (c *Chain) SetNewFullPath(clientID, connectionID, channelID, portID string) error {\n\treturn c.setPath(&PathEnd{\n\t\tChainID: c.ChainID,\n\t\tClientID: clientID,\n\t\tConnectionID: connectionID,\n\t\tChannelID: channelID,\n\t\tPortID: portID,\n\t})\n}", "func (*CaGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/group/%s\", ref)\n}", "func (*CaVerificationCa) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}", "func (m *DiagnosisMutation) ResetPatient() {\n\tm.patient = nil\n\tm.clearedpatient = false\n}", "func (*InterfaceTunnel) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/tunnel/%s\", ref)\n}", "func (m *Win32LobAppRegistryRule) SetKeyPath(value *string)() {\n m.keyPath = value\n}", "func (ant *Ant) Reset() {\n\tant.location = 0\n\tant.route = nil\n\tant.alpha = 0.0\n\tant.distTravelled = 0\n\tant.tourComplete = false\n\tant.firstPass = true\n}", "func (m *HarborMutation) ResetResource() {\n\tm.resource = nil\n}", "func (m *TransportMutation) ResetNote() {\n\tm.note = nil\n}", "func (*InterfaceTunnel) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/tunnel/%s\", ref)\n}", "func (*BgpGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/group/%s\", ref)\n}", "func (*SnmpTrap) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/trap/%s\", ref)\n}", "func (o *AnimationTreePlayer) Reset() {\n\t//log.Println(\"Calling AnimationTreePlayer.Reset()\")\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(\"AnimationTreePlayer\", \"reset\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (r *Router) SetRelativePath(relativePath string) {\n\tr.relativePath = relativePath\n}", "func (*ItfparamsGroup) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/group/%s\", ref)\n}", "func (p *progress) reset(nodeIndex NodeIndex, nextIndex LogEntryIndex) {\n\tp.MatchIndex[nodeIndex] = 0\n\tp.NextIndex[nodeIndex] = nextIndex\n}", "func (*CaGroup) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/group/%s\", ref)\n}", "func (*CaHttpVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/http_verification_ca/%s\", ref)\n}", "func (b *RouteBuilder) Path(subPath string) *RouteBuilder {\n\tb.currentPath = subPath\n\treturn b\n}", "func (m *BloodtypeMutation) ResetPatient() {\n\tm.patient = nil\n\tm.removedpatient = nil\n}", "func (options *CreateLoadBalancerMonitorOptions) SetPath(path string) *CreateLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func (*HttpCffProfile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/cff_profile/%s\", ref)\n}", "func (o *RelationshipManager) UnsetPhoto() {\n\to.Photo.Unset()\n}", "func (r *Router) Path(method, url string, viewFn View) *Path {\n\tif method != strings.ToUpper(method) {\n\t\tpanicf(\"http method '%s' must be in uppercase\", method)\n\t}\n\n\tp := &Path{\n\t\trouter: r,\n\t\tmethod: method,\n\t\turl: url,\n\t\tfullURL: r.getGroupFullPath(url),\n\t\tview: viewFn,\n\t}\n\n\tr.handlePath(p)\n\n\tp.registered = true\n\n\treturn p\n}", "func (*BgpGroup) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/group/%s\", ref)\n}", "func NormalizePathForTesting(path Path) string {\n\tp := path.String()\n\tif w, ok := path.(WritablePath); ok {\n\t\trel, err := filepath.Rel(w.buildDir(), p)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn rel\n\t}\n\treturn p\n}", "func (*ItfparamsPrimary) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/primary/%s\", ref)\n}", "func (*HttpParentProxy) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/parent_proxy/%s\", ref)\n}" ]
[ "0.7108436", "0.6571989", "0.63909775", "0.59130096", "0.53988624", "0.51365834", "0.51137793", "0.5081069", "0.49706945", "0.4948637", "0.49371397", "0.48576868", "0.48551345", "0.48401654", "0.4819019", "0.47944432", "0.47733396", "0.4750125", "0.47464317", "0.47329056", "0.47276366", "0.47105426", "0.47073716", "0.4703948", "0.4698896", "0.4694133", "0.46910742", "0.46581852", "0.465802", "0.46508378", "0.46339333", "0.46245632", "0.46226045", "0.46196195", "0.46155936", "0.4604951", "0.46008584", "0.4600296", "0.45931524", "0.45879504", "0.45743036", "0.45734695", "0.45615712", "0.45607725", "0.45443738", "0.45440632", "0.45390177", "0.4525211", "0.45214885", "0.45206943", "0.45191827", "0.45021987", "0.4499103", "0.44919327", "0.44857362", "0.447948", "0.44770563", "0.447641", "0.44652528", "0.445737", "0.4456384", "0.44438088", "0.44351926", "0.4430428", "0.4428668", "0.4424451", "0.44242236", "0.44138753", "0.4413371", "0.44093597", "0.44067585", "0.44040582", "0.4394067", "0.43865877", "0.43837285", "0.43835226", "0.4379255", "0.4376362", "0.43762055", "0.43695095", "0.43689528", "0.43635517", "0.43614647", "0.43611905", "0.43558714", "0.43533325", "0.43332678", "0.4326968", "0.43253052", "0.43238646", "0.4323104", "0.43230075", "0.43227568", "0.43214685", "0.43176436", "0.43098086", "0.4308312", "0.43064117", "0.4303227", "0.4296028" ]
0.7322597
0
Shuffle in an approximate time.
func (g *game) Shuffle(times, inMillisecond int) { speed := g.galaxy.Speed() g.galaxy.SetSpeed(speed * 10) { i := 0 for range time.Tick( (time.Millisecond * time.Duration(inMillisecond)) / time.Duration(times), ) { g.bg = gg.RandomNiceColor() g.Reset() i++ if i >= times { break } } } g.galaxy.SetSpeed(speed) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *deck) shuffle() {\n\trand.Seed(time.Now().UnixNano())\n\tfor i := len(d) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\td[i], d[j] = d[j], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\t// now generate rnd num and swap positions\n\tfor i := range d {\n\t\tnewPosition := r.Intn(len(d) - 1)\n\t\td[i], d[newPosition] = d[newPosition], d[i] // swap postions in slice\n\t}\n}", "func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }", "func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }", "func (s *summary) shuffle(rng RNG) {\n\tfor i := len(s.means) - 1; i > 1; i-- {\n\t\ts.Swap(i, rng.Intn(i+1))\n\t}\n}", "func Shuffle(values []float64) {\n\tvar tmp float64\n\tvar j int\n\tfor i := len(values) - 1; i > 0; i-- {\n\t\tj = rand.Int() % i\n\t\ttmp = values[j]\n\t\tvalues[j] = values[i]\n\t\tvalues[i] = tmp\n\t}\n}", "func (d deck) shuffle() {\n\t// To generate new random number, generating a new seed every time\n\tsource := rand.NewSource(time.Now().UnixNano()) // time.Now().UnixNano() generates new int64 every time\n\tr := rand.New(source)\n\n\tfor i := range d {\n\t\tnewPosition := r.Intn(len(d) - 1)\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (d deck) shuffle(){\n\n\n\t// method - 1\n\t//source := rand.NewSource(time.Now().UnixNano())\n\t//r := rand.New(source)\n\n\t// method - 2\n\trand.Seed(time.Now().UnixNano())\n\tmax := len(d)\n\tfor i := range d{\n\t\t//newPosition := r.Intn(max-i)+i\n\t\tnewPosition := rand.Intn(max-i)+i\t\t// generate random number between i and len(deck)\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\n\tfor i := range d {\n\t\tnewPosition := r.Intn(len(d) - 1)\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\trand.Seed(time.Now().UnixNano())\n\n\tfor i := range d {\n\t\tswapPos := rand.Intn(len(d) - 1)\n\t\td[i], d[swapPos] = d[swapPos], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\n\tfor i := range d { // i = index\n\t\tnewPosition := r.Intn(len(d) - 1)\n\n\t\td[i], d[newPosition] = d[newPosition], d[i] //swap them\n\t}\n}", "func (d deck) shuffle() {\n\tdeckLength := len(d)\n\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\n\tfor i := range d {\n\t\tr := r.Intn(deckLength)\n\t\td[i], d[r] = d[r], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\tsource := rand.NewSource(time.Now().UnixNano()) //generate a new seed for random number generator\n\tr := rand.New(source)\n\n\tfor i := range d {\n\t\tnewPosition := r.Intn(len(d) - 1)\n\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (pts testDatapoints) Shuffle() {\n\tfor i := len(pts) - 1; i > 0; i-- {\n\t\tif j := rand.Intn(i + 1); i != j {\n\t\t\tpts[i], pts[j] = pts[j], pts[i]\n\t\t}\n\t}\n}", "func (d deck) shuffle() {\n\trand.Seed(time.Now().UnixNano())\n\t// initial implementation\n\t// maxNdxPlus1 := len(d)\n\t// for i := range d {\n\t// \tnewPosition := rand.Intn(maxNdxPlus1)\n\t// \td[i], d[newPosition] = d[newPosition], d[i]\n\t// }\n\n\t// alternate implementation (using builtin Shuffle() function)\n\trand.Shuffle(len(d), func(i, j int) {\n\t\td[i], d[j] = d[j], d[i]\n\t})\n}", "func Shuffle(a []int) {\n\trand.Seed(time.Now().UnixNano())\n\n\tfor i := range a {\n\t\tj := rand.Intn(i + 1)\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n}", "func (d deck) shuffle() {\n\t//seed value = source\n\t//pass some value to NewSource > use time package\n\t//func Now & func (Time)UnixNano >every single time we run program we will use a new time\n\t//to generate number of type int64, we use that as seed as source object\n\tsource := rand.NewSource(time.Now().UnixNano())\n\n\t//type Rand\n\tr := rand.New(source)\n\n\t//for index or simply i (per convention) -- we need to get the element that we need to iterate over\n\tfor i := range d {\n\t\t//use rand function in math package -- pseudo random generator (by default go uses the exact same seed value)\n\t\t//len is the length of slice\n\t\t//newPosition := rand.Intn(len(d) - 1)\n\n\t\t//with fix to the same seed value (src) -> func New(src Source) *Rand\n\t\tnewPosition := r.Intn(len(d) - 1)\n\n\t\t//swap elements, take whatever is at newPosition and assign to i, take whatever is in i and assign to newPosition\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\t//create new random source, seed value\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\n\t//calling upon r of type rand we can replace rand.Intn() with r.Intn() to generate a random source seed for the Intn()\n\tfor i := range d {\n\t\tnewPosition := r.Intn(len(d) - 1)\n\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\t}\n}", "func (d Deck) Shuffle() {\n\tsource := rand.NewSource(time.Now().UnixNano())\n\tr := rand.New(source)\n\n\tfor i := range d {\n\t\tnewPos := r.Intn(len(d) - 1)\n\n\t\td[i], d[newPos] = d[newPos], d[i]\n\t}\n}", "func (d deck) shuffle() {\n\t/* \t1. create a trully random generator, starts whit a source object (is like a seed)\n\t \tevery sigle time the code runs use the Time object to create a unique value as a source (or seed)\n\t \tfor random number generator, NewSource needs and int64 as param, and UnixNano returns a int64 from actual time */\n\tsource := rand.NewSource(time.Now().UnixNano())\n\t//using the source object creates a random generator object *Rand type\n\tr := rand.New(source)\n\t//2. iterate the deck of cards, we will use only the index of the slice\n\tfor i := range d {\n\t\t//*Rand Object has Intn() method to creates a trully a random int beetwen 0 and lenght of slice - 1\n\t\tnewPosition := r.Intn(len(d) - 1)\n\t\t//4. in every i slice position, swap the values of the indexes, newPosition is a random number\n\t\t//so, the position of cards always will be random\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\n\t}\n\n}", "func ShuffleSeedTime() int64 {\n\treturn time.Now().UnixNano()\n}", "func TestShuffle(t *testing.T) {\n\tdeck := New()\n\tShuffle(deck)\n}", "func Shuffle(n int, swap func(i, j int)) {\n\tglobalRand.Shuffle(n, swap)\n}", "func (d *Deck) shuffle() {\n\tdeck := d.cards\n\tfor i := 1; i < len(deck); i++ {\n\t\tr := rand.Intn(i + 1)\n\t\tif i != r {\n\t\t\tdeck[r], deck[i] = deck[i], deck[r]\n\t\t}\n\t}\n}", "func Shuffle(n int, swap func(i, j int)) {\n\tglobalSource.Shuffle(n, swap)\n}", "func (d deck) shuffle() {\n\t// Get a new Source\n\tsrc := rand.NewSource(time.Now().UTC().UnixNano())\n\n\t// Get a new Rand\n\trandomizer := rand.New(src)\n\n\t// shuffle the cards in the deck\n\tfor i := range d {\n\t\tnewIndx := randomizer.Intn(len(d))\n\t\td[i], d[newIndx] = d[newIndx], d[i]\n\t}\n\n}", "func shufflePoints(ps []Point) {\n\tfor i := 0; i < len(ps)-1; i++ {\n\t\tj := rand.Intn(len(ps)-i) + i\n\t\tps[i], ps[j] = ps[j], ps[i]\n\t}\n}", "func (a Slice[T]) Shuffle() Slice[T] {\n\tfor i := len(a) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n\treturn a\n}", "func (d deck) shuffle() {\n\t// type Rand is a source of random numbers. If we create a value of type Rand, we have the ability to specify the seed, or source of randomness for our number generator.\n\t// To make a value of type Rand, and to make a source, we have to call newSource() and passing in a random int64 number, and pass source to our random number generator\n\t// In summary: we're using current time in nanoseconds to generate a new int64 number every time we start the program. We use that as the \"seed\" to generate a new source object, and we use that source object as the basis for our new random number generator.\n\tsource := rand.NewSource(time.Now().UnixNano()) // https://golang.org/pkg/math/rand/#Source\n\tr := rand.New(source) // r is random number generator of type Rand\n\n\tfor idx := range d {\n\t\tnewPosition := r.Intn(len(d) - 1) // if you have a value of type Rand, you can call Intn https://golang.org/pkg/math/rand/#Rand.Intn\n\n\t\td[idx], d[newPosition] = d[newPosition], d[idx] // swap elements at both idx and\n\t}\n\n}", "func (list *List) Shuffle() {\n\tfor i := range list.data {\n\t\tj := rand.Intn(i + 1)\n\t\tlist.data[i], list.data[j] = list.data[j], list.data[i]\n\t}\n}", "func Shuffle[T any](collection []T) []T {\n\trand.Shuffle(len(collection), func(i, j int) {\n\t\tcollection[i], collection[j] = collection[j], collection[i]\n\t})\n\n\treturn collection\n}", "func shuffle(a []int, n int) []int {\n\tfor i := 0; i < n; i++ {\n\t\tv := a[n+i]\n\t\tfor x := n + i; x > 2*i+1; x-- {\n\t\t\ta[x] = a[x-1]\n\t\t}\n\t\ta[2*i+1] = v\n\t}\n\treturn a\n}", "func (list List) Shuffle() {\n\trand.Seed(time.Now().Unix())\n\trand.Shuffle(len(list), func(i, j int) {\n\t\tlist[i], list[j] = list[j], list[i]\n\t})\n}", "func TestShuffle(t *testing.T) {\n\tdeckcount := 100\n\toffset := 1\n\n\tdeck := Deck{}\n\tcards := make([]Card, deckcount)\n\tdeck.cards = &cards\n\n\tfor i := 0; i < deckcount; i++ {\n\t\tcards[i] = Card{id: i + offset}\n\t}\n\n\tfor i := 0; i < deckcount; i++ {\n\t\tfmt.Println(strconv.Itoa(cards[i].id))\n\t}\n\n\tdeck.Shuffle()\n\n\tavg := (float32(offset+deckcount) / 2)\n\tdesiredtotal := int(avg * (float32(deckcount)))\n\n\tdecktotal := 0\n\tfor i := 0; i < deckcount; i++ {\n\t\tdecktotal += cards[i].id\n\t\tfmt.Println(strconv.Itoa(cards[i].id))\n\t}\n\n\tif desiredtotal != decktotal {\n\t\tt.Error(\"The deck is corrupt, expected \" + strconv.Itoa(desiredtotal) + \" received \" + strconv.Itoa(decktotal))\n\t}\n}", "func Shuffle(availableNumbers []string) []string {\n\trand.Seed(time.Now().UnixNano())\n\tfor i := len(availableNumbers) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\tavailableNumbers[i], availableNumbers[j] = availableNumbers[j], availableNumbers[i]\n\t}\n\treturn availableNumbers\n}", "func Shuffle(cards []Card) []Card {\n\tr := rand.New(rand.NewSource(time.Now().Unix()))\n\tr.Shuffle(len(cards), func(i, j int) {\n\t\tcards[i], cards[j] = cards[j], cards[i]\n\t})\n\treturn cards\n}", "func IntShuffle(values []int) {\n\tvar j, tmp int\n\tfor i := len(values) - 1; i > 0; i-- {\n\t\tj = rand.Int() % i\n\t\ttmp = values[j]\n\t\tvalues[j] = values[i]\n\t\tvalues[i] = tmp\n\t}\n}", "func Shuffle(slice interface{}) {\n\trv := reflect.ValueOf(slice)\n\tswap := reflect.Swapper(slice)\n\tlength := rv.Len()\n\tfor i := length - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\tswap(i, j)\n\t}\n}", "func (this *Solution) Shuffle() []int {\n\t// 随机交换元素的位置\n\ttmp := make([]int, len(this.a))\n\tcopy(tmp, this.a)\n\tfor i := 0; i < len(tmp); i++ {\n\t\tr := rand.Intn(len(tmp))\n\t\ttmp[i], tmp[r] = tmp[r], tmp[i]\n\t}\n\treturn tmp\n}", "func (this *Solution) Shuffle() []int {\ntmp:=make([]int,len(this.arr))\ncopy(tmp,this.arr)\nfor i:=0;i<len(tmp);i++{\n\tr:=rand.Intn(len(tmp))\n\ttmp[i],tmp[r] = tmp[r],tmp[i]\n}\nreturn tmp\n}", "func (d *Deck) Shuffle(seed int64) {\n\tif seed == UniqueShuffle {\n\t\tseed = time.Now().UnixNano()\n\t}\n\trand.Seed(seed)\n\tfor i := 0; i < 52; i++ {\n\t\tr := i + rand.Intn(52-i)\n\t\td.Cards[r], d.Cards[i] = d.Cards[i], d.Cards[r]\n\t}\n}", "func ShuffleJumps(s []jump) {\n\tfor i := range s {\n\t\tj := rand.Intn(i + 1)\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func (this *Solution) Shuffle() []int {\r\n n := len(this.raw)\r\n words := make([]int, n)\r\n copy(words, this.raw)\r\n for i:=n; i>1; i-- {\r\n seed := rand.Intn(i)\r\n words[i-1], words[seed] = words[seed], words[i-1]\r\n }\r\n return words\r\n}", "func ShuffleRandom(servers []types.DatabaseServer) []types.DatabaseServer {\n\trand.New(rand.NewSource(time.Now().UnixNano())).Shuffle(\n\t\tlen(servers), func(i, j int) {\n\t\t\tservers[i], servers[j] = servers[j], servers[i]\n\t\t})\n\treturn servers\n}", "func shuffle_array(arr []int) {\n rand.Shuffle(len(arr),\n func(i, j int) {\n arr[i], arr[j] = arr[j], arr[i] })\n}", "func (this *Solution) Shuffle() []int {\n\tresult := make([]int, this.size)\n\tcopy(result, this.nums)\n\tfor i := this.size - 1; i >= 0; i-- {\n\t\tj := rand.Intn(this.size)\n\t\tresult[i], result[j] = result[j], result[i]\n\t}\n\treturn result\n}", "func (f *Facts) Shuffle() []string {\n\tt := time.Now()\n\trand.Seed(int64(t.Nanosecond()))\n\n\tarr := f.behaviorsAccess\n\tfor i := len(arr) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i)\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn arr\n}", "func randomize(d time.Duration) time.Duration {\n\tmaxAdded := float64(d) / 4\n\tamount := rand.Float64() * maxAdded\n\n\treturn time.Duration(float64(d) + amount)\n}", "func (p *PCG64) Shuffle(n int, swap func(i, j int)) {\n\tif n < 0 {\n\t\tpanic(\"fastrand: invalid argument to Shuffle\")\n\t}\n\n\t// Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n\t// Shuffle really ought not be called with n that doesn't fit in 32 bits.\n\t// Not only will it take a very long time, but with 2³¹! possible permutations,\n\t// there's no way that any PRNG can have a big enough internal state to\n\t// generate even a minuscule percentage of the possible permutations.\n\t// Nevertheless, the right API signature accepts an int n, so handle it as best we can.\n\ti := n - 1\n\tfor ; i > 1<<31-1-1; i-- {\n\t\tj := int(p.Int63n(int64(i + 1)))\n\t\tswap(i, j)\n\t}\n\tfor ; i > 0; i-- {\n\t\tj := int(p.Int31n(int32(i + 1)))\n\t\tswap(i, j)\n\t}\n}", "func Shuffle(deck Deck) (shuffledDeck Deck) {\n\tshuffledDeck = deck\n\tlength := len(deck)\n\tfor i := 1; i < length; i++ {\n\t\trandom := rand.Intn(i + 1)\n\t\tif i != random {\n\t\t\tshuffledDeck[random], shuffledDeck[i] = shuffledDeck[i], shuffledDeck[random]\n\t\t}\n\t}\n\treturn\n}", "func (d *Dataset) Shuffle() (output Dataset) {\n\tdata := *(*d).Data\n\tfor i := range data {\n\t\tj := rand.Intn(i + 1)\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n\toutput.Data = &data\n\toutput.Size = (*d).Size\n\treturn\n}", "func ShuffleArray(array []int) {\n\tfor i := 0; i < len(array); i++ {\n\t\tk := rand.Int() % (i + 1)\n\t\ttemp := array[k]\n\t\tarray[k] = array[i]\n\t\tarray[i] = temp\n\t}\n}", "func (this *Solution) Shuffle() []int {\n\n\tl := len(this.current)\n\ttmp := make([]int, l)\n\tcopy(tmp, this.current)\n\tfor i:=range this.current{\n\t\tindex := i+rand.Int()%(l-i)\n\t\ttmp[i], tmp[index] = tmp[index], tmp[i]\n\t}\n\treturn tmp\n}", "func Shuffle(deck []Card) []Card {\n\tr := rand.New(rand.NewSource(time.Now().Unix()))\n\tshuffled := make([]Card, len(deck))\n\tj := 0\n\tfor _, i := range r.Perm(len(deck)) {\n\t\tshuffled[j] = deck[i]\n\t\tj++\n\t}\n\treturn shuffled\n}", "func Shuffle(cards []Card) []Card {\n\tfor i := range cards {\n\t\tj := rand.Intn(len(cards))\n\t\tcards[i], cards[j] = cards[j], cards[i]\n\t}\n\n\treturn cards\n}", "func shuffleNames(names []string) {\n\trand.Seed(time.Now().UnixNano())\n\trand.Shuffle(len(names), func(i, j int) { names[i], names[j] = names[j], names[i] })\n}", "func shuffleAds() {\n\tdest := make([]AdObject, len(Ads))\n\tperm := rand.Perm(len(Ads))\n\tfor i, v := range perm {\n\t\tdest[v] = Ads[i]\n\t}\n}", "func (shoe *Shoe) Shuffle() {\n\tc := shoe.Cards\n\trand.Seed(time.Now().UnixNano())\n\trand.Shuffle(\n\t\tlen(c),\n\t\tfunc(i, j int) {\n\t\t\tc[i], c[j] = c[j], c[i]\n\t\t})\n}", "func (s *Shuffle) Shuffle() []int {\n\tori := make([]int, len(s.ori))\n\tcopy(ori, s.ori)\n\trd := make([]int, len(ori))\n\tfor i := len(rd) - 1; i >= 0; i-- {\n\t\tpos := rand.Intn(i + 1)\n\t\trd[i] = ori[pos]\n\t\tori[pos], ori[i] = ori[i], ori[pos]\n\t}\n\treturn rd\n}", "func (this *SolutionShuffle) Shuffle() []int {\n\tres := make([]int, len(this.origin))\n\ttemp := append([]int{}, this.origin...)\n\tfor i := len(this.origin); i > 0; i-- {\n\t\t// gen random index\n\t\tidex := rand.Intn(i)\n\t\t// swap that index number with last index number\n\t\ttemp[len(temp)-1], temp[idex] = temp[idex], temp[len(temp)-1]\n\t\t// pop that number and add to array\n\t\tres[i-1] = temp[len(temp)-1]\n\t\ttemp = temp[:len(temp)-1]\n\t}\n\treturn res\n}", "func ArrayInt64Shuffle(arr []int64) []int64 {\n\tn := len(arr)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tj := IntRand(0, i+1)\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn arr\n}", "func randomize(it graph.Nodes, src rand.Source) graph.Nodes {\n\tnodes := graph.NodesOf(it)\n\tvar shuffle func(int, func(i, j int))\n\tif src == nil {\n\t\tshuffle = rand.Shuffle\n\t} else {\n\t\tshuffle = rand.New(src).Shuffle\n\t}\n\tshuffle(len(nodes), func(i, j int) {\n\t\tnodes[i], nodes[j] = nodes[j], nodes[i]\n\t})\n\treturn iterator.NewOrderedNodes(nodes)\n}", "func (this *Solution) Shuffle() []int {\n\tvar randIndex int\n\tlength := len(this.nums)\n\n\tfor i := 0; i < length; i++ {\n\t\trandIndex = rand.Intn(length)\n\t\tthis.nums[i], this.nums[randIndex] = this.nums[randIndex], this.nums[i]\n\t}\n\n\treturn this.nums\n}", "func (d *Deck) Shuffle() error {\n\tfor i := 0; i < d.size; i++ {\n\t\tr := rand.Intn(i + 1)\n\t\tif i != r {\n\t\t\td.Cards[r], d.Cards[i] = d.Cards[i], d.Cards[r]\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Solution) Shuffle() []int {\n\ttmp := make([]int, len(s.arr))\n\tcopy(tmp, s.arr)\n\tfor i := 0; i < len(s.arr); i++ {\n\t\tr := rand.Intn(len(s.arr))\n\t\ttmp[i], tmp[r] = tmp[r], tmp[i]\n\t}\n\n\treturn tmp\n}", "func (indis Individuals) shuffle(generator *rand.Rand) Individuals {\n\tvar shuffled = make(Individuals, len(indis))\n\tfor i, v := range generator.Perm(len(indis)) {\n\t\tshuffled[v] = indis[i]\n\t}\n\treturn shuffled\n}", "func (this *Solution) Shuffle() []int {\n\tarrLen := len(this.Arr)\n\tna := make([]int, arrLen, arrLen)\n\tcopy(na, this.Arr)\n\trand.Shuffle(arrLen, func(i, j int) {\n\t\tna[i], na[j] = na[j], na[i]\n\t})\n\treturn na\n}", "func (c *StoreCandidates) Shuffle() *StoreCandidates {\n\trand.Shuffle(len(c.Stores), func(i, j int) { c.Stores[i], c.Stores[j] = c.Stores[j], c.Stores[i] })\n\treturn c\n}", "func (this *Solution) Shuffle() []int {\n\tnums := make([]int, len(this.nums))\n\tcopy(nums, this.nums)\n\trand.Shuffle(len(nums), func(i int, j int) {\n\t\tnums[i], nums[j] = nums[j], nums[i]\n\t})\n\treturn nums\n}", "func (d deck) pseduoshuffle() {\n\tfor i := range d {\n\t\tnewPosition := rand.Intn(len(d) - 1) //pseudo random generator where we cannot specify a source\n\t\td[i], d[newPosition] = d[newPosition], d[i]\n\n\t}\n}", "func (sample *Sample) shuffleAlgorithm235() {\n\tsample.Well = Shuffle235(sample.Well, sample.WellSeen)\n}", "func Shuffle(sz []string) []string {\n\tif len(sz) <= 0 {\n\t\treturn nil\n\t}\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := len(sz) - 1; i > 0; i-- {\n\t\tj := r.Intn(i + 1)\n\t\ttmp := sz[i]\n\t\tsz[i] = sz[j]\n\t\tsz[j] = tmp\n\t}\n\treturn sz\n}", "func (this *Solution) Shuffle() []int {\n\tlength := len(this.cp)\n\tfor i := int32(length - 1); i >= 0; i-- {\n\t\tidx := rand.Int31n(i + 1)\n\t\tthis.cp[i], this.cp[idx] = this.cp[idx], this.cp[i]\n\t}\n\treturn this.cp\n}", "func (d *Dense) Shuffle(r *rand.Rand) {\n\tr.Shuffle(d.len, d.swap)\n}", "func Randomize(cfg *ModConfig, d2files d2file.D2Files) {\n\topts := getRandomOptions(cfg)\n\trand.Seed(opts.Seed)\n\n\tprops := getAllProps(opts, d2files)\n\n\ts := scrambler{\n\t\topts: opts,\n\t\td2files: d2files,\n\t\tprops: props,\n\t}\n\n\trandomizeUniqueProps(s)\n\trandomizeSetProps(s)\n\trandomizeSetItemsProps(s)\n\trandomizeRWProps(s)\n\t// writePropsToFile(props)\n}", "func RandomTime(t time.Time, r time.Duration) time.Time {\n\treturn t.Add(-time.Duration(float64(r) * rand.Float64()))\n}", "func ShuffleInts(a []int) {\n\tfor i := range a {\n\t\tj := rand.Intn(i + 1)\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n}", "func shuffleFunc(task *mapreduce.Task, key string) (reduceJob int) {\r\n\th := fnv.New32a()\r\n\th.Write([]byte(key))\r\n\treturn int(h.Sum32() % uint32(task.NumReduceJobs))\r\n}", "func (deck *Deck) Shuffle() {\n\tdeck.cards = make([]Card, len(fullDeck.cards))\n\tcopy(deck.cards, fullDeck.cards)\n\trand.Shuffle(len(deck.cards), func(i, j int) {\n\t\tdeck.cards[i], deck.cards[j] = deck.cards[j], deck.cards[i]\n\t})\n}", "func (d Deck) Shuffle() {\n\tvar numCards = len(d.cards)\n\tvar newCardsArray = make([]Card, numCards)\n\tvar perm = rand.Perm(numCards)\n\tfor i, j := range perm {\n\t\tnewCardsArray[j] = d.cards[i]\n\t}\n\td.cards = newCardsArray\n}", "func RandomShuffle(scope *Scope, value tf.Output, optional ...RandomShuffleAttr) (output 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: \"RandomShuffle\",\n\t\tInput: []tf.Input{\n\t\t\tvalue,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func shuffleCards(cards []*Card) []*Card {\n\tshuffled := make([]*Card, len(cards))\n\tcopy(shuffled, cards)\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tr.Shuffle(len(shuffled), func(i, j int) {\n\t\tshuffled[i], shuffled[j] = shuffled[j], shuffled[i]\n\t})\n\n\treturn shuffled\n}", "func rnd() float64 {\n\tss := *g_seed\n\tss += ss\n\tss ^= 1\n\tif int32(ss) < 0 {\n\t\tss ^= 0x88888eef\n\t}\n\t*g_seed = ss\n\treturn float64(*g_seed%95) / float64(95)\n}", "func rnd() float64 {\n\tss := *g_seed\n\tss += ss\n\tss ^= 1\n\tif int32(ss) < 0 {\n\t\tss ^= 0x88888eef\n\t}\n\t*g_seed = ss\n\treturn float64(*g_seed%95) / float64(95)\n}", "func Shuffle(r *rand.Rand, n int, swap func(i, j int)) {\n\tif n < 0 {\n\t\tpanic(\"invalid argument to Shuffle\")\n\t}\n\n\t// Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n\t// Shuffle really ought not be called with n that doesn't fit in 32 bits.\n\t// Not only will it take a very long time, but with 2³¹! possible permutations,\n\t// there's no way that any PRNG can have a big enough internal state to\n\t// generate even a minuscule percentage of the possible permutations.\n\t// Nevertheless, the right API signature accepts an int n, so handle it as best we can.\n\ti := n - 1\n\tfor ; i > 1<<31-1-1; i-- {\n\t\tj := int(r.Int63n(int64(i + 1)))\n\t\tswap(i, j)\n\t}\n\tfor ; i > 0; i-- {\n\t\tj := int(Int31n(r, int32(i+1)))\n\t\tswap(i, j)\n\t}\n}", "func (this *Solution) Shuffle() []int {\n\tvar temp []int\n\tresult := []int{}\n\tif len(this.changed) == 0 {\n\t\ttemp = this.initial\n\t} else {\n\t\ttemp = this.changed\n\t}\n\tfor i, d := range temp {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, d)\n\t}\n\tresult = append(result, temp[0])\n\tthis.changed = result\n\treturn result\n}", "func Bubblesort(workload int64) {\n\n randomValues := make([]int64, workload)\n\n\n var i int64\n\n for i=0; i<workload; i++{\n randomValues[i] = rand.Int63n(workload)\n }\n\n workload = workload - 1\n\n swapped := true;\n\n rand.Seed(time.Now().UnixNano())\n timestamp := time.Now()\n\n\n for swapped==true {\n swapped = false\n\n for i=0; i<workload; i++{\n prevValue := randomValues[i]\n succValue := randomValues[i+1]\n\n if prevValue > succValue{\n temp := randomValues[i+1]\n randomValues[i+1] = randomValues[i]\n randomValues[i] = temp\n swapped = true\n }\n }\n }\n\n timestampCompleted := time.Now()\n\n executionTime := timestampCompleted.Sub(timestamp)\n\n executionTime_ms := float64(executionTime/time.Microsecond)/1000\n\n fmt.Println(executionTime_ms) \n}", "func Shuffle235(well []string, count int64) []string {\n\tvar choice int64\n\tvar old string\n\n\tfor i := count - 1; i > 1; i-- {\n\t\tchoice = rand.Int63n(i)\n\t\told = well[i]\n\t\twell[i] = well[choice]\n\t\twell[choice] = old\n\t}\n\treturn well\n}", "func (area *MineArea) shuffleArea(rate int) {\n\t// generate the bombs\n\tfor i := 0; i < 100; i++ {\n\t\tfor j := 0; j < 100; j++ {\n\t\t\tif rand.Intn(100)+1 <= rate {\n\t\t\t\tarea.GetBlock2(i, j).Value = 9\n\t\t\t}\n\t\t}\n\t}\n\t// generate numbers\n\tfor i := 0; i < 100; i++ {\n\t\tfor j := 0; j < 100; j++ { // x : j, y : i\n\t\t\tif area.GetBlock2(j, i).Value == 9 {\n\t\t\t\tcontinue\n\t\t\t} else if i == 0 || i == 99 || j == 0 || j == 99 {\n\t\t\t\tarea.GetBlock2(j, i).Value = 11\n\t\t\t} else {\n\t\t\t\tarea.GetBlock2(j, i).Value = area.calcBombs(j, i)\n\t\t\t}\n\t\t}\n\t}\n}", "func BenchmarkQuickSortRand128(b *testing.B) {\n\tl := genListRand(128)\n\tbenchmarkSort(b, QuickSort, l)\n}", "func (br *BlackRock) Shuffle(m uint64) uint64 {\n\tvar c uint64\n\tc = br.encrypt(br.rounds, br.a, br.b, m, br.seed)\n\tfor {\n\t\tif c >= br.inputSize {\n\t\t\tc = br.encrypt(br.rounds, br.a, br.b, c, br.seed)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn c\n}", "func (br *BlackRock) Unshuffle(m uint64) uint64 {\n\tvar c uint64\n\n\tc = br.unencrypt(br.rounds, br.a, br.b, m, br.seed)\n\tfor {\n\t\tif c >= br.inputSize {\n\t\t\tc = br.unencrypt(br.rounds, br.a, br.b, c, br.seed)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn c\n}", "func randomize(s []Resource) {\n\tvar low, high int\n\tfor low = 0; low < len(s)-1; low++ {\n\t\tfor high = low + 1; high < len(s) && s[low].Name == s[high].Name; high++ {\n\t\t}\n\n\t\tshuffle(s[low:high])\n\t\tlow = high\n\t}\n}", "func (stab *adaptiveStabilize) rand() time.Duration {\n\tr := rand.Float64()\n\td := time.Duration((r * float64(stab.max-stab.min)) + float64(stab.min))\n\n\t// check if adaptive stabilize is enabled\n\tif stab.min < stab.threshold {\n\t\tif stab.c > stab.stayCount {\n\t\t\tstab.step()\n\t\t} else {\n\t\t\tstab.c++\n\t\t}\n\t}\n\n\treturn d\n}", "func Shuffler(d *Deck) {\n\tneworder := make([]Card, len(d.Cards))\n\trand.Seed(int64(time.Now().Nanosecond()))\n\tm := make(map[int]bool)\n\toid := 0\n\tfor {\n\t\tid := rand.Intn(len(d.Cards))\n\t\tif _, ok := m[id]; !ok {\n\t\t\tm[id] = true\n\t\t\tneworder[oid] = d.Cards[id]\n\t\t\toid++\n\t\t}\n\t\tif len(m) == len(d.Cards) {\n\t\t\tbreak\n\t\t}\n\t}\n\td.Cards = neworder\n}", "func (c combinatorics) RandomTime(values []time.Time) time.Time {\n\tif len(values) == 0 {\n\t\treturn time.Time{}\n\t}\n\tif len(values) == 1 {\n\t\treturn values[0]\n\t}\n\treturn values[RandomProvider().Intn(len(values))]\n}", "func ArrayIntShuffle(arr []int) []int {\n\tn := len(arr)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tj := IntRand(0, i+1)\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn arr\n}", "func (s *SliceInt) Shuffle() *SliceInt {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tfor i := len(s.data) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\ts.data[i], s.data[j] = s.data[j], s.data[i]\n\t}\n\treturn s\n}", "func (this *Solution) Shuffle() []int {\n\tshuffled := make([]int, len(this.NumOrigin))\n\tperm := this.random.Perm(len(this.NumOrigin))\n\tfor k, v := range perm {\n\t\tshuffled[k] = this.NumOrigin[v]\n\t}\n\n\treturn shuffled\n}", "func (d *Deck) Shuffle() {\n\n\tShuffleCards(d.Cards)\n}" ]
[ "0.6643019", "0.6610405", "0.656916", "0.656916", "0.6559215", "0.6543622", "0.65322894", "0.6528126", "0.65013474", "0.64964604", "0.6465577", "0.64433384", "0.6441934", "0.63497853", "0.63177043", "0.63148683", "0.62923735", "0.62625074", "0.6247741", "0.6245899", "0.6233942", "0.61720145", "0.61592317", "0.6155722", "0.6130526", "0.61209106", "0.6118826", "0.6115426", "0.61129206", "0.6078583", "0.60592645", "0.602945", "0.5930115", "0.5882853", "0.5826762", "0.5820796", "0.5813801", "0.58017766", "0.580093", "0.5756285", "0.57399106", "0.57118565", "0.5704611", "0.5700241", "0.5697032", "0.5674853", "0.5674335", "0.56676173", "0.5661948", "0.5649094", "0.56455356", "0.5644496", "0.5611374", "0.5597374", "0.5585559", "0.5575309", "0.5571993", "0.55660504", "0.5561327", "0.5553216", "0.5548002", "0.5524661", "0.55221784", "0.55044454", "0.5499464", "0.54982626", "0.5490985", "0.54780453", "0.5470247", "0.5455228", "0.54464495", "0.54192805", "0.5411671", "0.54012585", "0.53986055", "0.5393622", "0.5348995", "0.5347347", "0.5343946", "0.5262116", "0.52561355", "0.52552557", "0.5245928", "0.5245928", "0.5240566", "0.5235735", "0.5233561", "0.52326417", "0.52147645", "0.52122563", "0.5199061", "0.5182332", "0.5181502", "0.515032", "0.51466465", "0.51227146", "0.51091653", "0.50950396", "0.50893456", "0.50843495" ]
0.70752513
0
Read only methods WindowDeep is a hacky way to access a window in deep. It returns (window glfw.Window) which is an unexported member inside a (pixelgl.Window). Read only argument game ignores the pass lock by value warning.
func (g game) WindowDeep() (baseWindow *glfw.Window) { return *(**glfw.Window)(unsafe.Pointer(reflect.Indirect(reflect.ValueOf(g.window)).FieldByName("window").UnsafeAddr())) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ref *UIElement) Window() *UIElement {\n\tret, _ := ref.UIElementAttr(WindowAttribute)\n\treturn ret\n}", "func (s *Scroll) Window() sparta.Window {\n\treturn s.win\n}", "func (l *List) Window() sparta.Window {\n\treturn l.win\n}", "func (s *Session) Window(name string) (*Window, error) {\n\tws, err := s.Windows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, w := range ws {\n\t\tif w.Name == name {\n\t\t\treturn w, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(`window \"%s\" not found in session \"%s\"`, name, s.Name)\n}", "func (g *Graph) Window(w window.Window) {\n\tg.window = w\n}", "func (r *ringBufferRateLimiter) Window() time.Duration {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\treturn r.window\n}", "func Window(title string) *WindowWidget {\n\treturn &WindowWidget{\n\t\ttitle: title,\n\t}\n}", "func (w *windowImpl) WinTex() oswin.Texture {\n\treturn w.winTex\n}", "func (sc *slidingCounter) getCurrentWindow() *window {\n\tnow := time.Now().Unix()\n\n\tif w, found := sc.windows[now]; found {\n\t\treturn w\n\t}\n\n\tresult := &window{}\n\tsc.windows[now] = result\n\treturn result\n}", "func (o *os) GetBorderlessWindow() gdnative.Bool {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetBorderlessWindow()\")\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(\"_OS\", \"get_borderless_window\")\n\n\t// Call the parent method.\n\t// bool\n\tretPtr := gdnative.NewEmptyBool()\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.NewBoolFromPointer(retPtr)\n\treturn ret\n}", "func (t *Tracker) Window() time.Duration {\n\t// acquire mutex\n\tt.mutex.RLock()\n\tdefer t.mutex.RUnlock()\n\n\treturn t.timeout - time.Since(t.last)\n}", "func (win *Window) GetUserPointer() unsafe.Pointer {\n\treturn unsafe.Pointer(C.glfwGetWindowUserPointer(win.c()))\n}", "func (o ConnectedRegistryOutput) SyncWindow() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectedRegistry) pulumi.StringPtrOutput { return v.SyncWindow }).(pulumi.StringPtrOutput)\n}", "func PropValWindow(reply *xproto.GetPropertyReply,\n\terr error) (xproto.Window, error) {\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif reply.Format != 32 {\n\t\treturn 0, fmt.Errorf(\"PropValId: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\treturn xproto.Window(xgb.Get32(reply.Value)), nil\n}", "func (w *WidgetImplement) FindWindow() IWindow {\n\tparent := w.Parent()\n\tif parent == nil {\n\t\tpanic(\"Widget:internal error (could not find parent window)\")\n\t}\n\treturn parent.FindWindow()\n}", "func (s settings) WindowSettings() interfaces.WindowSettings {\n\treturn s.windowSettings\n}", "func IsWin() bool { return false }", "func (view *View) WindowOpen() *bool {\n\treturn &view.model.windowOpen\n}", "func getWindowLongPtr(hwnd _HWND, what uintptr) uintptr {\n\tr1, _, _ := _getWindowLongPtr.Call(\n\t\tuintptr(hwnd),\n\t\twhat)\n\treturn r1\n}", "func SingleWindow() *WindowWidget {\n\tsize := Context.platform.DisplaySize()\n\ttitle := fmt.Sprintf(\"SingleWindow_%d\", Context.GetWidgetIndex())\n\n\treturn Window(title).\n\t\tFlags(\n\t\t\timgui.WindowFlagsNoTitleBar|\n\t\t\t\timgui.WindowFlagsNoCollapse|\n\t\t\t\timgui.WindowFlagsNoScrollbar|\n\t\t\t\timgui.WindowFlagsNoMove|\n\t\t\t\timgui.WindowFlagsNoResize).\n\t\tSize(size[0], size[1])\n}", "func GetWindowPadding() (x, y float32) {\n\tvec2 := imgui.CurrentStyle().WindowPadding()\n\treturn vec2.X, vec2.Y\n}", "func (w *WebGLShadowMap) JSObject() *js.Object { return w.p }", "func GetChromeProfileWindow(ctx context.Context, tconn *chrome.TestConn, condition func(uiauto.NodeInfo) bool) (*nodewith.Finder, error) {\n\tprofileWindow := nodewith.NameContaining(\"Google Chrome\").Role(role.Window).HasClass(\"BrowserRootView\")\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\n\tvar result *nodewith.Finder\n\tif err := testing.Poll(ctx, func(ctx context.Context) error {\n\t\tprofileInfos, err := ui.NodesInfo(ctx, profileWindow)\n\t\tif err != nil {\n\t\t\treturn testing.PollBreak(errors.Wrapf(err, \"failed to get info for %v\", profileWindow.Pretty()))\n\t\t}\n\t\tfor i := range profileInfos {\n\t\t\tif condition(profileInfos[i]) {\n\t\t\t\tresult = profileWindow.Name(profileInfos[i].Name)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn errors.Errorf(\"failed to find the Chrome window matching the condition: %v windows were checked\", len(profileInfos))\n\t}, &testing.PollOptions{Timeout: DefaultUITimeout}); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to find the Chrome window matching the condition\")\n\t}\n\n\treturn result, nil\n}", "func newWindowFromNative(obj unsafe.Pointer) interface{} {\n\tw := &Window{}\n\tw.object = C.to_GtkWindow(obj)\n\n\tif gobject.IsObjectFloating(w) {\n\t\tgobject.RefSink(w)\n\t} else {\n\t\tgobject.Ref(w)\n\t}\n\tw.Bin = NewBin(obj)\n\twindowFinalizer(w)\n\n\treturn w\n}", "func (ref *UIElement) Windows() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(WindowsAttribute)\n}", "func (w *WarpState) WindowSize() warp.Size {\n\treturn w.windowSize\n}", "func (window Window) OuterHeight() int {\n\treturn window.Get(\"outerHeight\").Int()\n}", "func (win *Window) GetMonitor() *Monitor {\n\treturn (*Monitor)(C.glfwGetWindowMonitor(win.c()))\n}", "func (win *Window) GetMonitor() *Monitor {\n\treturn (*Monitor)(C.glfwGetWindowMonitor(win.c()))\n}", "func List() (ret []*Window) {\n\tfor _, v := range winMap {\n\t\tret = append(ret, v)\n\t}\n\treturn\n}", "func Window(append ...bool) vecty.Markup {\n\treturn AddClass(window, append...)\n}", "func getGlobalObject() Uint32_t {\n\tif Jerry_value_is_null(globalObj) {\n\t\tglobalObj = Jerry_get_global_object()\n\t}\n\treturn globalObj\n}", "func (o *os) GetWindowSafeArea() gdnative.Rect2 {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetWindowSafeArea()\")\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(\"_OS\", \"get_window_safe_area\")\n\n\t// Call the parent method.\n\t// Rect2\n\tretPtr := gdnative.NewEmptyRect2()\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.NewRect2FromPointer(retPtr)\n\treturn ret\n}", "func (this *Renderer) CreateWindow() (*Window, error) {\n\tw := &Window{\n\t\tourRenderer: this,\n\t\tinputHelper: private.NewInputHelper(),\n\t\tendLastFrame: time.Now(),\n\t}\n\n\t// Construct the scene renderer and resolve the scenegraph, including\n\t// delivery of input events. The result is a list of DrawableNode.\n\tw.sceneRenderer = private.SceneRenderer{\n\t\tWindow: w,\n\t\tInputHelper: &w.inputHelper,\n\t}\n\tvar err error\n\tw.window, w.sdlRenderer, err = sdl.CreateWindowAndRenderer(800, 600, sdl.WINDOW_SHOWN|sdl.WINDOW_RESIZABLE)\n\t// ### a 'clear color' on the Window might make sense\n\tw.sdlRenderer.SetDrawColor(0, 0, 0, 0)\n\tw.id, err = w.window.GetID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tthis.windows[w.id] = w\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}", "func (ref *UIElement) MainWindow() *UIElement {\n\tret, _ := ref.UIElementAttr(MainWindowAttribute)\n\treturn ret\n}", "func Window(windowType WindowType, input VectorComplex) VectorComplex {\n\tswitch windowType {\n\tcase WindowTypeHann:\n\t\treturn Hann(input)\n\tcase WindowTypeHamming:\n\t\treturn Hamming(input)\n\tcase WindowTypeNuttal:\n\t\treturn Nuttal(input)\n\t}\n\treturn nil\n}", "func (app *appImpl) setSysWindow(opts *oswin.NewWindowOptions, winPtr uintptr) error {\n\tapp.mu.Lock()\n\tdefer app.mu.Unlock()\n\n\tvar sf vk.Surface\n\t// we have to remake the surface, system, and drawer every time someone reopens the window\n\t// because the operating system changes the underlying window\n\tlog.Println(\"in NewWindow\", app.gpu.Instance, winPtr, &sf)\n\tret := vk.CreateWindowSurface(app.gpu.Instance, winPtr, nil, &sf)\n\tif err := vk.Error(ret); err != nil {\n\t\tlog.Println(\"oswin/driver/mobile new window: vulkan error:\", err)\n\t\treturn err\n\t}\n\tapp.Surface = vgpu.NewSurface(app.gpu, sf)\n\n\tlog.Printf(\"format: %s\\n\", app.Surface.Format.String())\n\n\tapp.System = app.gpu.NewGraphicsSystem(app.name, &app.Surface.Device)\n\tapp.System.ConfigRender(&app.Surface.Format, vgpu.UndefType)\n\tapp.Surface.SetRender(&app.System.Render)\n\t// app.window.System.Mem.Vars.NDescs = vgpu.MaxTexturesPerSet\n\tapp.System.Config()\n\n\tapp.Draw = vdraw.Drawer{\n\t\tSys: *app.System,\n\t\tYIsDown: true,\n\t}\n\t// app.window.Draw.ConfigSys()\n\tapp.Draw.ConfigSurface(app.Surface, vgpu.MaxTexturesPerSet)\n\n\tapp.winptr = winPtr\n\tlog.Println(\"set window pointer to\", app.winptr)\n\tlog.Println(\"total number of windows:\", len(app.windows))\n\n\treturn nil\n}", "func mustView(view C.CFTypeRef) *window {\n\tw, ok := lookupView(view)\n\tif !ok {\n\t\tpanic(\"no window view view\")\n\t}\n\treturn w\n}", "func (o LaunchProfileStreamingSessionStorageRootPtrOutput) Windows() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *LaunchProfileStreamingSessionStorageRoot) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Windows\n\t}).(pulumi.StringPtrOutput)\n}", "func updateWindow(ctx context.Context, a api.FullNode, w CidWindow, t int, ch chan CidWindow) (CidWindow, error) {\n\thead, err := a.ChainHead(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twindow := appendCIDsToWindow(w, head.Cids(), t)\n\tch <- window\n\treturn window, nil\n}", "func FindWindow(win string) (ret uintptr, err error) {\n\tlpszWindow := syscall.StringToUTF16Ptr(win)\n\n\tr0, _, e1 := syscall.Syscall(findWindowW.Addr(), 2, uintptr(unsafe.Pointer(nil)), uintptr(unsafe.Pointer(lpszWindow)), 0)\n\tret = uintptr(r0)\n\tif ret == 0 {\n\t\tif e1 != 0 {\n\t\t\terr = error(e1)\n\t\t} else {\n\t\t\terr = syscall.EINVAL\n\t\t}\n\t}\n\treturn\n}", "func (w *Window) Clone() *Window {\n\tif w == nil {\n\t\treturn nil\n\t}\n\tother := *w\n\tother.Name = w.Name.Clone()\n\tother.Definition = w.Definition.Clone()\n\treturn &other\n}", "func (self *SinglePad) Game() *Game{\n return &Game{self.Object.Get(\"game\")}\n}", "func InternalWinSwarmingBot(num int, opsys, setupScriptPath, startupScriptPath, chromebotScript string) *gce.Instance {\n\tvm := Swarming20171114(fmt.Sprintf(\"skia-i-gce-%03d\", num), gce.SERVICE_ACCOUNT_CHROME_SWARMING)\n\treturn AddWinConfigs(vm, opsys, setupScriptPath, startupScriptPath, chromebotScript)\n}", "func newGLWindow(opts *oswin.NewWindowOptions, sc *oswin.Screen) (*glfw.Window, error) {\n\t_, _, tool, fullscreen := oswin.WindowFlagsToBool(opts.Flags)\n\tglfw.DefaultWindowHints()\n\tglfw.WindowHint(glfw.Resizable, glfw.True)\n\tglfw.WindowHint(glfw.Visible, glfw.False) // needed to position\n\tglfw.WindowHint(glfw.Focused, glfw.True)\n\t// glfw.WindowHint(glfw.ScaleToMonitor, glfw.True)\n\tglfw.WindowHint(glfw.ContextVersionMajor, glosGlMajor)\n\tglfw.WindowHint(glfw.ContextVersionMinor, glosGlMinor)\n\tglfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)\n\tglfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)\n\tglfw.WindowHint(glfw.Samples, 0) // don't do multisampling for main window -- only in sub-render\n\tif glosDebug {\n\t\tglfw.WindowHint(glfw.OpenGLDebugContext, glfw.True)\n\t}\n\n\t// todo: glfw.Samples -- multisampling\n\tif fullscreen {\n\t\tglfw.WindowHint(glfw.Maximized, glfw.True)\n\t}\n\tif tool {\n\t\tglfw.WindowHint(glfw.Decorated, glfw.False)\n\t} else {\n\t\tglfw.WindowHint(glfw.Decorated, glfw.True)\n\t}\n\t// todo: glfw.Floating for always-on-top -- could set for modal\n\tsz := opts.Size // note: this is already in standard window size units!\n\twin, err := glfw.CreateWindow(sz.X, sz.Y, opts.GetTitle(), nil, theApp.shareWin)\n\tif err != nil {\n\t\treturn win, err\n\t}\n\twin.SetPos(opts.Pos.X, opts.Pos.Y)\n\treturn win, err\n}", "func (w *Window) Screen() (im wde.Image) {\n\tif w.closed {\n\t\treturn\n\t}\n\tim = &Image{w.buffer}\n\treturn im\n}", "func NewWindow(info Info, currentState int) *Windows {\n\tacc := Windows{}\n\tacc.Accessory = New(info, TypeWindow)\n\tacc.Window = service.NewWindow()\n\tacc.Window.CurrentPosition.SetValue(currentState)\n\tacc.AddService(acc.Window.Service)\n\n\treturn &acc\n}", "func (o LaunchProfileStreamingSessionStorageRootOutput) Windows() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LaunchProfileStreamingSessionStorageRoot) *string { return v.Windows }).(pulumi.StringPtrOutput)\n}", "func (s *State) WindowBounds() image.Rectangle {\n\treturn s.windowSize.Sub(s.bounds.Min)\n}", "func (w *windowImpl) Handle() any {\n\treturn w.app.winptr\n}", "func (win *Window) GetUserPointer() *interface{} {\n\tcPointer := C.glfwGetWindowUserPointer(win.c())\n\tif unsafe.Pointer(cPointer) != C.NULL {\n\t\treturn (*interface{})(cPointer)\n\t}\n\treturn nil\n}", "func (w *Window) Base() app.Window {\n\treturn w\n}", "func (window Window) InnerWidth() int {\n\treturn window.Get(\"innerWidth\").Int()\n}", "func (w *windowImpl) Handle() interface{} {\n\treturn w.glw\n}", "func (w *windowImpl) getScreenOvlp() *oswin.Screen {\n\treturn w.app.screens[0]\n}", "func NewWindow(\n\twidth, height int,\n\ttitle string,\n\tvisible bool,\n) (*Window, error) {\n\tif width < 0 {\n\t\treturn nil, errors.New(\"Width must not be < 0\")\n\t}\n\tif height < 0 {\n\t\treturn nil, errors.New(\"Height must not be < 0\")\n\t}\n\terr := ensGlfwInit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar v = 0\n\tif visible {\n\t\tv = 1\n\t}\n\tglfwWin := C.createWin(\n\t\tC.int(width),\n\t\tC.int(height),\n\t\tC.CString(title),\n\t\tC.int(v),\n\t)\n\tif glfwWin == nil {\n\t\tTerminate()\n\t\treturn nil, errors.New(\"Failed to create window\")\n\t}\n\terrno := int(C.initGlew(glfwWin))\n\tif errno != 1 {\n\t\treturn nil, errors.New(\"Failed to init GLEW\")\n\t}\n\tC.initWin(glfwWin, C.int(width), C.int(height))\n\ttex := newTex(width, height)\n\ttexId := C.createTex(\n\t\tglfwWin,\n\t\tunsafe.Pointer(&tex),\n\t\tC.int(width),\n\t\tC.int(height),\n\t)\n\tC.glfwSetInputMode(glfwWin, C.GLFW_CURSOR, C.GLFW_CURSOR_DISABLED)\n\treturn &Window{width, height, glfwWin, texId, tex}, nil\n}", "func init() {\n\tmapType(\"wxNonOwnedWindow\", reflect.TypeOf(nonOwnedWindow{}))\n}", "func WindowList(URL *url.URL) ([]Window, error) {\n\tvar list []Window\n\tif err := request(URL, http.MethodGet, nil, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}", "func NewWindowsKioskProfile()(*WindowsKioskProfile) {\n m := &WindowsKioskProfile{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (self *Graphics) Game() *Game{\n return &Game{self.Object.Get(\"game\")}\n}", "func (self *TileSprite) Game() *Game{\n return &Game{self.Object.Get(\"game\")}\n}", "func (o *os) GetWindowSize() gdnative.Vector2 {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetWindowSize()\")\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(\"_OS\", \"get_window_size\")\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 (o *os) GetWindowPerPixelTransparencyEnabled() gdnative.Bool {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetWindowPerPixelTransparencyEnabled()\")\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(\"_OS\", \"get_window_per_pixel_transparency_enabled\")\n\n\t// Call the parent method.\n\t// bool\n\tretPtr := gdnative.NewEmptyBool()\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.NewBoolFromPointer(retPtr)\n\treturn ret\n}", "func NewWindow() *Window {\n\tp := new(Window)\n\tp.Self = p\n\tp.Init()\n\treturn p\n}", "func newGLWindow(opts *oswin.NewWindowOptions) (*glfw.Window, error) {\n\t_, _, tool, fullscreen := oswin.WindowFlagsToBool(opts.Flags)\n\tglfw.DefaultWindowHints()\n\tglfw.WindowHint(glfw.Resizable, glfw.True)\n\tglfw.WindowHint(glfw.Visible, glfw.True) // needed to position\n\tglfw.WindowHint(glfw.Focused, glfw.True)\n\tglfw.WindowHint(glfw.ContextVersionMajor, 4) // 4.1 is max supported on macos\n\tglfw.WindowHint(glfw.ContextVersionMinor, 1)\n\tglfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)\n\tglfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)\n\tglfw.WindowHint(glfw.Samples, 0) // don't do multisampling for main window -- only in sub-render\n\tif glosDebug {\n\t\tglfw.WindowHint(glfw.OpenGLDebugContext, glfw.True)\n\t}\n\n\t// todo: glfw.Samples -- multisampling\n\tif fullscreen {\n\t\tglfw.WindowHint(glfw.Maximized, glfw.True)\n\t}\n\tif tool {\n\t\tglfw.WindowHint(glfw.Decorated, glfw.False)\n\t} else {\n\t\tglfw.WindowHint(glfw.Decorated, glfw.True)\n\t}\n\t// todo: glfw.Floating for always-on-top -- could set for modal\n\twin, err := glfw.CreateWindow(opts.Size.X, opts.Size.Y, opts.GetTitle(), nil, nil)\n\tif err != nil {\n\t\treturn win, err\n\t}\n\twin.SetPos(opts.Pos.X, opts.Pos.Y)\n\treturn win, err\n}", "func (a *AbstractSessionChannelHandler) OnWindow(\n\t_ uint64,\n\t_ uint32,\n\t_ uint32,\n\t_ uint32,\n\t_ uint32,\n) error {\n\treturn fmt.Errorf(\"not supported\")\n}", "func (w *GlfwWindow) FullScreen() bool {\n\n\treturn w.fullscreen\n}", "func (p *Page) MustGetWindow() *proto.BrowserBounds {\n\tbounds, err := p.GetWindow()\n\tp.e(err)\n\treturn bounds\n}", "func (window Window) OuterWidth() int {\n\treturn window.Get(\"outerWidth\").Int()\n}", "func (game Game) WinRow() [3]int {\n\treturn game.winRow\n}", "func (c *Counter) LoadW() int64 {\n\treturn c.window.Load()\n}", "func (v *WindowGroup) native() *C.GtkWindowGroup {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\tp := unsafe.Pointer(v.GObject)\n\treturn C.toGtkWindowGroup(p)\n}", "func NewWindow(width, height int, profileDir string, styleSheet string, args ...string) *Window {\n\n\tels := Elements{slice: []*Element{}}\n\n\tw := Window{\n\t\tWidth: width,\n\t\tHeight: height,\n\t\tStyle: StyleSheet{URL: styleSheet},\n\t\tui: nil,\n\t\tArgs: args,\n\t\tProfileDir: profileDir,\n\t\tElements: &els,\n\t\tBindings: []Binding{},\n\t}\n\treturn &w\n}", "func WindowSize() (w, h int) {\n\treturn windowSize()\n}", "func NewWindow(renderer interfaces.Renderer) *Window {\n\treturn &Window{\n\t\trenderer: renderer,\n\t}\n}", "func (w *Window) Width() int {\n\treturn int(C.ANativeWindow_getWidth(w.cptr()))\n}", "func takeWindowScreenshot(ctx context.Context, tconn *chrome.TestConn) error {\n\tui := uiauto.New(tconn)\n\n\tif _, err := filesapp.Launch(ctx, tconn); err != nil {\n\t\treturn errors.Wrap(err, \"failed to launch the app\")\n\t}\n\n\tactiveWindow, err := ash.GetActiveWindow(ctx, tconn)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to find active window\")\n\t}\n\tcenterPoint := activeWindow.BoundsInRoot.CenterPoint()\n\n\tif err = uiauto.Combine(\"take window screenshot\",\n\t\tui.LeftClick(nodewith.Role(role.ToggleButton).Name(\"Screenshot\")),\n\t\tui.LeftClick(nodewith.Role(role.ToggleButton).Name(\"Take window screenshot\")),\n\t\tmouse.Move(tconn, centerPoint, time.Second), // Different names for clamshell/tablet mode.\n\t\tui.LeftClick(nodewith.Role(role.Window).First()), // Click on the center of root window to take the screenshot.\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to take window screenshot\")\n\t}\n\n\treturn nil\n}", "func TestAssignWindow(t *testing.T) {\n\ttests := []struct {\n\t\tfn *window.Fn\n\t\tin typex.EventTime\n\t\tout []typex.Window\n\t}{\n\t\t{\n\t\t\twindow.NewGlobalWindows(),\n\t\t\tmtime.ZeroTimestamp,\n\t\t\twindow.SingleGlobalWindow,\n\t\t},\n\t\t{\n\t\t\twindow.NewGlobalWindows(),\n\t\t\tmtime.MinTimestamp,\n\t\t\twindow.SingleGlobalWindow,\n\t\t},\n\t\t{\n\t\t\twindow.NewGlobalWindows(),\n\t\t\tmtime.Now(),\n\t\t\twindow.SingleGlobalWindow,\n\t\t},\n\t\t{\n\t\t\twindow.NewGlobalWindows(),\n\t\t\tmtime.MaxTimestamp, // TODO(herohde) 4/18/2018: is this even valid?\n\t\t\twindow.SingleGlobalWindow,\n\t\t},\n\t\t{\n\t\t\twindow.NewFixedWindows(time.Minute),\n\t\t\t0,\n\t\t\t[]typex.Window{window.IntervalWindow{Start: 0, End: 60000}},\n\t\t},\n\t\t{\n\t\t\twindow.NewFixedWindows(time.Minute),\n\t\t\t-123,\n\t\t\t[]typex.Window{window.IntervalWindow{Start: -60000, End: 0}},\n\t\t},\n\t\t{\n\t\t\twindow.NewFixedWindows(time.Minute),\n\t\t\t59999,\n\t\t\t[]typex.Window{window.IntervalWindow{Start: 0, End: 60000}},\n\t\t},\n\t\t{\n\t\t\twindow.NewFixedWindows(time.Minute),\n\t\t\t60000,\n\t\t\t[]typex.Window{window.IntervalWindow{Start: 60000, End: 120000}},\n\t\t},\n\t\t{\n\t\t\twindow.NewFixedWindows(2 * time.Minute),\n\t\t\t60000,\n\t\t\t[]typex.Window{window.IntervalWindow{Start: 0, End: 120000}},\n\t\t},\n\t\t{\n\t\t\twindow.NewSlidingWindows(time.Minute, 3*time.Minute),\n\t\t\t0,\n\t\t\t[]typex.Window{\n\t\t\t\twindow.IntervalWindow{Start: 0, End: 180000},\n\t\t\t\twindow.IntervalWindow{Start: -60000, End: 120000},\n\t\t\t\twindow.IntervalWindow{Start: -120000, End: 60000},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\twindow.NewSlidingWindows(time.Minute, 3*time.Minute),\n\t\t\t123,\n\t\t\t[]typex.Window{\n\t\t\t\twindow.IntervalWindow{Start: 0, End: 180000},\n\t\t\t\twindow.IntervalWindow{Start: -60000, End: 120000},\n\t\t\t\twindow.IntervalWindow{Start: -120000, End: 60000},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\twindow.NewSlidingWindows(time.Minute, 3*time.Minute),\n\t\t\t60000,\n\t\t\t[]typex.Window{\n\t\t\t\twindow.IntervalWindow{Start: 60000, End: 240000},\n\t\t\t\twindow.IntervalWindow{Start: 0, End: 180000},\n\t\t\t\twindow.IntervalWindow{Start: -60000, End: 120000},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tout := assignWindows(test.fn, test.in)\n\t\tif !window.IsEqualList(out, test.out) {\n\t\t\tt.Errorf(\"assignWindows(%v, %v) = %v, want %v\", test.fn, test.in, out, test.out)\n\t\t}\n\t}\n}", "func (o *os) GetRealWindowSize() gdnative.Vector2 {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetRealWindowSize()\")\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(\"_OS\", \"get_real_window_size\")\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 (p *ControlPanel) RunWindow(opts *widget.RunWindowOptions) error {\n\tvar (\n\t\tnwo *screen.NewWindowOptions\n\t\tt *theme.Theme\n\t)\n\tif opts != nil {\n\t\tnwo = &opts.NewWindowOptions\n\t\tt = &opts.Theme\n\t}\n\tvar err error\n\tp.w, err = p.s.NewWindow(nwo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer p.w.Release()\n\n\tpaintPending := false\n\n\tgef := gesture.EventFilter{EventDeque: p.w}\n\tfor {\n\t\te := p.w.NextEvent()\n\n\t\tif e = gef.Filter(e); e == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch e := e.(type) {\n\t\tcase lifecycle.Event:\n\t\t\tp.root.OnLifecycleEvent(e)\n\t\t\tif e.To == lifecycle.StageDead {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase gesture.Event, mouse.Event:\n\t\t\tp.root.OnInputEvent(e, image.Point{})\n\n\t\tcase paint.Event:\n\t\t\tctx := &node.PaintContext{\n\t\t\t\tTheme: t,\n\t\t\t\tScreen: p.s,\n\t\t\t\tDrawer: p.w,\n\t\t\t\tSrc2Dst: f64.Aff3{\n\t\t\t\t\t1, 0, 0,\n\t\t\t\t\t0, 1, 0,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif err := p.root.Paint(ctx, image.Point{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.w.Publish()\n\t\t\tpaintPending = false\n\n\t\tcase size.Event:\n\t\t\tif dpi := float64(e.PixelsPerPt) * unit.PointsPerInch; dpi != t.GetDPI() {\n\t\t\t\tnewT := new(theme.Theme)\n\t\t\t\tif t != nil {\n\t\t\t\t\t*newT = *t\n\t\t\t\t}\n\t\t\t\tnewT.DPI = dpi\n\t\t\t\tt = newT\n\t\t\t}\n\n\t\t\twindowSize := e.Size()\n\t\t\tp.root.Measure(t, windowSize.X, windowSize.Y)\n\t\t\tp.root.Wrappee().Rect = e.Bounds()\n\t\t\tp.root.Layout(t)\n\t\t\t// TODO: call Mark(node.MarkNeedsPaint)?\n\n\t\tcase panelUpdate:\n\n\t\tcase error:\n\t\t\treturn e\n\t\t}\n\n\t\tif !paintPending && p.root.Wrappee().Marks.NeedsPaint() {\n\t\t\tpaintPending = true\n\t\t\tp.w.Send(paint.Event{})\n\t\t}\n\t}\n}", "func NewWindow(width, height int) (w *Window, err error) {\n\n\tw = new(Window)\n\tw.width, w.height = width, height\n\tw.showed = false\n\n\tw.xu, err = xgbutil.NewConn()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.conn = w.xu.Conn()\n\t// screen := w.xu.Screen()\n\n\tw.win, err = xwindow.Generate(w.xu)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %#+v\\n\", err)\n\t\treturn\n\t}\n\n\tkeybind.Initialize(w.xu)\n\n\terr = w.win.CreateChecked(w.xu.RootWin(), 0, 0, width, height, xproto.CwBackPixel, 0x606060ff)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.win.Listen(AllEventsMask)\n\n\terr = icccm.WmProtocolsSet(w.xu, w.win.Id, []string{\"WM_DELETE_WINDOW\"})\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\terr = nil\n\t}\n\n\tw.bufferLck = &sync.Mutex{}\n\tw.buffer = xgraphics.New(w.xu, image.Rect(0, 0, width, height))\n\tw.buffer.XSurfaceSet(w.win.Id)\n\n\t// I /think/ XDraw actually sends data to server?\n\tw.buffer.XDraw()\n\t// I /think/ XPaint tells the server to paint image to window\n\tw.buffer.XPaint(w.win.Id)\n\n\tkeyMap, modMap := keybind.MapsGet(w.xu)\n\tkeybind.KeyMapSet(w.xu, keyMap)\n\tkeybind.ModMapSet(w.xu, modMap)\n\n\tw.events = make(chan interface{})\n\n\tw.SetIcon(Gordon)\n\tw.SetIconName(\"Go\")\n\n\tgo w.handleEvents()\n\n\treturn\n}", "func (w *Window) Handle() *glfw.Window {\n\treturn w.glfwHandle\n}", "func (pa *PodAutoscaler) Window() (time.Duration, bool) {\n\t// The value is validated in the webhook.\n\treturn pa.annotationDuration(autoscaling.WindowAnnotation)\n}", "func (w *Window) Height() int {\n\treturn int(C.ANativeWindow_getHeight(w.cptr()))\n}", "func (c *Context) WindowHint(hint Hint, value HintValue) {\n\tC.glfwWindowHint(C.int(hint), C.int(value))\n}", "func (c *Context) WindowHint(hint Hint, value HintValue) {\n\tC.glfwWindowHint(C.int(hint), C.int(value))\n}", "func (w *WebGLRenderTarget) JSObject() *js.Object { return w.p }", "func (s *Session) Windows() ([]*Window, error) {\n\tresult, err := run(s, \"list-windows\", \"-F\", \"'#{window_id} #I #{window_active} #W'\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlines := strings.Split(result, \"\\n\")\n\n\twindows := make([]*Window, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tw, err := parseWindow(line)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tw.Session = s\n\n\t\twindows = append(windows, w)\n\t}\n\n\treturn windows, nil\n}", "func NewGlobalWindow() *WindowCoder {\n\treturn &WindowCoder{Kind: GlobalWindow}\n}", "func (app *appImpl) waitWindowInFocus() oswin.Window {\n\tfor {\n\t\twin := app.WindowInFocus()\n\t\tif win != nil {\n\t\t\treturn win\n\t\t}\n\t}\n}", "func newWindow(X *xgbutil.XUtil, color uint32) *xwindow.Window {\n\twin, err := xwindow.Generate(X)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = win.CreateChecked(X.RootWin(), 0, 0, 400, 400,\n\t\txproto.CwBackPixel|xproto.CwEventMask,\n\t\tcolor, xproto.EventMaskPointerMotion)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twin.Map()\n\treturn win\n}", "func (s *sdlWindow) Screen() draw.Image {\n\treturn s\n}", "func (d *WindowDefinition) Clone() *WindowDefinition {\n\tif d == nil {\n\t\treturn nil\n\t}\n\tother := *d\n\tother.Base = d.Base.Clone()\n\tother.Partitions = cloneExprs(d.Partitions)\n\tother.OrderingTerms = cloneOrderingTerms(d.OrderingTerms)\n\tother.Frame = d.Frame.Clone()\n\treturn &other\n}", "func NewRecvWindow(size int) *RecvWindow {\n\treturn &RecvWindow{\n\t\tsize: size,\n\t\tbuffer: NewRingBuffer(size),\n\t\tmessageNonce: 1,\n\t}\n}", "func getWindowData() []*windowData {\n\tresults := make([]*windowData, 0)\n\n\tsubWindowsLock.RLock()\n\n\ti := 0\n\tfor i < len(rotatedSubWindows) {\n\t\tthisWindow := *rotatedSubWindows[i]\n\t\tvar startWindow windowData\n\t\tif i == 0 {\n\t\t\tstartWindow = thisWindow\n\t\t} else {\n\t\t\tstartWindow = *rotatedSubWindows[i-1]\n\t\t}\n\t\taggregatedSubWindows := 1\n\t\t// Aggregate later sub windows\n\t\ti++\n\t\tfor i < len(rotatedSubWindows) && aggregatedSubWindows < maxSubWindowLengthInWindow {\n\t\t\tthisWindow.ExecuteCount += rotatedSubWindows[i].ExecuteCount\n\t\t\tthisWindow.TiFlashUsage.PushDown += rotatedSubWindows[i].TiFlashUsage.PushDown\n\t\t\tthisWindow.TiFlashUsage.ExchangePushDown += rotatedSubWindows[i].TiFlashUsage.ExchangePushDown\n\t\t\tthisWindow.TiFlashUsage.TableScan += rotatedSubWindows[i].TiFlashUsage.TableScan\n\t\t\tthisWindow.TiFlashUsage.TableScanWithFastScan += rotatedSubWindows[i].TiFlashUsage.TableScanWithFastScan\n\t\t\tthisWindow.CoprCacheUsage.GTE0 += rotatedSubWindows[i].CoprCacheUsage.GTE0\n\t\t\tthisWindow.CoprCacheUsage.GTE1 += rotatedSubWindows[i].CoprCacheUsage.GTE1\n\t\t\tthisWindow.CoprCacheUsage.GTE10 += rotatedSubWindows[i].CoprCacheUsage.GTE10\n\t\t\tthisWindow.CoprCacheUsage.GTE20 += rotatedSubWindows[i].CoprCacheUsage.GTE20\n\t\t\tthisWindow.CoprCacheUsage.GTE40 += rotatedSubWindows[i].CoprCacheUsage.GTE40\n\t\t\tthisWindow.CoprCacheUsage.GTE80 += rotatedSubWindows[i].CoprCacheUsage.GTE80\n\t\t\tthisWindow.CoprCacheUsage.GTE100 += rotatedSubWindows[i].CoprCacheUsage.GTE100\n\t\t\tthisWindow.SQLUsage.SQLTotal = rotatedSubWindows[i].SQLUsage.SQLTotal - startWindow.SQLUsage.SQLTotal\n\t\t\tthisWindow.SQLUsage.SQLType = calDeltaSQLTypeMap(rotatedSubWindows[i].SQLUsage.SQLType, startWindow.SQLUsage.SQLType)\n\n\t\t\tmergedBuiltinFunctionsUsage := BuiltinFunctionsUsage(thisWindow.BuiltinFunctionsUsage)\n\t\t\tmergedBuiltinFunctionsUsage.Merge(BuiltinFunctionsUsage(rotatedSubWindows[i].BuiltinFunctionsUsage))\n\t\t\tthisWindow.BuiltinFunctionsUsage = mergedBuiltinFunctionsUsage\n\t\t\taggregatedSubWindows++\n\t\t\ti++\n\t\t}\n\t\tresults = append(results, &thisWindow)\n\t}\n\n\tsubWindowsLock.RUnlock()\n\n\treturn results\n}", "func (w *Window) Screen() *gui.QScreen {\n\treturn w.screen\n}", "func debugPrintWinSize() {\n\twindow := getWinSize()\n\tfmt.Printf(\"col: %v\\nrow: %v\\nx: %v\\ny: %v\\n\", window.col, window.row, window.unusedX, window.unusedY)\n}", "func constructWindowDef(\n\tdef parser.WindowDef, namedWindowSpecs map[string]*parser.WindowDef,\n) (parser.WindowDef, error) {\n\tmodifyRef := false\n\tvar refName string\n\tswitch {\n\tcase def.RefName != \"\":\n\t\t// SELECT rank() OVER (w) FROM t WINDOW w as (...)\n\t\t// We copy the referenced window specification, and modify it if necessary.\n\t\trefName = def.RefName.Normalize()\n\t\tmodifyRef = true\n\tcase def.Name != \"\":\n\t\t// SELECT rank() OVER w FROM t WINDOW w as (...)\n\t\t// We use the referenced window specification directly, without modification.\n\t\trefName = def.Name.Normalize()\n\t}\n\tif refName == \"\" {\n\t\treturn def, nil\n\t}\n\n\treferencedSpec, ok := namedWindowSpecs[refName]\n\tif !ok {\n\t\treturn def, errors.Errorf(\"window %q does not exist\", refName)\n\t}\n\tif !modifyRef {\n\t\treturn *referencedSpec, nil\n\t}\n\n\t// referencedSpec.Partitions is always used.\n\tif len(def.Partitions) > 0 {\n\t\treturn def, errors.Errorf(\"cannot override PARTITION BY clause of window %q\", refName)\n\t}\n\tdef.Partitions = referencedSpec.Partitions\n\n\t// referencedSpec.OrderBy is used if set.\n\tif len(referencedSpec.OrderBy) > 0 {\n\t\tif len(def.OrderBy) > 0 {\n\t\t\treturn def, errors.Errorf(\"cannot override ORDER BY clause of window %q\", refName)\n\t\t}\n\t\tdef.OrderBy = referencedSpec.OrderBy\n\t}\n\treturn def, nil\n}", "func (sd *SelectDataset) Window(ws ...exp.WindowExpression) *SelectDataset {\n\treturn sd.copy(sd.clauses.SetWindows(ws))\n}", "func (c *Context) GetCurrentContext() *Window {\n\tcWindow := C.glfwGetCurrentContext()\n\tif unsafe.Pointer(cWindow) != C.NULL {\n\t\treturn (*Window)(cWindow)\n\t}\n\treturn nil\n}" ]
[ "0.6121591", "0.57735056", "0.56956416", "0.55192953", "0.5446127", "0.53620154", "0.5274085", "0.52285427", "0.51846564", "0.5162946", "0.511235", "0.50249225", "0.5017211", "0.5011972", "0.499117", "0.49634722", "0.49331006", "0.4904986", "0.48966926", "0.48881537", "0.48422503", "0.48358512", "0.48166093", "0.48059526", "0.48042086", "0.47964057", "0.47735503", "0.47723803", "0.47723803", "0.47540805", "0.47350666", "0.4719406", "0.47120428", "0.47089264", "0.4702294", "0.46879253", "0.4687723", "0.46811318", "0.4678027", "0.4669504", "0.46673143", "0.46580833", "0.46518764", "0.4650419", "0.4648789", "0.46437317", "0.46355164", "0.46197945", "0.46190488", "0.46106136", "0.4606568", "0.45910794", "0.4579194", "0.45760632", "0.4575847", "0.4574895", "0.45628914", "0.45589024", "0.45478952", "0.45476604", "0.45303366", "0.45261058", "0.4517817", "0.45125163", "0.45095152", "0.4508769", "0.45076823", "0.4507385", "0.45045203", "0.45042548", "0.45029515", "0.45008042", "0.44993362", "0.44804028", "0.4479692", "0.44769764", "0.4471348", "0.446434", "0.44595164", "0.44542384", "0.44537255", "0.44495678", "0.44351935", "0.44339523", "0.44227728", "0.44227728", "0.4406882", "0.44038042", "0.44026908", "0.439737", "0.43973213", "0.43931046", "0.43913236", "0.43816036", "0.43803895", "0.4368577", "0.4360931", "0.4357952", "0.43531987", "0.4343219" ]
0.8779711
0
Read only argument game ignores the pass lock by value warning.
func (g game) BridgesCount() (sum int) { for _, row := range g.ladder.bridges { for _, col := range row { if col { sum++ } } } return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*NoCopy) Lock() {}", "func (*noCopy) Lock() {}", "func Readonly(opts *Options) {\n\topts.Readonly = true\n}", "func mainLock(ctx *cli.Context) error {\n\tconsole.SetColor(\"Mode\", color.New(color.FgCyan, color.Bold))\n\tconsole.SetColor(\"Validity\", color.New(color.FgYellow))\n\n\t// Parse encryption keys per command.\n\t_, err := getEncKeys(ctx)\n\tfatalIf(err, \"Unable to parse encryption keys.\")\n\n\t// lock specific flags.\n\tclearLock := ctx.Bool(\"clear\")\n\n\targs := ctx.Args()\n\n\tvar urlStr string\n\tvar mode *minio.RetentionMode\n\tvar validity *uint\n\tvar unit *minio.ValidityUnit\n\n\tswitch l := len(args); l {\n\tcase 1:\n\t\turlStr = args[0]\n\n\tcase 3:\n\t\turlStr = args[0]\n\t\tif clearLock {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"clear flag must be passed with target alone\")\n\t\t}\n\n\t\tm := minio.RetentionMode(strings.ToUpper(args[1]))\n\t\tif !m.IsValid() {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid retention mode '%v'\", m)\n\t\t}\n\n\t\tmode = &m\n\n\t\tvalidityStr := args[2]\n\t\tunitStr := string(validityStr[len(validityStr)-1])\n\n\t\tvalidityStr = validityStr[:len(validityStr)-1]\n\t\tui64, err := strconv.ParseUint(validityStr, 10, 64)\n\t\tif err != nil {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity '%v'\", args[2])\n\t\t}\n\t\tu := uint(ui64)\n\t\tvalidity = &u\n\n\t\tswitch unitStr {\n\t\tcase \"d\", \"D\":\n\t\t\td := minio.Days\n\t\t\tunit = &d\n\t\tcase \"y\", \"Y\":\n\t\t\ty := minio.Years\n\t\t\tunit = &y\n\t\tdefault:\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity format '%v'\", args[2])\n\t\t}\n\tdefault:\n\t\tcli.ShowCommandHelpAndExit(ctx, \"lock\", 1)\n\t}\n\n\treturn lock(urlStr, mode, validity, unit, clearLock)\n}", "func (fb *Firebase) Shallow(v bool) {\n\tif v {\n\t\tfb.params.Set(shallowParam, \"true\")\n\t} else {\n\t\tfb.params.Del(shallowParam)\n\t}\n}", "func (self *ArgumentParser) statePassThrough(parser *parserState) stateFunc {\n for ; parser.pos < len(parser.args) ; parser.pos++ {\n arg := parser.args[parser.pos]\n parser.emitWithArgument(tokArgument, parser.stickyArg, parser.stickyArg.String)\n parser.emitWithValue(tokValue, arg)\n }\n return nil\n}", "func FuncChangeArg(param uint) {}", "func Passthrough(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {\n\treturn in, nil // nothing to do here, just to keep track of the safe application\n}", "func (x *fastReflection_PositionalArgDescriptor) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.proto_field\":\n\t\tpanic(fmt.Errorf(\"field proto_field of message cosmos.autocli.v1.PositionalArgDescriptor is not mutable\"))\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.varargs\":\n\t\tpanic(fmt.Errorf(\"field varargs of message cosmos.autocli.v1.PositionalArgDescriptor is not mutable\"))\n\tcase \"cosmos.autocli.v1.PositionalArgDescriptor.optional\":\n\t\tpanic(fmt.Errorf(\"field optional of message cosmos.autocli.v1.PositionalArgDescriptor is not mutable\"))\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 (r GopassRepo) lockState(payload []byte) error { return nil }", "func Bypass(i interface{}, err error) interface{} {\n\tPanicIf(err)\n\treturn i\n}", "func (*Item) Lock() {}", "func updateGPSReading( update GPSReading ) {\n rw_mutex.Lock()\n gpsReading = update\n rw_mutex.Unlock()\n}", "func Pass() (string, error) {\n\treturn arg.p, nil\n}", "func SkipArgs() Option { return Option{skipArgs: true} }", "func unused(value interface{}) {\n\t// TODO remove this method\n}", "func unused(value interface{}) {\n\t// TODO remove this method\n}", "func unused(value interface{}) {\n\t// TODO remove this method\n}", "func unused(value interface{}) {\n\t// TODO remove this method\n}", "func unused(value interface{}) {\n\t// TODO remove this method\n}", "func (c *cursor) allowUsable() {\n\tatomic.SwapUint32(&c.useState, 1)\n\tc.source.maybeConsume()\n}", "func pySafeArg(anm string, idx int) string {\n\tif anm == \"\" {\n\t\tanm = fmt.Sprintf(\"arg_%d\", idx)\n\t}\n\treturn pySafeName(anm)\n}", "func (p *Player) lock() {\n\tp.chLock <- struct{}{}\n}", "func (self *TileSprite) IgnoreChildInput() bool{\n return self.Object.Get(\"ignoreChildInput\").Bool()\n}", "func dontChangeMe(p animal) {\n\n\tp.name = \"New name\"\n\tp.age = 99\n}", "func (c Chan) ReadOnly() ReadChan {\n\treturn (chan struct{})(c)\n}", "func checkArgValue(v string, found bool, def cmdkit.Argument) error {\n\tif def.Variadic && def.SupportsStdin {\n\t\treturn nil\n\t}\n\n\tif !found && def.Required {\n\t\treturn fmt.Errorf(\"argument %q is required\", def.Name)\n\t}\n\n\treturn nil\n}", "func main(){\n\tx := 0\n\tchangeXVal(x)//Send value of x\n\tfmt.Println(\"x =\", x)\n}", "func (l *lockServer) Lock(args *LockArgs, reply *bool) error {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tif err := l.verifyArgs(args); err != nil {\n\t\treturn err\n\t}\n\t_, *reply = l.lockMap[args.Name]\n\tif !*reply { // No locks held on the given name, so claim write lock\n\t\tl.lockMap[args.Name] = []lockRequesterInfo{{writer: true, node: args.Node, rpcPath: args.RPCPath, uid: args.UID, timestamp: time.Now(), timeLastCheck: time.Now()}}\n\t}\n\t*reply = !*reply // Negate *reply to return true when lock is granted or false otherwise\n\treturn nil\n}", "func Warning(args ...interface{}) {\r\n\tif *gloged {\r\n\t\tglog.Warning(args...)\r\n\t} else {\r\n\t\tlog.Println(args...)\r\n\t}\r\n}", "func Warning(args ...interface{}) {\n\tWarn(args...)\n}", "func (m *RWMutex) RLockBypass() {\n\tm.mu.RLock()\n}", "func (lv *argLiveness) valueEffect(v *ssa.Value, live bitvec.BitVec) bool {\n\tif v.Op != ssa.OpStoreReg { // TODO: include other store instructions?\n\t\treturn false\n\t}\n\tn, off := ssa.AutoVar(v)\n\tif n.Class != ir.PPARAM {\n\t\treturn false\n\t}\n\ti, ok := lv.idx[nameOff{n, off}]\n\tif !ok || live.Get(i) {\n\t\treturn false\n\t}\n\tlive.Set(i)\n\treturn true\n}", "func FuncRemArg() {}", "func (self *Graphics) IgnoreChildInput() bool{\n return self.Object.Get(\"ignoreChildInput\").Bool()\n}", "func main() {\n\tage := 44\n\tfmt.Println(&age)\n\n\tchangeMe(&age)\n\n\tfmt.Println(&age)\n\tfmt.Println(age)\n}", "func (obj *Field) Lock(ctx context.Context) (bool, error) {\n\tresult := &struct {\n\t\tReturn bool `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"Lock\", result)\n\treturn result.Return, err\n}", "func (l *Lgr) BuildableWarn(buildableLogKey string, args ...interface{}) {\n msg := fmt.Sprint(args...)\n l.Logger.Warn(msg)\n l.newStreamEntry(buildableLogKey, msg, WarnLevel, false)\n}", "func failedUpdate(px *int) {\n\tx2 := 20\n\tpx = &x2\n}", "func (p *Player) Pass() {\n\tp.Passed = true\n}", "func (*S) Lock() {}", "func (m *RWMutex) RUnlockBypass() {\n\tm.mu.RUnlock()\n}", "func passArray(arr [3]int) {\n\tarr[1] = 10\n\tfmt.Println(\"Array is\", arr)\n}", "func (e *Enumerate) lock() {\n\te.u.m.Lock()\n}", "func (m programMap) setUnlocked(pid, number uint16) {\n\tm.p[uint32(pid)] = number\n}", "func TestPrewriteLocked4A(t *testing.T) {\n}", "func main() {\n\tage := 42\n\tfmt.Println(&age)\n\n\tchangeMe(&age)\n\n\tfmt.Println(&age)\n\tfmt.Println(age)\n}", "func PermitMemberDataOp(chantype, flag, name string) {\n\tHookCheckMemberData(chantype, name, func(_ string, u *core.User, m *core.Membership, _, _ string) (int, os.Error) {\n\t\tif HasOpFlag(u, m.Channel(), flag) {\n\t\t\treturn 10000, nil\n\t\t}\n\t\treturn 0, nil\n\t})\n}", "func (vals PendingValues) lockSet(inst, prop ident.Id, nilVal, want interface{}) (err error) {\n\tif reflect.TypeOf(nilVal) != reflect.TypeOf(want) {\n\t\terr = SetValueMismatch(inst, prop, nilVal, want)\n\t} else if curr, have := vals[prop]; have && curr != want {\n\t\terr = SetValueChanged(inst, prop, curr, want)\n\t} else {\n\t\tvals[prop] = want\n\t}\n\treturn err\n}", "func rn(vm *VM, argument string) {\n\tif vm.reading == nil {\n\t\tvm.err = ErrorReadingClose\n\t\treturn\n\t}\n\tif !vm.reading.previously() {\n\t\treturn\n\t}\n\tvm.reading.current = !vm.reading.current\n}", "func TestSetWrongArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetWrongArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\")})\n\n\tif res.Status != shim.ERROR {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func Warning(args ...interface{}) {\n\tlog.Println(args...)\n}", "func unlocked(res string) Lock {\n\treturn Lock{res, res, time.Time{}}\n}", "func rest() {\n\tP.health = P.maxHealth\n\ttextBox(\"Health Restored!\")\n}", "func shouldCopyLockFile(args []string) bool {\n\tif util.FirstArg(args) == CommandNameInit {\n\t\treturn true\n\t}\n\n\tif util.FirstArg(args) == CommandNameProviders && util.SecondArg(args) == CommandNameLock {\n\t\treturn true\n\t}\n\treturn false\n}", "func mutuallyExclusiveArgs(required bool, flags ...string) cli.BeforeFunc {\n\treturn func(c *cli.Context) error {\n\t\tprovidedCount := 0\n\t\tfor _, flag := range flags {\n\t\t\tif c.IsSet(flag) {\n\t\t\t\tprovidedCount++\n\t\t\t}\n\t\t}\n\n\t\tif providedCount > 1 {\n\t\t\treturn errors.Errorf(\"only one of (%s) can be set\", strings.Join(flags, \" | \"))\n\t\t}\n\n\t\tif required && providedCount == 0 {\n\t\t\treturn errors.Errorf(\"one of (%s) must be set\", strings.Join(flags, \" | \"))\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (d *Dam) Lock() {\n\td.freeze.Lock()\n}", "func Warning(args ...interface{}) {\n\tif defaultLgr == nil {\n\t\treturn\n\t}\n\tdefaultLgr.Warningf(strings.TrimSpace(strings.Repeat(\"%+v \", len(args))), args...)\n}", "func (bool shadower) shadowThem() {}", "func Warning(v ...interface{}) {\n if level <= LevelWarning {\n StdOutLogger.Printf(\"[W] %v\\n\", v)\n }\n}", "func (m *MutexSafe) lock() {\n\tm.Mutex.Lock()\n}", "func FuncChangeChanDirRelax(arg1 chan int) {}", "func read(arg string) int {\n\t// we do not consume the key, but in real life the key will be consumed to get the value\n\t// from DB or a filesystem etc.\n\t// We simply return a random number between 0 and 100 (excluded 100).\n\treturn rand.Intn(100)\n}", "func change(val *int) {\n\t*val = 55\n}", "func (x *XcChaincode) lock(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) < 3 {\n\t\treturn shim.Error(\"Params Error\")\n\t}\n\t//get operator\n\tsender, err := stub.GetSender()\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t} else if sender == \"\" {\n\t\treturn shim.Error(\"Account not exist\")\n\t}\n\ttoPlatform := strings.ToLower(args[0])\n\ttoAccount := strings.ToLower(args[1])\n\tamount := big.NewInt(0)\n\t_, ok := amount.SetString(args[2], 10)\n\tif !ok {\n\t\treturn shim.Error(\"Expecting integer value for amount\")\n\t}\n\n\t//try to get state from book which key is variable toPlatform's value\n\tplatState, err := stub.GetState(toPlatform)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get platform: \" + err.Error())\n\t} else if platState == nil {\n\t\treturn shim.Error(\"The platform named \" + toPlatform + \" is not registered\")\n\t}\n\n\t//set txId to be key\n\tkey := stub.GetTxID()\n\t//do transfer\n\terr = stub.Transfer(x.tacTokenAddr, \"TAB\", amount)\n\tif err != nil {\n\t\treturn shim.Error(\"Transfer error \" + err.Error())\n\t}\n\ttxTimestamp, err := stub.GetTxTimestamp()\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\ttimeStr := fmt.Sprintf(\"%d\", txTimestamp.GetSeconds())\n\t//build turn out state\n\tstate := x.buildTurnOutMessage(sender, toPlatform, toAccount, amount, timeStr)\n\terr = stub.PutState(key, state)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t//build composite key\n\tindexName := \"type~address~datetime~platform~key\"\n\tindexKey, err := stub.CreateCompositeKey(indexName, []string{\"out\", sender, timeStr, x.platName, key})\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tvalue := []byte{0x00}\n\tstub.PutState(indexKey, value)\n\n\t//sign\n\tsignJson, err := x.signJson([]byte(\"abc\"), \"60320b8a71bc314404ef7d194ad8cac0bee1e331\")\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\treturn shim.Success(signJson)\n}", "func mark_harmless(){\nif history==spotless{\nhistory= harmless_message\n}\n}", "func (l *Logger) Warning(args ...interface{}) {\n\tl.lock()\n\tdefer l.unlock()\n\tl.logger.Warning(args...)\n}", "func (*ExprLShr) Immutable() {}", "func (orm *Xorm) ReadOnly(b bool) {\n\torm.readOnly = b\n}", "func (p Position) Pass() bool {\n\treturn !p.Valid()\n}", "func main() {\n\tvar memoryAccess sync.Mutex //1\n\tvar value int\n\tgo func() {\n\t\tmemoryAccess.Lock() //2\n\t\tvalue++\n\t\tmemoryAccess.Unlock() //3\n\t}()\n\n\tmemoryAccess.Lock() //4\n\tif value == 0 {\n\t\tfmt.Printf(\"the value is %v\\n\", value)\n\t} else {\n\t\tfmt.Printf(\"the value is %v\\n\", value)\n\t}\n\tmemoryAccess.Unlock() //5\n}", "func (px *Paxos) setunreliable(what bool) {\n if what {\n atomic.StoreInt32(&px.unreliable, 1)\n } else {\n atomic.StoreInt32(&px.unreliable, 0)\n }\n}", "func (self *PhysicsP2) SleepMode() int{\n return self.Object.Get(\"sleepMode\").Int()\n}", "func passByReference(name *string) string {\n\t// We have to use the * to dereference the pointer \n\t*name = \"John\"\n\tfmt.Println(\"Name changed in passByReference to \", *name)\n\tfmt.Println(\"\\n\\n\")\n\treturn *name\n}", "func main () {\n\t\tx := 0\n\t\t//&x is passing the reference to x\n\t\tchangeXValNow(&x)\n\t\tfmt.Println(\"x = \", x)\n\n\t}", "func setLogicalLock(ctx context.Context, db *sql.DB, desired bool) error {\n\tt := time.NewTicker(1 * time.Second)\n\tdefer t.Stop()\n\n\tfor {\n\t\tresult, err := db.ExecContext(ctx, \"\"+\n\t\t\t\"update __meta set value = ? where `key` = 'locked' and value = ?\",\n\t\t\tboolToString(desired), boolToString(!desired),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\taffected, err := result.RowsAffected()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif affected == 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tselect {\n\t\tcase <-t.C:\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}", "func (t *TrudyPipe) Lock() {\n\tt.userMutex.Lock()\n}", "func checkArgs(c *cli.Context) (rtn int) {\n rtn = 0\n if c.NArg() < 3 {\n color.Red(\"Wrong Input.\")\n color.Red(\"Use mo sqlite3 <dbFullName> <UserToChange> <PasswordToSet>\")\n color.Red(\"Example: mo sqlite3 USER.DB admin 111111 \")\n rtn = 1\n return\n }\n\n _, err := os.Stat(c.Args().First())\n if err != nil {\n if os.IsNotExist(err) {\n color.Red(\"File %s does not exist.\", c.Args().First())\n rtn = 2\n return\n }\n }\n return\n\n}", "func muting(s *discordgo.Session, v *discordgo.VoiceStateUpdate) {\n\tif v.UserID == s.State.User.ID {\n\t\tlkm := newLkm()\n\n\t\tif v.Deaf || v.Mute || v.SelfDeaf || v.SelfMute {\n\t\t\tlog.Info(\"Muted on Discord.\")\n\t\t\tdiscordUnmuted = false\n\t\t\tlkm.write(true)\n\t\t} else {\n\t\t\tlog.Info(\"Unmuted on Discord.\")\n\t\t\tdiscordUnmuted = true\n\t\t\tlkm.write(false)\n\t\t}\n\t}\n\n\treturn\n}", "func Unlock() {\n\t// TO DO\n}", "func Warn(v ...interface{}){\n log.Warn(v)\n}", "func (l *Level) set(val Level) {\n\tatomic.StoreInt32((*int32)(l), int32(val))\n}", "func (v Verbosity) Warning(args ...interface{}) {\n\tif v {\n\t\twarningLog.Output(CallDepth+1, fmt.Sprint(args...))\n\t}\n}", "func (self *TileSprite) OutOfCameraBoundsKill() bool{\n return self.Object.Get(\"outOfCameraBoundsKill\").Bool()\n}", "func (p Pin) Lock() {\n\tp.Port().Lock(Pin0 << p.index())\n}", "func PermitChanDataOp(chantype, flag, name string) {\n\tHookCheckChanData(chantype, name, func(_ string, u *core.User, ch *core.Channel, _, _ string) (int, os.Error) {\n\t\tif HasOpFlag(u, ch, flag) {\n\t\t\treturn 10000, nil\n\t\t}\n\t\treturn 0, nil\n\t})\n}", "func check_complete(){\nif len(change_buffer)> 0{/* changing is false */\nbuffer= change_buffer\nchange_buffer= nil\nchanging= true\nchange_depth= include_depth\nloc= 0\nerr_print(\"! Change file entry did not match\")\n\n}\n}", "func lWarn(v ...interface{}) {\n\t/* #nosec */\n\t_ = warnLogger.Output(2, fmt.Sprintln(v...)) //Following log package, ignoring error value\n}", "func (l *Lgr) Warn(args ...interface{}) {\n l.Logger.Warn(args...)\n}", "func (mdl *Model) Lock() {\n\tmdl.locked = true\n}", "func (f *fragment) protectedSnapshot(fromQueue bool) error {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\terr := f.snapshot()\n\tif fromQueue {\n\t\tf.snapshotting = false\n\t}\n\treturn err\n}", "func (g *Game) RunLocked(f func()) {\n\tg.M.Lock()\n\tdefer g.M.Unlock()\n\tf()\n}", "func (ma *FakeActor) GoodCall(ctx exec.VMContext) (uint8, error) {\n\tfastore := &FakeActorStorage{}\n\t_, err := WithState(ctx, fastore, func() (interface{}, error) {\n\t\tfastore.Changed = true\n\t\treturn nil, nil\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn 0, nil\n}", "func (l *Level) get() Level {\n\treturn Level(atomic.LoadInt32((*int32)(l)))\n}", "func (m *ParameterMutator) Required(v bool) *ParameterMutator {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.proxy.required = v\n\treturn m\n}", "func (heap *SkewHeap) lock() { heap.mutex.Lock() }", "func Safe(call func()) {\n\tdefer Recover()\n\tcall()\n}", "func (c SubRepoPermissionCheckerEnabledFuncCall) Args() []interface{} {\n\treturn []interface{}{}\n}", "func Warning(args ...interface{}) {\n LoggerOf(default_id).Warning(args...)\n}", "func square(num int) {\n\n\tfmt.Println(\"Received Copy:\", num)\n\n\tnum = num * num\n\tfmt.Println(\"Modified Copy:\", num)\n}", "func changeMe(z *int) {\n\tfmt.Println(z)\n\tfmt.Println(*z)\n\t//*z dereferences memory address\n\t//and shows value instead of address\n\t*z = 24\n\t//changing value of original\n\t//data passed into func by using memory address\n\tfmt.Println(z)\n\tfmt.Println(*z)\n}" ]
[ "0.5734881", "0.5633942", "0.5482277", "0.54154927", "0.5370941", "0.5030581", "0.50263333", "0.50120914", "0.5009855", "0.49270573", "0.49246377", "0.4844874", "0.48276043", "0.4819514", "0.4801058", "0.47585997", "0.47585997", "0.47585997", "0.47585997", "0.47585997", "0.4716871", "0.47102258", "0.47086865", "0.46717608", "0.46685284", "0.46672317", "0.46592996", "0.4654456", "0.463866", "0.46375033", "0.4617878", "0.45936158", "0.45929146", "0.45700195", "0.45681068", "0.45674616", "0.4554986", "0.45454618", "0.45354804", "0.45302904", "0.45282638", "0.4514023", "0.45121184", "0.4499779", "0.44971755", "0.44958", "0.4487596", "0.4487094", "0.44855836", "0.4482647", "0.4479316", "0.44725946", "0.44610095", "0.44598776", "0.44583136", "0.4448488", "0.44458017", "0.44415006", "0.44362906", "0.44333008", "0.44259086", "0.44248515", "0.4416751", "0.4411014", "0.43841094", "0.43832612", "0.4379918", "0.43783942", "0.4375534", "0.43714687", "0.43549883", "0.43477136", "0.43465278", "0.4342507", "0.43384305", "0.43382195", "0.4338054", "0.43339565", "0.43324456", "0.43323138", "0.43241763", "0.4324059", "0.4322868", "0.43218586", "0.43204296", "0.4320397", "0.4317545", "0.43125182", "0.43100086", "0.43089852", "0.43077055", "0.43055227", "0.4304464", "0.43039933", "0.4300357", "0.4300337", "0.4299719", "0.42964563", "0.42950958", "0.42945424", "0.42929935" ]
0.0
-1
Run on main thread Run the game window and its event loop on main thread.
func (g *game) Run() { pixelgl.Run(func() { g.RunLazyInit() g.RunEventLoop() }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func run() {\n\tglobal.gVariables.Load(wConfigFile)\n\n\t// Initialize window\n\tcfg := pixelgl.WindowConfig{\n\t\tTitle: wWindowTitle,\n\t\tBounds: pixel.R(0, 0, global.gVariables.WindowWidth, global.gVariables.WindowHeight),\n\t\tVSync: true,\n\t}\n\tgWin, err := pixelgl.NewWindow(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgWin.SetCursorVisible(false)\n\tglobal.gWin = gWin\n\n\tsetup()\n\n\tgameLoop()\n}", "func (w *MainWindow) Run() {\n\t// https://www.iditect.com/how-to/53890601.html\n\tglfw.SwapInterval(0)\n\n\t//TODO detect best sleeping times using the old frame time and desired refresh rate\n\n\tbegin := time.Now()\n\tlast := time.Duration(0)\n\tfor !w.glfwWindow.ShouldClose() {\n\t\ttime.Sleep(w.FixedPreFrameSleep)\n\n\t\tt := time.Since(begin)\n\t\tdt := (t - last)\n\t\tif w.maxSimStep > 0 && dt > w.maxSimStep {\n\t\t\tdt = w.maxSimStep\n\t\t}\n\t\tw.totalSimTime += dt\n\t\tlast = t\n\n\t\tglfw.WaitEventsTimeout(w.FixedPollEventsTimeout.Seconds())\n\n\t\tgl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\n\t\tfor _, c := range w.layers {\n\t\t\tc.Update(w, dt.Seconds())\n\t\t}\n\n\t\tfor _, c := range w.layers {\n\t\t\tc.Render(w)\n\t\t}\n\n\t\tw.glfwWindow.SwapBuffers()\n\t}\n\n\t// now gracefully close remaining contexts:\n\tfor len(w.layers) > 0 {\n\t\tw.LeaveUppermostLayer()\n\t}\n}", "func (w *Window) Run() {\n\tw.readEvents(w.nativeWin.EventChan())\n}", "func Run(app func(w *Window)) {\n\tw := &Window{\n\t\tRedraw: make(chan window.Event, 128),\n\t\tapp: app,\n\t\trender: make(chan struct{}),\n\t}\n\twindow.Run(w.gfxLoop, Props)\n}", "func (g *Gui) MainLoop() error {\n\tgo func() {\n\t\tfor {\n\t\t\tg.tbEvents <- g.screen.PollEvent()\n\t\t}\n\t}()\n\n\tif g.Mouse {\n\t\tg.screen.EnableMouse()\n\t}\n\t// s.EnablePaste()\n\n\tif err := g.flush(); err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tselect {\n\t\tcase ev := <-g.tbEvents:\n\t\t\tif err := g.handleEvent(ev); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ev := <-g.userEvents:\n\t\t\tif err := ev.f(g); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif err := g.consumeevents(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := g.flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (ws *WindowSurface) Run() {\n\t// log.Println(\"Starting viewer polling\")\n\tws.running = true\n\t// var simStatus = \"\"\n\tvar frameStart time.Time\n\tvar elapsedTime float64\n\tvar loopTime float64\n\n\tsleepDelay := 0.0\n\n\t// Get a reference to SDL's internal keyboard state. It is updated\n\t// during sdl.PollEvent()\n\tkeyState := sdl.GetKeyboardState()\n\n\trasterizer := renderer.NewBresenHamRasterizer()\n\n\tsdl.SetEventFilterFunc(ws.filterEvent, nil)\n\n\tfor ws.running {\n\t\tframeStart = time.Now()\n\n\t\tsdl.PumpEvents()\n\n\t\tif keyState[sdl.SCANCODE_Z] != 0 {\n\t\t\tws.mod--\n\t\t}\n\t\tif keyState[sdl.SCANCODE_X] != 0 {\n\t\t\tws.mod++\n\t\t}\n\n\t\tws.clearDisplay()\n\n\t\tws.render(rasterizer)\n\n\t\t// This takes on average 5-7ms\n\t\t// ws.texture.Update(nil, ws.pixels.Pix, ws.pixels.Stride)\n\t\tws.texture.Update(nil, ws.rasterBuffer.Pixels().Pix, ws.rasterBuffer.Pixels().Stride)\n\t\tws.renderer.Copy(ws.texture, nil, nil)\n\n\t\tws.txtFPSLabel.DrawAt(10, 10)\n\t\tf := fmt.Sprintf(\"%2.2f\", 1.0/elapsedTime*1000.0)\n\t\tws.dynaTxt.DrawAt(ws.txtFPSLabel.Bounds.W+10, 10, f)\n\n\t\t// ws.mx, ws.my, _ = sdl.GetMouseState()\n\t\tws.txtMousePos.DrawAt(10, 25)\n\t\tf = fmt.Sprintf(\"<%d, %d>\", ws.mx, ws.my)\n\t\tws.dynaTxt.DrawAt(ws.txtMousePos.Bounds.W+10, 25, f)\n\n\t\tws.txtLoopLabel.DrawAt(10, 40)\n\t\tf = fmt.Sprintf(\"%2.2f\", loopTime)\n\t\tws.dynaTxt.DrawAt(ws.txtLoopLabel.Bounds.W+10, 40, f)\n\n\t\tws.renderer.Present()\n\n\t\t// time.Sleep(time.Millisecond * 5)\n\t\tloopTime = float64(time.Since(frameStart).Nanoseconds() / 1000000.0)\n\t\t// elapsedTime = float64(time.Since(frameStart).Seconds())\n\n\t\tsleepDelay = math.Floor(framePeriod - loopTime)\n\t\t// fmt.Printf(\"%3.5f ,%3.5f, %3.5f \\n\", framePeriod, elapsedTime, sleepDelay)\n\t\tif sleepDelay > 0 {\n\t\t\tsdl.Delay(uint32(sleepDelay))\n\t\t\telapsedTime = framePeriod\n\t\t} else {\n\t\t\telapsedTime = loopTime\n\t\t}\n\t}\n}", "func Main(f func(oswin.App)) {\n\toswin.TheApp = theApp\n\ttheApp.initScreens()\n\n\t// It does not matter which OS thread we are on.\n\t// All that matters is that we confine all UI operations\n\t// to the thread that created the respective window.\n\truntime.LockOSThread()\n\n\tif err := initCommon(); err != nil {\n\t\treturn\n\t}\n\n\tif err := initAppWindow(); err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t// TODO(andlabs): log an error if this fails?\n\t\t_DestroyWindow(appHWND)\n\t\t// TODO(andlabs): unregister window class\n\t}()\n\n\tif err := initWindowClass(); err != nil {\n\t\treturn\n\t}\n\n\t// Prime the pump.\n\tmainCallback = f\n\t_PostMessage(appHWND, msgMainCallback, 0, 0)\n\n\t// Main message pump.\n\tvar m _MSG\n\tfor {\n\t\tdone, err := _GetMessage(&m, 0, 0, 0)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"win32 GetMessage failed: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif done == 0 { // WM_QUIT\n\t\t\tbreak\n\t\t}\n\t\t_TranslateMessage(&m)\n\t\t_DispatchMessage(&m)\n\t}\n}", "func (v *App) Run() {\n\t// log.Println(\"Starting App polling\")\n\tv.running = true\n\tsdl.SetEventFilterFunc(v.filterEvent, nil)\n\n\t// sdl.SetHint(sdl.HINT_RENDER_SCALE_QUALITY, \"linear\")\n\tv.renderer.SetDrawColor(64, 64, 64, 255)\n\tv.renderer.Clear()\n\n\t// v.pointsGraph.SetSeries(v.pointsGraph.Accessor())\n\tv.spikeGraph.SetSeries(nil)\n\n\tfor v.running {\n\t\tsdl.PumpEvents()\n\n\t\tv.renderer.Clear()\n\n\t\t// v.pointsGraph.MarkDirty(true)\n\t\tv.spikeGraph.MarkDirty(true)\n\n\t\tif samples.PoiSamples != nil {\n\t\t\tdraw := v.spikeGraph.Check()\n\t\t\tif draw {\n\t\t\t\tv.spikeGraph.DrawAt(0, 100)\n\t\t\t}\n\t\t}\n\n\t\tv.expoGraph.DrawAt(0, 300)\n\n\t\tv.txtSimStatus.Draw()\n\t\tv.txtActiveProperty.Draw()\n\n\t\tv.window.UpdateSurface()\n\n\t\t// sdl.Delay(17)\n\t\ttime.Sleep(time.Millisecond * 100)\n\t}\n\n\tv.shutdown()\n}", "func (w *windowImpl) drawLoop() {\n\truntime.LockOSThread()\nouter:\n\tfor {\n\t\tselect {\n\t\tcase <-w.winClose:\n\t\t\tbreak outer\n\t\tcase <-w.publish:\n\t\t\tw.app.RunOnMain(func() {\n\t\t\t\ttheGPU.UseContext(w)\n\t\t\t\tgl.Flush()\n\t\t\t\tw.glw.SwapBuffers()\n\t\t\t\t// gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\t\t\t\ttheGPU.ClearContext(w)\n\t\t\t})\n\t\t\tw.publishDone <- oswin.PublishResult{}\n\t\t}\n\t}\n}", "func (app *App) Run() error {\n\t// Configure global settings\n\tgl.Enable(gl.CULL_FACE)\n\tgl.Enable(gl.DEPTH_TEST)\n\tgl.DepthFunc(gl.LESS)\n\n\tpreviousTime := glfw.GetTime()\n\n\tfor !app.window.ShouldClose() {\n\n\t\t// Update\n\t\ttime := glfw.GetTime()\n\t\telapsed := time - previousTime\n\t\tpreviousTime = time\n\n\t\tfor _, r := range app.Renderers {\n\t\t\tr.Render(app.Camera.ProjView, elapsed)\n\t\t}\n\n\t\t// Maintenance\n\t\tapp.window.SwapBuffers()\n\t\tglfw.PollEvents()\n\t}\n\treturn nil\n}", "func (render *Render) MainLoop() {\n\tdefer glfw.Terminate()\n\n\t// texture setup\n\tvar texture uint32\n\tgl.GenTextures(1, &texture)\n\tgl.BindTexture(gl.TEXTURE_2D, texture)\n\tsetTextureParams()\n\tgl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGB, Width, Height, 0, gl.RGBA, gl.UNSIGNED_BYTE, nil)\n\n\t// bind to shader\n\tgl.UseProgram(render.Program)\n\t// gl.Uniform1i(gl.GetUniformLocation(render.Program, gl.Str(\"ourTexture\\x00\")), 0)\n\n\ttexUniform := gl.GetUniformLocation(render.Program, gl.Str(\"ourTexture\\x00\"))\n\tflipXUniform := gl.GetUniformLocation(render.Program, gl.Str(\"flipX\\x00\"))\n\tflipYUniform := gl.GetUniformLocation(render.Program, gl.Str(\"flipY\\x00\"))\n\tmodelUniform := gl.GetUniformLocation(render.Program, gl.Str(\"model\\x00\"))\n\tidentity := mgl32.Ident4()\n\n\tgl.UseProgram(render.Program)\n\n\tvar lastTime float64\n\n\tvar delta, lastUpdate float64\n\tvar nbFrames int\n\tfor !render.Window.ShouldClose() {\n\n\t\t// block to reduce fan noise (if fps limited)\n\t\t// this limits the speed of the opengl rendering thread\n\t\tlastTime = render.Sleep(lastTime)\n\n\t\tcurrentTime := glfw.GetTime()\n\t\tdelta = currentTime - lastUpdate\n\t\tnbFrames++\n\t\tif delta >= 1.0 { // If last cout was more than 1 sec ago\n\t\t\trender.Window.SetTitle(fmt.Sprintf(\"FPS: %.2f / %.2f\", float64(nbFrames)/delta, render.Fps))\n\t\t\tnbFrames = 0\n\t\t\tlastUpdate = currentTime\n\t\t}\n\n\t\t// are we in capture input mode?\n\t\tselect {\n\t\tcase n := <-render.StartInput:\n\t\t\trender.InputMode = n\n\t\tcase spriteCommand := <-render.SpriteChannel:\n\t\t\trender.runSpriteCommand(spriteCommand)\n\t\tdefault:\n\t\t\t// don't block\n\t\t}\n\n\t\tglfw.PollEvents()\n\n\t\tswapBuffers := false\n\t\trender.Lock.Lock()\n\t\tif render.UpdateScreen {\n\t\t\tgl.ActiveTexture(gl.TEXTURE0)\n\t\t\tgl.BindTexture(gl.TEXTURE_2D, texture)\n\n\t\t\t// need to do this so go.Ptr() works. This could be a bug in go: https://github.com/golang/go/issues/14210\n\t\t\tpixels := render.PixelMemory\n\t\t\tgl.TexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, Width, Height, gl.RGB, gl.UNSIGNED_BYTE, gl.Ptr(&pixels[0]))\n\n\t\t\t// gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\t\t\tgl.UniformMatrix4fv(modelUniform, 1, false, &identity[0])\n\t\t\tgl.Uniform1i(texUniform, 0)\n\t\t\tgl.Uniform1i(flipXUniform, 0)\n\t\t\tgl.Uniform1i(flipYUniform, 0)\n\t\t\tgl.BindVertexArray(render.Vao)\n\t\t\tgl.DrawArrays(gl.TRIANGLES, 0, int32(len(screen)/8))\n\n\t\t\trender.UpdateScreen = false\n\t\t\tswapBuffers = true\n\t\t}\n\t\trender.Lock.Unlock()\n\n\t\trender.SpriteLock.Lock()\n\t\tif swapBuffers || render.UpdateSprites {\n\t\t\tgl.Enable(gl.BLEND)\n\t\t\t// gl.BlendEquation(gl.MAX)\n\t\t\tgl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)\n\t\t\tfor _, sprite := range render.Sprites {\n\t\t\t\tif sprite.Show {\n\t\t\t\t\tgl.BindTexture(gl.TEXTURE_2D, sprite.Textures[sprite.ImageIndex])\n\t\t\t\t\tgl.Uniform1i(texUniform, 0)\n\t\t\t\t\tgl.Uniform1i(flipXUniform, sprite.FlipX)\n\t\t\t\t\tgl.Uniform1i(flipYUniform, sprite.FlipY)\n\n\t\t\t\t\tsprite.Model = mgl32.Ident4().\n\t\t\t\t\t\tMul4(mgl32.Translate3D(float32(sprite.X-Width/2)/float32(Width/2), -float32(sprite.Y-Height/2)/float32(Height/2), 0)).\n\t\t\t\t\t\tMul4(mgl32.Scale3D(float32(sprite.W)/float32(Width), float32(sprite.H)/float32(Height), 1))\n\n\t\t\t\t\tgl.UniformMatrix4fv(modelUniform, 1, false, &sprite.Model[0])\n\t\t\t\t\tgl.DrawArrays(gl.TRIANGLES, 0, int32(len(screen)/8))\n\t\t\t\t}\n\t\t\t}\n\t\t\tgl.Disable(gl.BLEND)\n\n\t\t\trender.UpdateSprites = false\n\t\t\tswapBuffers = true\n\t\t}\n\t\trender.SpriteLock.Unlock()\n\n\t\tif swapBuffers {\n\t\t\trender.Window.SwapBuffers()\n\t\t}\n\t}\n}", "func run() {\n\tw, h := 800, 550\n\n\tvar err error\n\twin, err := wde.NewWindow(w, h)\n\tif err != nil {\n\t\tlog.Printf(\"Create window error: %v\", err)\n\t\treturn\n\t}\n\n\twin.SetTitle(title)\n\twin.LockSize(true)\n\twin.Show()\n\n\teng = engine.NewEngine(win, w, h)\n\tgo eng.Run()\n\n\tfor event := range win.EventChan() {\n\t\tif quit := handleEvent(event); quit {\n\t\t\tbreak\n\t\t}\n\t}\n\teng.Stop()\n\n\twde.Stop()\n}", "func init() {\n\t// Ensure that the ui's main thread is locked to the main thread.\n\truntime.LockOSThread()\n}", "func (w *windowImpl) winLoop() {\nouter:\n\tfor {\n\t\tselect {\n\t\tcase <-w.winClose:\n\t\t\tbreak outer\n\t\tcase f := <-w.runQueue:\n\t\t\tif w.glw == nil {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t\tf.f()\n\t\t\tif f.done != nil {\n\t\t\t\tf.done <- true\n\t\t\t}\n\t\tcase <-w.publish:\n\t\t\tif w.glw == nil {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t\tif !theApp.noScreens {\n\t\t\t\ttheApp.RunOnMain(func() {\n\t\t\t\t\tif !w.Activate() {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tw.glw.SwapBuffers() // note: implicitly does a flush\n\t\t\t\t\t// note: generally don't need this:\n\t\t\t\t\t// gpu.Draw.Clear(true, true)\n\t\t\t\t})\n\t\t\t\tw.publishDone <- struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}", "func Main(f func(oswin.App)) {\n\tlog.Println(\"in Main\")\n\tgi.DialogsSepWindow = false\n\tmainCallback = f\n\ttheApp.initVk()\n\toswin.TheApp = theApp\n\tgo func() {\n\t\tmainCallback(theApp)\n\t\tlog.Println(\"main callback done\")\n\t\ttheApp.stopMain()\n\t}()\n\ttheApp.eventLoop()\n\tlog.Println(\"main loop done\")\n}", "func main() {\n\t// Creates the Window Wrapper\n\tglw := wrapper.NewWrapper(windowWidth, windowHeight, \"Lab 3: Lights\")\n\tglw.SetFPS(windowFPS)\n\n\t// Creates the Window\n\tglw.CreateWindow()\n\n\t// Sets the Event Callbacks\n\tglw.SetRenderCallback(drawLoop)\n\tglw.SetKeyCallBack(keyCallback)\n\tglw.SetReshapeCallback(reshape)\n\n\t// Initializes the App\n\tInitApp(glw)\n\n\t// Starts the Rendering Loop\n\tglw.StartLoop()\n\n\t// Sets the Viewport (Important !!, this has to run after the loop!!)\n\tdefer gl.Viewport(0, 0, windowWidth, windowHeight)\n}", "func main() {\n\tr := NewRenderer()\n\n\t// We draw the background canvas just once.\n\tr.GetBackgroundCanvasReady()\n\n\t// Everything else happens in response to mouse movements.\n\tr.RealCanvas.Set(\"onmousemove\", js.FuncOf(r.OnMoveHandler))\n\twait := make(chan bool)\n\t<-wait\n}", "func (a *App) Loop() {\n\tif err := a.gui.MainLoop(); err != nil && err != gocui.ErrQuit {\n\t\tlog.Panicln(err)\n\t}\n}", "func main() {\n\tfmt.Println(\"init\")\n\tgame := Game{}\n\tgame.Init()\n\n\trl.InitWindow(game.ScreenWidth, game.ScreenHeight, game.Title)\n\trl.SetTargetFPS(60)\n\n\tfor !rl.WindowShouldClose() {\n\t\tgame.Update()\n\t\tgame.Draw()\n\t}\n\n\trl.CloseWindow()\n}", "func (g *Game) Run() {\n\t// On browsers, let's use fullscreen so that this is playable on any browsers.\n\t// It is planned to ignore the given 'scale' apply fullscreen automatically on browsers (#571).\n\tif runtime.GOARCH == \"js\" || runtime.GOOS == \"js\" {\n\t\tebiten.SetFullscreen(true)\n\t}\n\n\tif err := ebiten.Run(g.Update, g.width, g.height, screenScale, \"Raycaster-Go\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Run(level int8) error {\n\terr := sdl.Init(sdl.INIT_EVERYTHING)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not initialize SDL: %w\", err)\n\t}\n\tdefer sdl.Quit()\n\n\tif err := ttf.Init(); err != nil {\n\t\treturn fmt.Errorf(\"could not initialize TTF: %w\", err)\n\t}\n\tdefer ttf.Quit()\n\n\tw, r, err := sdl.CreateWindowAndRenderer(1280, 720, sdl.WINDOW_SHOWN)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create window: %w\", err)\n\t}\n\tdefer w.Destroy()\n\n\ts, err := scene.NewScene(r, level)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create scene: %w\", err)\n\t}\n\tdefer s.Destroy()\n\n\tevents := make(chan sdl.Event)\n\terrc := s.Run(events, r)\n\n\truntime.LockOSThread()\n\tfor {\n\t\tselect {\n\t\tcase events <- sdl.WaitEvent():\n\t\tcase err := <-errc:\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (a *Application) Run(update func(rend *renderer.Renderer, deltaTime time.Duration)) {\r\n\r\n\t// Initialize start and frame time\r\n\ta.startTime = time.Now()\r\n\ta.frameStart = time.Now()\r\n\r\n\t// Set up recurring calls to user's update function\r\n\tfor true {\r\n\t\t// If Exit() was called or there was an attempt to close the window dispatch OnExit event for subscribers.\r\n\t\t// If no subscriber cancelled the event, terminate the application.\r\n\t\tif a.IWindow.(*window.GlfwWindow).ShouldClose() {\r\n\t\t\ta.Dispatch(OnExit, nil)\r\n\t\t\t// TODO allow for cancelling exit e.g. showing dialog asking the user if he/she wants to save changes\r\n\t\t\t// if exit was cancelled {\r\n\t\t\t// a.IWindow.(*window.GlfwWindow).SetShouldClose(false)\r\n\t\t\t// } else {\r\n\t\t\tbreak\r\n\t\t\t// }\r\n\t\t}\r\n\t\t// Update frame start and frame delta\r\n\t\tnow := time.Now()\r\n\t\ta.frameDelta = now.Sub(a.frameStart)\r\n\t\ta.frameStart = now\r\n\t\t// Call user's update function\r\n\t\tupdate(a.renderer, a.frameDelta)\r\n\t\t// Swap buffers and poll events\r\n\t\ta.IWindow.(*window.GlfwWindow).SwapBuffers()\r\n\t\ta.IWindow.(*window.GlfwWindow).PollEvents()\r\n\t}\r\n\r\n\t// Close default audio device\r\n\tif a.audioDev != nil {\r\n\t\tal.CloseDevice(a.audioDev)\r\n\t}\r\n\t// Destroy window\r\n\ta.Destroy()\r\n}", "func Run(onStart func() error, onExit func(err error)) {\n\tif started {\n\t\tpanic(\"re-enter func Run()\")\n\t}\n\tstarted = true\n\tgOnStart = onStart\n\tgOnExit = onExit\n\tcode := C.winl_event_loop()\n\twinl_on_exit(code)\n}", "func (gui *Gui) Start() {\n\tgo func(done chan interface{}) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(500 * time.Millisecond):\n\t\t\t\tgui.app.Draw()\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(gui.done)\n}", "func StartMainLoop() {\n\tC.gstreamer_receive_start_mainloop()\n}", "func (l *renderLoop) Run() {\n\truntime.LockOSThread()\n\tcubelib.Initialize()\n\n\t// Create the 3D world\n\tworld := cubelib.NewWorld()\n\tworld.SetCamera(0.0, 0.0, 5.0)\n\n\tcube := cubelib.NewCube()\n\tcube.AttachTexture(loadImage(\"marmo.png\"))\n\n\tworld.Attach(cube)\n\tangle := float32(0.0)\n\tfor {\n\t\tselect {\n\t\tcase <-l.pause:\n\t\t\tl.ticker.Stop()\n\t\t\tl.pause <- 0\n\t\tcase <-l.terminate:\n\t\t\tcubelib.Cleanup()\n\t\t\tl.terminate <- 0\n\t\tcase <-l.ticker.C:\n\t\t\tangle += 0.05\n\t\t\tcube.RotateY(angle)\n\t\t\tworld.Draw()\n\t\t\tcubelib.Swap()\n\t\t}\n\t}\n}", "func (g *game) Run() {\n\tif err := termbox.Init(); err != nil {\n\t\tpanic(err)\n\t}\n\tg.keypressChan = make(chan keypress)\n\tg.selectedIndex = point{Row: 0, Column: 0}\n\n\tg.Render()\n\tgo g.listenForEvents()\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-g.keypressChan:\n\t\t\tswitch ev.EventType {\n\t\t\tcase MoveUp:\n\t\t\t\tg.moveCursor(-1, 0)\n\t\t\tcase MoveDown:\n\t\t\t\tg.moveCursor(1, 0)\n\t\t\tcase MoveLeft:\n\t\t\t\tg.moveCursor(0, -1)\n\t\t\tcase MoveRight:\n\t\t\t\tg.moveCursor(0, 1)\n\t\t\tcase Quit:\n\t\t\t\ttermbox.Close()\n\t\t\t\treturn\n\t\t\tcase Select:\n\t\t\t\tg.selectCell(g.selectedIndex.Row, g.selectedIndex.Column)\n\t\t\tcase Flag:\n\t\t\t\tg.flagCell(g.selectedIndex.Row, g.selectedIndex.Column)\n\t\t\t}\n\t\t}\n\t}\n}", "func Run(app App) error {\n\t// -------------------------------------------------------------------- //\n\t// Create\n\t// -------------------------------------------------------------------- //\n\tsettings := defaultSettings\n\terr := app.OnCreate(&settings)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\n\t// -------------------------------------------------------------------- //\n\t// Init\n\t// -------------------------------------------------------------------- //\n\tjsTge := js.Global().Get(\"tge\")\n\tif settings.Fullscreen {\n\t\tjsTge.Call(\"setFullscreen\", settings.Fullscreen)\n\t} else {\n\t\tjsTge.Call(\"resize\", settings.Width, settings.Height)\n\t}\n\n\tcanvas := jsTge.Call(\"init\")\n\n\t// Instanciate Runtime\n\tbrowserRuntime := _runtimeInstance.(*browserRuntime)\n\tbrowserRuntime.app = app\n\tbrowserRuntime.canvas = &canvas\n\tbrowserRuntime.jsTge = &jsTge\n\tbrowserRuntime.settings = settings\n\tbrowserRuntime.isPaused = true\n\tbrowserRuntime.isStopped = true\n\tbrowserRuntime.done = make(chan bool)\n\n\t// Init plugins\n\tinitPlugins()\n\n\t// Start App\n\terr = app.OnStart(browserRuntime)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tpanic(err)\n\t}\n\tbrowserRuntime.isStopped = false\n\n\t// Resume App\n\tapp.OnResume()\n\tbrowserRuntime.isPaused = false\n\n\t// Resize App\n\tpublish(ResizeEvent{int32(browserRuntime.canvas.Get(\"clientWidth\").Int()),\n\t\tint32(browserRuntime.canvas.Get(\"clientHeight\").Int())})\n\n\t// -------------------------------------------------------------------- //\n\t// Ticker Loop\n\t// -------------------------------------------------------------------- //\n\tsyncChan := make(chan interface{})\n\telapsedTpsTime := time.Duration(0)\n\tgo func() {\n\t\tfor !browserRuntime.isStopped {\n\t\t\tif !browserRuntime.isPaused {\n\t\t\t\tnow := time.Now()\n\t\t\t\tapp.OnTick(elapsedTpsTime, syncChan)\n\t\t\t\telapsedTpsTime = time.Since(now)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// -------------------------------------------------------------------- //\n\t// Callbacks\n\t// -------------------------------------------------------------------- //\n\n\t// Resize\n\tresizeEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif !browserRuntime.isStopped {\n\t\t\tw := int32(browserRuntime.canvas.Get(\"clientWidth\").Int())\n\t\t\th := int32(browserRuntime.canvas.Get(\"clientHeight\").Int())\n\t\t\tjsTge.Call(\"resize\", w, h)\n\t\t\tpublish(ResizeEvent{\n\t\t\t\tWidth: w,\n\t\t\t\tHeight: h,\n\t\t\t})\n\t\t}\n\t\treturn false\n\t})\n\tdefer resizeEvtCb.Release()\n\tjs.Global().Call(\"addEventListener\", \"resize\", resizeEvtCb)\n\n\t// Focus\n\tblurEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\tgo func() {\n\t\t\t\tbrowserRuntime.isPaused = true\n\t\t\t\tbrowserRuntime.app.OnPause()\n\t\t\t}()\n\t\t}\n\t\treturn false\n\t})\n\tdefer blurEvtCb.Release()\n\tbrowserRuntime.canvas.Call(\"addEventListener\", \"blur\", blurEvtCb)\n\n\tfocuseEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif !browserRuntime.isStopped && browserRuntime.isPaused {\n\t\t\t//Called in go routine in case of asset loading in resume (blocking)\n\t\t\tgo func() {\n\t\t\t\tbrowserRuntime.app.OnResume()\n\t\t\t\tbrowserRuntime.isPaused = false\n\t\t\t}()\n\t\t}\n\t\treturn false\n\t})\n\tdefer focuseEvtCb.Release()\n\tbrowserRuntime.canvas.Call(\"addEventListener\", \"focus\", focuseEvtCb)\n\n\t// Destroy\n\tbeforeunloadEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif !browserRuntime.isStopped {\n\t\t\tbrowserRuntime.Stop()\n\t\t}\n\t\treturn false\n\t})\n\tdefer beforeunloadEvtCb.Release()\n\tjs.Global().Call(\"addEventListener\", \"beforeunload\", beforeunloadEvtCb)\n\n\t// MouseButtonEvent\n\tif (settings.EventMask & MouseButtonEventEnabled) != 0 {\n\t\tmouseDownEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tbutton := ButtonNone\n\t\t\t\tswitch event.Get(\"button\").Int() {\n\t\t\t\tcase 0:\n\t\t\t\t\tbutton = ButtonLeft\n\t\t\t\tcase 1:\n\t\t\t\t\tbutton = ButtonMiddle\n\t\t\t\tcase 2:\n\t\t\t\t\tbutton = ButtonRight\n\t\t\t\t}\n\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\tX: int32(event.Get(\"offsetX\").Int()),\n\t\t\t\t\tY: int32(event.Get(\"offsetY\").Int()),\n\t\t\t\t\tButton: button,\n\t\t\t\t\tType: TypeDown,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer mouseDownEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"mousedown\", mouseDownEvtCb)\n\n\t\ttouchDownEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\ttouchList := event.Get(\"touches\")\n\t\t\t\ttouchListLen := touchList.Get(\"length\").Int()\n\t\t\t\tfor i := 0; i < touchListLen; i++ {\n\t\t\t\t\tbutton := ButtonNone\n\t\t\t\t\tswitch i {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tbutton = TouchFirst\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tbutton = TouchSecond\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tbutton = TouchThird\n\t\t\t\t\t}\n\t\t\t\t\ttouch := touchList.Index(i)\n\t\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\t\tX: int32(touch.Get(\"clientX\").Int()),\n\t\t\t\t\t\tY: int32(touch.Get(\"clientY\").Int()),\n\t\t\t\t\t\tButton: button,\n\t\t\t\t\t\tType: TypeDown,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer touchDownEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"touchstart\", touchDownEvtCb)\n\n\t\tmouseUpEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tbutton := ButtonNone\n\t\t\t\tswitch event.Get(\"button\").Int() {\n\t\t\t\tcase 0:\n\t\t\t\t\tbutton = ButtonLeft\n\t\t\t\tcase 1:\n\t\t\t\t\tbutton = ButtonMiddle\n\t\t\t\tcase 2:\n\t\t\t\t\tbutton = ButtonRight\n\t\t\t\t}\n\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\tX: int32(event.Get(\"offsetX\").Int()),\n\t\t\t\t\tY: int32(event.Get(\"offsetY\").Int()),\n\t\t\t\t\tButton: button,\n\t\t\t\t\tType: TypeUp,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer mouseUpEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"mouseup\", mouseUpEvtCb)\n\n\t\ttouchUpEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\ttouchList := event.Get(\"changedTouches\")\n\t\t\t\ttouchListLen := touchList.Get(\"length\").Int()\n\t\t\t\tfor i := 0; i < touchListLen; i++ {\n\t\t\t\t\tbutton := ButtonNone\n\t\t\t\t\tswitch i {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tbutton = TouchFirst\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tbutton = TouchSecond\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tbutton = TouchThird\n\t\t\t\t\t}\n\t\t\t\t\ttouch := touchList.Index(i)\n\t\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\t\tX: int32(touch.Get(\"clientX\").Int()),\n\t\t\t\t\t\tY: int32(touch.Get(\"clientY\").Int()),\n\t\t\t\t\t\tButton: button,\n\t\t\t\t\t\tType: TypeUp,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer touchUpEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"touchend\", touchUpEvtCb)\n\t}\n\n\t// MouseMotionEventEnabled\n\tif (settings.EventMask & MouseMotionEventEnabled) != 0 {\n\t\tmouseMoveEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\tX: int32(event.Get(\"clientX\").Int()),\n\t\t\t\t\tY: int32(event.Get(\"clientY\").Int()),\n\t\t\t\t\tButton: ButtonNone,\n\t\t\t\t\tType: TypeMove,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer mouseMoveEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"mousemove\", mouseMoveEvtCb)\n\n\t\ttouchMoveEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\ttouchList := event.Get(\"touches\")\n\t\t\t\ttouchListLen := touchList.Get(\"length\").Int()\n\t\t\t\tfor i := 0; i < touchListLen; i++ {\n\t\t\t\t\tbutton := ButtonNone\n\t\t\t\t\tswitch i {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tbutton = TouchFirst\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tbutton = TouchSecond\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tbutton = TouchThird\n\t\t\t\t\t}\n\t\t\t\t\ttouch := touchList.Index(i)\n\t\t\t\t\tpublish(MouseEvent{\n\t\t\t\t\t\tX: int32(touch.Get(\"clientX\").Int()),\n\t\t\t\t\t\tY: int32(touch.Get(\"clientY\").Int()),\n\t\t\t\t\t\tButton: button,\n\t\t\t\t\t\tType: TypeMove,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer touchMoveEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"touchmove\", touchMoveEvtCb)\n\t}\n\n\t// ScrollEvent\n\tif (settings.EventMask & ScrollEventEnabled) != 0 {\n\t\twheelEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\tx := float64(event.Get(\"deltaX\").Int())\n\t\t\t\ty := float64(event.Get(\"deltaY\").Int())\n\t\t\t\tif x != 0 {\n\t\t\t\t\tx = x / math.Abs(x)\n\t\t\t\t}\n\t\t\t\tif y != 0 {\n\t\t\t\t\ty = y / math.Abs(y)\n\t\t\t\t}\n\t\t\t\tpublish(ScrollEvent{\n\t\t\t\t\tX: int32(x),\n\t\t\t\t\tY: -int32(y),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer wheelEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"wheel\", wheelEvtCb)\n\t}\n\n\t// KeyEvent\n\tif (settings.EventMask & KeyEventEnabled) != 0 {\n\t\tkeyDownEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\tkeyCode := event.Get(\"key\").String()\n\t\t\t\tpublish(KeyEvent{\n\t\t\t\t\tKey: keyMap[keyCode],\n\t\t\t\t\tValue: keyCode,\n\t\t\t\t\tType: TypeDown,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer keyDownEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"keydown\", keyDownEvtCb)\n\n\t\tkeyUpEvtCb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tif !browserRuntime.isStopped && !browserRuntime.isPaused {\n\t\t\t\tevent := args[0]\n\t\t\t\tevent.Call(\"preventDefault\")\n\t\t\t\tkeyCode := event.Get(\"key\").String()\n\t\t\t\tpublish(KeyEvent{\n\t\t\t\t\tKey: keyMap[keyCode],\n\t\t\t\t\tValue: keyCode,\n\t\t\t\t\tType: TypeUp,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tdefer keyUpEvtCb.Release()\n\t\tbrowserRuntime.canvas.Call(\"addEventListener\", \"keyup\", keyUpEvtCb)\n\t}\n\n\t// -------------------------------------------------------------------- //\n\t// Render Loop\n\t// -------------------------------------------------------------------- //\n\tvar renderFrame js.Func\n\telapsedFpsTime := time.Duration(0)\n\trenderFrame = js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif !browserRuntime.isPaused {\n\t\t\tnow := time.Now()\n\t\t\tapp.OnRender(elapsedFpsTime, syncChan)\n\t\t\telapsedFpsTime = time.Since(now)\n\t\t}\n\t\tif !browserRuntime.isStopped {\n\t\t\tjs.Global().Call(\"requestAnimationFrame\", renderFrame)\n\t\t} else {\n\t\t\tbrowserRuntime.done <- true\n\t\t}\n\t\treturn false\n\t})\n\tjs.Global().Call(\"requestAnimationFrame\", renderFrame)\n\n\t<-browserRuntime.done\n\n\trenderFrame.Release()\n\tjsTge.Call(\"stop\")\n\n\tnoExit := make(chan int)\n\t<-noExit\n\n\treturn nil\n}", "func main() {\n\t// Initialize the library.\n\tctx := glfw.Init()\n\tif ctx == nil {\n\t\tpanic(\"failed to initialize GLFW\")\n\t}\n\tdefer ctx.Terminate()\n\n\t// Create a windowed mode window and its OpenGL context.\n\twin := ctx.CreateWindow(640, 480, \"Hello World\", nil, nil)\n\tif win == nil {\n\t\tpanic(\"failed to create window\")\n\t}\n\tdefer win.Destroy()\n\n\t// Make the window's context current.\n\tctx.MakeContextCurrent(win)\n\n\t// Loop until the user closes the window.\n\tfor !win.ShouldClose() {\n\t\t// Render here.\n\n\t\t// Swap front and back buffers.\n\t\twin.SwapBuffers()\n\n\t\t// Poll for and process events.\n\t\tctx.PollEvents()\n\t}\n}", "func (a *Application) Run() error {\n\tvar err error\n\ta.Lock()\n\n\t// Make a screen if there is none yet.\n\tif a.screen == nil {\n\t\ta.screen, err = tcell.NewScreen()\n\t\tif err != nil {\n\t\t\ta.Unlock()\n\t\t\treturn err\n\t\t}\n\t\tif err = a.screen.Init(); err != nil {\n\t\t\ta.Unlock()\n\t\t\treturn err\n\t\t}\n\t\tif a.enableMouse {\n\t\t\ta.screen.EnableMouse()\n\t\t}\n\t}\n\n\t// We catch panics to clean up because they mess up the terminal.\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\tif a.screen != nil {\n\t\t\t\ta.screen.Fini()\n\t\t\t}\n\t\t\tpanic(p)\n\t\t}\n\t}()\n\n\t// Draw the screen for the first time.\n\ta.Unlock()\n\ta.draw()\n\n\t// Separate loop to wait for screen events.\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\ta.RLock()\n\t\t\tscreen := a.screen\n\t\t\ta.RUnlock()\n\t\t\tif screen == nil {\n\t\t\t\t// We have no screen. Let's stop.\n\t\t\t\ta.QueueEvent(nil)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Wait for next event and queue it.\n\t\t\tevent := screen.PollEvent()\n\t\t\tif event != nil {\n\t\t\t\t// Regular event. Queue.\n\t\t\t\ta.QueueEvent(event)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// A screen was finalized (event is nil). Wait for a new scren.\n\t\t\tscreen = <-a.screenReplacement\n\t\t\tif screen == nil {\n\t\t\t\t// No new screen. We're done.\n\t\t\t\ta.QueueEvent(nil)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// We have a new screen. Keep going.\n\t\t\ta.Lock()\n\t\t\ta.screen = screen\n\t\t\ta.Unlock()\n\n\t\t\t// Initialize and draw this screen.\n\t\t\tif err := screen.Init(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif a.enableMouse {\n\t\t\t\tscreen.EnableMouse()\n\t\t\t}\n\t\t\ta.draw()\n\t\t}\n\t}()\n\n\t// Start event loop.\nEventLoop:\n\tfor {\n\t\tselect {\n\t\tcase event := <-a.events:\n\t\t\tif event == nil {\n\t\t\t\tbreak EventLoop\n\t\t\t}\n\n\t\t\ta.RLock()\n\t\t\tp := a.focus\n\t\t\tinputCapture := a.inputCapture\n\t\t\tmouseCapture := a.mouseCapture\n\t\t\ttempMouseCapture := a.tempMouseCapture\n\t\t\tscreen := a.screen\n\t\t\troot := a.root\n\t\t\ta.RUnlock()\n\n\t\t\tswitch event := event.(type) {\n\t\t\tcase *tcell.EventKey:\n\t\t\t\t// Intercept keys.\n\t\t\t\tif inputCapture != nil {\n\t\t\t\t\tevent = inputCapture(event)\n\t\t\t\t\tif event == nil {\n\t\t\t\t\t\ta.draw()\n\t\t\t\t\t\tcontinue // Don't forward event.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Ctrl-C closes the application.\n\t\t\t\tif event.Key() == tcell.KeyCtrlC {\n\t\t\t\t\ta.Stop()\n\t\t\t\t}\n\n\t\t\t\t// Pass other key events to the currently focused primitive.\n\t\t\t\tif p != nil {\n\t\t\t\t\tif handler := p.InputHandler(); handler != nil {\n\t\t\t\t\t\thandler(event, func(p Primitive) {\n\t\t\t\t\t\t\ta.SetFocus(p)\n\t\t\t\t\t\t})\n\t\t\t\t\t\ta.draw()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase *tcell.EventResize:\n\t\t\t\t// Throttle resize events.\n\t\t\t\tif time.Since(a.lastResize) < ResizeEventThrottle {\n\t\t\t\t\t// Stop timer\n\t\t\t\t\tif a.throttleResize != nil && !a.throttleResize.Stop() {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-a.throttleResize.C:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tevent := event // Capture\n\n\t\t\t\t\t// Start timer\n\t\t\t\t\ta.throttleResize = time.AfterFunc(ResizeEventThrottle, func() {\n\t\t\t\t\t\ta.events <- event\n\t\t\t\t\t})\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ta.lastResize = time.Now()\n\n\t\t\t\tif screen == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tscreen.Clear()\n\n\t\t\t\t// Call afterResize handler if there is one.\n\t\t\t\tif a.afterResize != nil {\n\t\t\t\t\twidth, height := screen.Size()\n\t\t\t\t\ta.afterResize(width, height)\n\t\t\t\t}\n\n\t\t\t\ta.draw()\n\t\t\tcase *tcell.EventMouse:\n\t\t\t\tatX, atY := event.Position()\n\t\t\t\tbtn := event.Buttons()\n\n\t\t\t\tpstack := a.appendStackAtPoint(nil, atX, atY)\n\t\t\t\tvar punderMouse Primitive\n\t\t\t\tif len(pstack) > 0 {\n\t\t\t\t\tpunderMouse = pstack[len(pstack)-1]\n\t\t\t\t}\n\t\t\t\tvar ptarget Primitive\n\t\t\t\tif a.lastMouseBtn != 0 {\n\t\t\t\t\t// While a button is down, the same primitive gets events.\n\t\t\t\t\tptarget = a.lastMouseTarget\n\t\t\t\t}\n\t\t\t\tif ptarget == nil {\n\t\t\t\t\tptarget = punderMouse\n\t\t\t\t\tif ptarget == nil {\n\t\t\t\t\t\tptarget = root // Fallback to root.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ta.lastMouseTarget = ptarget\n\n\t\t\t\t// Calculate mouse actions.\n\t\t\t\tvar act MouseAction\n\t\t\t\tif atX != a.lastMouseX || atY != a.lastMouseY {\n\t\t\t\t\tact |= MouseMove\n\t\t\t\t\ta.lastMouseX = atX\n\t\t\t\t\ta.lastMouseY = atY\n\t\t\t\t}\n\t\t\t\tbtnDiff := btn ^ a.lastMouseBtn\n\t\t\t\tif btnDiff != 0 {\n\t\t\t\t\tif btn&btnDiff != 0 {\n\t\t\t\t\t\tact |= MouseDown\n\t\t\t\t\t}\n\t\t\t\t\tif a.lastMouseBtn&btnDiff != 0 {\n\t\t\t\t\t\tact |= MouseUp\n\t\t\t\t\t}\n\t\t\t\t\tif a.lastMouseBtn == tcell.Button1 && btn == 0 {\n\t\t\t\t\t\tif ptarget == punderMouse {\n\t\t\t\t\t\t\t// Only if Button1 and mouse up over same p.\n\t\t\t\t\t\t\tact |= MouseClick\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.lastMouseBtn = btn\n\t\t\t\t}\n\n\t\t\t\tevent2 := NewEventMouse(event, ptarget, a, act)\n\n\t\t\t\t// Intercept event.\n\t\t\t\tif tempMouseCapture != nil {\n\t\t\t\t\tevent2 = tempMouseCapture(event2)\n\t\t\t\t\tif event2 == nil {\n\t\t\t\t\t\ta.draw()\n\t\t\t\t\t\tcontinue // Don't forward event.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif mouseCapture != nil {\n\t\t\t\t\tevent2 = mouseCapture(event2)\n\t\t\t\t\tif event2 == nil {\n\t\t\t\t\t\ta.draw()\n\t\t\t\t\t\tcontinue // Don't forward event.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ptarget == punderMouse {\n\t\t\t\t\t// Observe mouse events inward (\"capture\")\n\t\t\t\t\tfor _, pp := range pstack {\n\t\t\t\t\t\t// If the primitive has this ObserveMouseEvent func.\n\t\t\t\t\t\tif pp, ok := pp.(interface {\n\t\t\t\t\t\t\tObserveMouseEvent(*EventMouse)\n\t\t\t\t\t\t}); ok {\n\t\t\t\t\t\t\tpp.ObserveMouseEvent(event2)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif handler := ptarget.MouseHandler(); handler != nil {\n\t\t\t\t\thandler(event2)\n\t\t\t\t\ta.draw()\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If we have updates, now is the time to execute them.\n\t\tcase updater := <-a.updates:\n\t\t\tupdater()\n\t\t}\n\t}\n\n\t// Wait for the event loop to finish.\n\twg.Wait()\n\ta.screen = nil\n\n\treturn nil\n}", "func (c *thickClient) Run() {\n\tpixelgl.Run(c.run)\n}", "func (s *scene) run(ctx context.Context, r *sdl.Renderer) chan error {\n\terrc := make(chan error)\n\tgo func() {\n\t\tdefer close(errc)\n\t\tfor range time.Tick(10 * time.Millisecond) {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tif err := s.paint(r); err != nil {\n\t\t\t\t\terrc <- err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn errc\n}", "func (ui *GUI) Run() {\n\tlog.Infof(\"GUI served on port %v.\", ui.cfg.GUIPort)\n\n\tgo func() {\n\t\tif err := ui.server.ListenAndServeTLS(ui.cfg.TLSCertFile,\n\t\t\tui.cfg.TLSKeyFile); err != nil &&\n\t\t\terr != http.ErrServerClosed {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n}", "func (w *windowImpl) winLoop() {\n\twinShow := time.NewTimer(time.Second)\nouter:\n\tfor {\n\t\tlog.Println(\"mobile window loop iteration\")\n\t\tselect {\n\t\tcase <-w.winClose:\n\t\t\tbreak outer\n\t\tcase f := <-w.runQueue:\n\t\t\tif w.app.gpu == nil {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t\tf.f()\n\t\t\tif f.done != nil {\n\t\t\t\tf.done <- true\n\t\t\t}\n\t\tcase <-winShow.C:\n\t\t\tif w.app.gpu == nil {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t\tw.sendWindowEvent(window.Show)\n\t\t}\n\t}\n}", "func Main(ctx context.Context, cancelFunc func(), title string, showMainWindow bool) error {\n\tlog.WithFields(log.Fields{\"title\": title, \"showMainWindow\": showMainWindow}).Info(\"Initializing GUI.\")\n\t// Note: ui.Main() calls any functions queued with ui.QueueMain() before the one we provide via parameter.\n\treturn ui.Main(func() {\n\t\twindowTitle = title\n\t\twindow = ui.NewWindow(windowTitle, 600, 50, false)\n\t\tapplyIconToWindow(window.Handle())\n\t\tapplyWindowStyle(window.Handle())\n\n\t\twindow.OnClosing(func(*ui.Window) bool {\n\t\t\tlog.Info(\"User tries to close the window.\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tpanelDownloadStatus = makeContent()\n\t\twindow.SetChild(panelDownloadStatus)\n\t\twindow.SetMargined(true)\n\n\t\tui.OnShouldQuit(func() bool {\n\t\t\tlog.Info(\"OnShouldQuit().\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tif showMainWindow {\n\t\t\tcenterWindow(window.Handle())\n\t\t\twindow.Show()\n\t\t\tcenterWindow(window.Handle())\n\t\t}\n\n\t\tgo updateProgressPeriodically(ctx)\n\n\t\tguiInitWaitGroup.Done()\n\t})\n}", "func MainLoop(fullScreen bool, slideshow bool) int {\n\tvar event sdl.Event\n\tvar src, dst sdl.Rect\n\tvar err error\n\tvar flags uint32 = sdl.WINDOW_SHOWN | sdl.WINDOW_RESIZABLE | sdl.WINDOW_ALLOW_HIGHDPI\n\n\t// Load the font library\n\tif err := ttf.Init(); err != nil {\n\t\tlogger.Warning(\"Unable to open font lib\")\n\t}\n\n\twindow.window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winDefaultHeight, winDefaultWidth, flags)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to create window: %s\\n\", err)\n\t\treturn 1\n\t}\n\tdefer window.window.Destroy()\n\n\t// Load resources\n\tif f, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {\n\t\ticon := filepath.Join(f, \"app\", \"icon.bmp\")\n\t\tif i, err := sdl.LoadBMP(icon); err == nil {\n\t\t\twindow.window.SetIcon(i)\n\t\t}\n\n\t\tfont := filepath.Join(f, \"app\", \"fonts\", \"opensans.ttf\")\n\t\twindow.font, err = ttf.OpenFont(font, 14)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"Unable to load \" + font)\n\t\t}\n\t\twindow.font.SetKerning(false)\n\n\t\tfont = filepath.Join(f, \"app\", \"fonts\", \"fontawesome.ttf\")\n\t\twindow.symbols, err = ttf.OpenFont(font, 64)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"Unable to load \" + font)\n\t\t}\n\t}\n\n\twindow.renderer, err = sdl.CreateRenderer(window.window, -1, sdl.RENDERER_ACCELERATED)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to create renderer: %s\\n\", err)\n\t\treturn 2\n\t}\n\tdefer window.renderer.Destroy()\n\n\twindow.displayInfo = false\n\twindow.displayLoading()\n\twindow.setTitle(slide.current+1, len(slide.list), curImg().path)\n\twindow.loadCurrentImage(false)\n\n\t// Declare if the image needs to be updated\n\tvar update = false\n\tvar running = true\n\n\tfor running {\n\t\tevent = sdl.WaitEvent()\n\t\tswitch t := event.(type) {\n\t\tcase *sdl.QuitEvent:\n\t\t\trunning = false\n\n\t\tcase *sdl.DropEvent:\n\t\t\tfileName := t.File\n\n\t\t\t// Check if picture already in list\n\t\t\tfound := false\n\t\t\tfor i := range slide.list {\n\t\t\t\tif slide.list[i].path == fileName {\n\t\t\t\t\tfound = true\n\t\t\t\t\tslide.current = i\n\t\t\t\t\tupdate = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tif err := addPic(fileName); err != nil {\n\t\t\t\t\tsdl.ShowSimpleMessageBox(sdl.MESSAGEBOX_INFORMATION, \"File dropped on window\", \"Cannot add \"+fileName, window.window)\n\t\t\t\t} else {\n\t\t\t\t\tslide.current = len(slide.list) - 1\n\t\t\t\t\tupdate = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t/*case *sdl.MouseMotionEvent:\n\t\t\tfmt.Printf(\"[%d ms] MouseMotion\\ttype:%d\\tid:%d\\tx:%d\\ty:%d\\txrel:%d\\tyrel:%d\\n\",\n\t\t\t\tt.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel)\n\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\tfmt.Printf(\"[%d ms] MouseButton\\ttype:%d\\tid:%d\\tx:%d\\ty:%d\\tbutton:%d\\tstate:%d\\n\",\n\t\t\t\tt.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State)*/\n\n\t\tcase *sdl.WindowEvent:\n\t\t\tif t.Event == sdl.WINDOWEVENT_RESIZED || t.Event == sdl.WINDOWEVENT_EXPOSED {\n\t\t\t\twindow.window.SetSize(t.Data1, t.Data2)\n\n\t\t\t\t// Display information of the image\n\t\t\t\twWidth, wHeight := window.window.GetSize()\n\n\t\t\t\tsrc = sdl.Rect{X: 0, Y: 0, W: curImg().W, H: curImg().H}\n\t\t\t\tfitWidth, fitHeight := utils.ComputeFitImage(uint32(wWidth), uint32(wHeight), uint32(curImg().W), uint32(curImg().H))\n\t\t\t\tdst = sdl.Rect{X: int32(wWidth/2 - int32(fitWidth)/2), Y: int32(wHeight/2 - int32(fitHeight)/2), W: int32(fitWidth), H: int32(fitHeight)}\n\n\t\t\t\twindow.renderer.Clear()\n\t\t\t\twindow.renderer.Copy(curImg().texture, &src, &dst)\n\t\t\t\twindow.renderer.Present()\n\n\t\t\t\tif window.displayInfo {\n\t\t\t\t\twindow.displayPictureInfo()\n\t\t\t\t\twindow.renderer.Present()\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *sdl.KeyboardEvent:\n\n\t\t\tif t.GetType() != sdl.KEYDOWN {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Get next or previous image\n\t\t\tif t.Repeat == 0 {\n\t\t\t\tif t.Keysym.Sym == sdl.K_LEFT {\n\t\t\t\t\tslide.current = utils.Mod((slide.current - 1), len(slide.list))\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_RIGHT {\n\t\t\t\t\tslide.current = utils.Mod((slide.current + 1), len(slide.list))\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_PAGEUP {\n\t\t\t\t\tif err := picture.RotateImage(curImg().path, picture.CounterClockwise); err != nil {\n\t\t\t\t\t\tlogger.Warning(err.Error())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresetImg(slide.current)\n\t\t\t\t\t}\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_PAGEDOWN {\n\t\t\t\t\tif err := picture.RotateImage(curImg().path, picture.Clockwise); err != nil {\n\t\t\t\t\t\tlogger.Warning(err.Error())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresetImg(slide.current)\n\t\t\t\t\t}\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == 102 { // F\n\n\t\t\t\t\tif window.fullscreen {\n\t\t\t\t\t\twindow.window.SetFullscreen(0)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Go fullscreen\n\t\t\t\t\t\twindow.window.SetFullscreen(sdl.WINDOW_FULLSCREEN_DESKTOP)\n\t\t\t\t\t}\n\t\t\t\t\twindow.fullscreen = !window.fullscreen\n\t\t\t\t} else if t.Keysym.Sym == 105 { // I\n\n\t\t\t\t\twindow.displayInfo = !window.displayInfo\n\t\t\t\t\tif window.displayInfo {\n\t\t\t\t\t\tfmt.Println(\"Toggle info: on\")\n\t\t\t\t\t\twindow.displayPictureInfo()\n\t\t\t\t\t\twindow.renderer.Present()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(\"Toggle info: off\")\n\t\t\t\t\t\tupdate = true\n\t\t\t\t\t}\n\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_ESCAPE {\n\n\t\t\t\t\tif window.fullscreen {\n\t\t\t\t\t\twindow.window.SetFullscreen(0)\n\t\t\t\t\t\twindow.fullscreen = false\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%d\\n\", t.Keysym.Sym)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif update {\n\t\t\twindow.loadCurrentImage(true)\n\t\t\tupdate = false\n\t\t}\n\t}\n\n\treturn 0\n}", "func (ui *ReplApp) Run() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // stops engine\n\n\t// start chat engine\n\tui.engine.Start(ctx)\n\t// start repl console\n\tui.console.Run(ctx)\n\n\tui.loop() // blocks until \"quit\"\n}", "func (tui *TUI) Run() error {\n\treturn tui.app.SetRoot(tui.window, true).Run()\n}", "func (g *Game) Start() {\n\tif minesweeper.IsDebug() {\n\t\tfmt.Println(\"Starting game...\")\n\t}\n\t// loop\n\tg.UI.StartRunning()\n\tfor g.UI.ShouldRun() {\n\t\tg.UI.ManageInput()\n\t\tg.updateState()\n\t\tg.UI.Draw(g.State.CurrentState, g.MaskedBoard)\n\t}\n}", "func mainLoop(ch chan int) {\n\tfmt.Println(\"Looping\")\n\n\tfor {\n\t\tfmt.Println(\"Updating world...\")\n\t\tupdate()\n\t\ttime.Sleep(updateInterval)\n\t}\n\tch <- 0\n}", "func (a *App) Run() error {\n\t// Run state updater\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo a.updater.Run(ctx)\n\ta.cancelStateUpdate = cancel\n\n\t// run gui\n\treturn a.gui.Run()\n}", "func Run() {\n\tlog.Printf(\"[%s] starting ui\", tag)\n\n\t// stream list\n\tstreamList := cview.NewList()\n\tstreamList.\n\t\tClear().\n\t\tSetHighlightFullLine(true).\n\t\tShowSecondaryText(false).\n\t\tSetBorder(true).\n\t\tSetBorderColor(tcell.ColorBlue).\n\t\tSetTitle(\" 📻 streams \").\n\t\tSetTitleAlign(cview.AlignLeft)\n\n\tfor _, stationID := range streams.StreamStationIDs {\n\t\tstreamList.AddItem(streams.Streams[stationID].Stream, \"\", 0, nil)\n\t}\n\n\t// now playing\n\tnowplaying := cview.NewTextView()\n\tnowplaying.\n\t\tSetText(\"...\").\n\t\tSetTextAlign(cview.AlignCenter).\n\t\tSetTitle(\" 🎵 now playing \").\n\t\tSetTitleAlign(cview.AlignLeft).\n\t\tSetBorderColor(tcell.ColorOrange).\n\t\tSetBorder(true)\n\n\tstreamList.SetSelectedFunc(func(idx int, maintext string, secondarytext string, shortcut rune) {\n\t\tlog.Printf(\"[%s] selected stream changed\", tag)\n\n\t\tstationID := streams.StreamStationIDs[idx]\n\t\turl := \"http:\" + streams.Streams[stationID].URLHigh\n\t\tnowplaying.SetText(streams.Streams[stationID].Stream)\n\n\t\tlog.Printf(\"[%s] playing %s from url %s\", tag, streams.Streams[stationID].Stream, url)\n\t\tplayer.Stop()\n\t\tplayer.Play(url)\n\t})\n\n\t// main layout\n\tflex := cview.NewFlex().\n\t\tSetDirection(cview.FlexRow).\n\t\tAddItem(streamList, 0, 1, true).\n\t\tAddItem(nowplaying, 3, 1, false)\n\n\tapp.SetInputCapture(handleKeyEvent)\n\tif err := app.SetRoot(flex, true).Run(); err != nil {\n\t\tlog.Fatalf(\"[%s] ui initialization failed: %d\", tag, err)\n\t}\n}", "func (v *Viewer) MainLoop() error {\n\tif err := v.display(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := keyboard.Open(); err != nil {\n\t\treturn err\n\t}\n\tdefer keyboard.Close()\n\n\tfor {\n\t\tchar, key, err := keyboard.GetKey()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif key == keyboard.KeyEsc || char == 'q' {\n\t\t\tfmt.Print(\"\\033[2J\")\n\t\t\tfmt.Print(\"\\033[0;0H\")\n\t\t\tif v.autoclose {\n\t\t\t\texec.Command(\"osascript\", \"-e\", `tell application \"iTerm\" to tell current tab of current window to close`).Start()\n\t\t\t}\n\t\t\tbreak\n\t\t} else if char == 'n' {\n\t\t\tv.nextDisplay()\n\t\t} else if char == 'p' {\n\t\t\tv.prevDisplay()\n\t\t} else {\n\t\t\tfmt.Printf(\"You pressed: %q\\r\\n\", char)\n\t\t\tfmt.Println(key)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (gb *GameBoy) Run() {\n\t// Number of extra clocks consumed in the last tick.\n\tclockDebt := 0\n\n\tfor {\n\t\tselect {\n\n\t\tcase <-gb.clk.C:\n\t\t\tclockDebt = gb.RunClocks(CPUClock/BaseClock - clockDebt)\n\n\t\tcase event := <-gb.events:\n\t\t\tgb.jp.Handle(event)\n\n\t\tcase frame := <-gb.ppu.F:\n\t\t\tselect {\n\t\t\tcase gb.F <- frame:\n\t\t\tdefault:\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (q *EventQueue) Run() {\n\tif q.notSafeToAccess() {\n\t\treturn\n\t}\n\n\tgo q.run()\n}", "func (g *Game) Run() {\n\n\tgo g.handleGameUpdates()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase userJoined := <-g.OnUserJoined:\n\t\t\t\tlog.Info(\"Received UserJoinged message\")\n\t\t\t\tg.handleUserJoined(userJoined.User)\n\n\t\t\tcase userQuit := <-g.OnUserQuit:\n\t\t\t\tlog.WithField(\"user\", userQuit.User).Info(\"Received UserQuit message\")\n\t\t\t\tg.handleUserQuit(userQuit.User)\n\n\t\t\tcase msg := <-g.onMessageReceived:\n\t\t\t\tswitch message := msg.(type) {\n\t\t\t\tcase *m.Message:\n\t\t\t\t\t// attach current character if a user is set\n\t\t\t\t\tg.attachCharacterToMessage(message)\n\n\t\t\t\t\t// only broadcast if global commandprocessor didnt process it\n\t\t\t\t\tif !g.CommandProcessor.Process(g, message) {\n\t\t\t\t\t\t// check room commands\n\t\t\t\t\t\tif !g.RoomProcessor.Process(g, message) {\n\t\t\t\t\t\t\t// generic messages will be converted to plain OutgoingMessages (type message)\n\t\t\t\t\t\t\t// and send to the room audience including the origin nickname or charactername\n\t\t\t\t\t\t\tg.handleDefaultMessage(message)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func Run() {\n\t// Seed RNG\n\trand.Seed(time.Now().UnixNano())\n\n\t// Set up the game window\n\tebiten.SetWindowSize(640, 480)\n\tebiten.SetWindowTitle(\"Soup The Moon\")\n\n\tif util.IsRasPi() {\n\t\t// Set fullscreen\n\t\tebiten.SetFullscreen(true)\n\n\t\t// Hide cursor\n\t\tebiten.SetCursorMode(ebiten.CursorModeHidden)\n\n\t\t// Setup RPIO button input\n\t\tinput.InitPluto()\n\t\tinput.InitSaturn()\n\t\tinput.InitJupiter()\n\t\tinput.InitMars()\n\t\tinput.InitEarth()\n\t\tinput.InitMercury()\n\t\tinput.InitUp()\n\t\tinput.InitDown()\n\t\tinput.InitEnter()\n\t\tinput.InitBack()\n\t}\n\n\t// Run game\n\tif err := ebiten.RunGame(newGame(640, 480)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func lockMain(cb callback) {\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tgo cb()\n\tfor {\n\t\tselect {\n\t\tcase f := <-mainThread:\n\t\t\tf()\n\t\tcase <-mainDone:\n\t\t\treturn\n\t\t}\n\t}\n}", "func init() {\n\t// Locks the Execution in the main Thread as OpenGL is not thread Safe\n\truntime.LockOSThread()\n}", "func main() {\n\tgo func() {\n\t\tw := app.NewWindow(\n\t\t\tapp.Title(\"Gopher-Garden\"),\n\t\t\tapp.Size(unit.Dp(ui.WidthPx+500), unit.Dp(ui.HeightPx)))\n\t\tu := ui.NewUi(w)\n\t\tif err := u.Loop(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tos.Exit(0)\n\t}()\n\tapp.Main()\n}", "func (ftm *FtmBridge) run() {\n\tftm.wg.Add(1)\n\tgo ftm.observeBlocks()\n}", "func (app *Application) Start(acConstructor func() ClientApplication) {\n\twindowManager.Start()\n\n\trenderSystem.Start()\n\taudioSystem.Start()\n\tphysicsSystem.Start()\n\timguiSystem.Start()\n\n\tresourceManager.start()\n\n\t// create the client app\n\tapp.client = acConstructor()\n\n\t// step the windowsystem to force swap buffers before starting loop\n\twindowManager.window.SwapBuffers()\n\n\t// start main loop, all systems go\n\tapp.runLoop()\n\n\t// done\n\tresourceManager.stop()\n\n\timguiSystem.Stop()\n\tphysicsSystem.Stop()\n\taudioSystem.Stop()\n\trenderSystem.Stop()\n\n\tglfw.Terminate()\n}", "func (w *windowImpl) RunOnWin(f func()) {\n\tif w.IsClosed() {\n\t\treturn\n\t}\n\tdone := make(chan bool)\n\tw.runQueue <- funcRun{f: f, done: done}\n\t<-done\n}", "func (w *windowImpl) RunOnWin(f func()) {\n\tif w.IsClosed() {\n\t\treturn\n\t}\n\tdone := make(chan bool)\n\tw.runQueue <- funcRun{f: f, done: done}\n\t<-done\n}", "func Start(update func(float32), draw func()) error {\n\tcurrentWindow, windowErr := window.NewWindow()\n\tdefer window.Destroy()\n\tif windowErr != nil {\n\t\treturn windowErr\n\t}\n\tgfx.InitContext(currentWindow.Config.Width, currentWindow.Config.Height)\n\tdefer gfx.DeInit()\n\tif OnLoad != nil {\n\t\tOnLoad()\n\t}\n\tfor !window.ShouldClose() {\n\t\ttimer.Step()\n\t\tupdate(timer.GetDelta())\n\t\tgfx.ClearC(gfx.GetBackgroundColorC())\n\t\tgfx.Origin()\n\t\tdraw()\n\t\tgfx.Present()\n\t\tevent.Poll()\n\t}\n\treturn nil\n}", "func (d *Drawer) mainLoop() {\n\ttimer := time.After(FlushInterval)\n\tfor {\n\t\tselect {\n\t\tcase <-d.close:\n\t\t\treturn\n\t\tcase <-timer:\n\t\t\tif d.dirty {\n\t\t\t\terr := d.flush()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer = time.After(FlushInterval)\n\t\t}\n\t}\n}", "func (w *Window) Render() {\n\t// Signal to the graphics loop to render a frame.\n\tw.render <- struct{}{}\n\n\t// Wait for the render to complete.\n\t<-w.render\n}", "func (app *DockApp) Main() {\n\tapp.win.Map()\n\txevent.Main(app.x)\n}", "func runTUI() error {\n\n\t// Set function to manage all views and keybindings\n\tclientGui.SetManagerFunc(layout)\n\n\t// Bind keys with functions\n\t_ = clientGui.SetKeybinding(\"\", gocui.KeyCtrlC, gocui.ModNone, quit)\n\t_ = clientGui.SetKeybinding(\"input\", gocui.KeyEnter, gocui.ModNone, send)\n\n\t// Start main event loop of the TUI\n\treturn clientGui.MainLoop()\n}", "func (e *Emulator) Run() {\n\tdriver.Main(func(s screen.Screen) {\n\t\te.s = s\n\t\t// Calculate initial window size based on whatever our gutter/pixel pitch currently is.\n\t\tdims := e.matrixWithMarginsRect()\n\t\twopts := &screen.NewWindowOptions{\n\t\t\tTitle: \"RGB LED Matrix Emulator\",\n\t\t\tWidth: dims.Max.X,\n\t\t\tHeight: dims.Max.Y,\n\t\t}\n\t\tw, err := s.NewWindow(wopts)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\te.w = w\n\t\tfirstRender := true\n\t\tfor {\n\t\t\tevn := w.NextEvent()\n\t\t\tswitch evn := evn.(type) {\n\t\t\tcase key.Event:\n\t\t\t\tif evn.Code == key.CodeEscape {\n\t\t\t\t\te.Close()\n\t\t\t\t}\n\t\t\tcase paint.Event:\n\t\t\t\te.Render()\n\t\t\tcase size.Event:\n\t\t\t\tif evn.WidthPx == 0 && evn.HeightPx == 0 {\n\t\t\t\t\te.Close()\n\t\t\t\t}\n\t\t\t\te.sz = evn\n\t\t\t\tif firstRender {\n\t\t\t\t\te.Render()\n\t\t\t\t\tfirstRender = false\n\t\t\t\t}\n\t\t\tcase error:\n\t\t\t\tfmt.Println(\"render:\", err)\n\t\t\t}\n\t\t}\n\t})\n}", "func main () {\n\n\tstartGame() // start the game\n\n}", "func (t *tui) Run(done, ready chan bool) {\n\tt.ready = ready\n\n\tlog.Tracef(\"creating UI\")\n\tvar err error\n\tt.g, err = gotui.NewGui(gotui.Output256)\n\tif err != nil {\n\t\tlog.Criticalf(\"unable to create ui: %v\", err)\n\t\tos.Exit(2)\n\t}\n\tdefer t.g.Close()\n\n\tt.g.Cursor = true\n\tt.g.Mouse = t.client.Config.Client.UI.Mouse\n\n\tt.g.SetManagerFunc(t.layout)\n\tt.g.SetResizeFunc(t.onResize)\n\n\tlog.Tracef(\"adding keybindings\")\n\tif err := t.keybindings(t.g); err != nil {\n\t\tlog.Criticalf(\"ui couldn't create keybindings: %v\", err)\n\t\tos.Exit(2)\n\t}\n\n\tlog.Tracef(\"listening for signals\")\n\tt.listener = make(chan signal.Signal)\n\tgo t.listen()\n\tt.client.Env.AddListener(\"ui\", t.listener)\n\n\tlog.Tracef(\"running UI...\")\n\tif err := t.g.MainLoop(); err != nil && err != gotui.ErrQuit {\n\t\tt.errs.Close()\n\t\tlog.Criticalf(\"ui unexpectedly quit: %s: %s\", err, errgo.Details(err))\n\t\tfmt.Printf(\"Oh no! Something went very wrong :( Here's all we know: %s: %s\\n\", err, errgo.Details(err))\n\t\tfmt.Println(\"Your connections will all close gracefully and any logs properly closed out.\")\n\t}\n\tt.client.CloseAll()\n\tdone <- true\n}", "func (ui *jobCreatorUI) ShowAndRun() {\n\tif ui.window == nil {\n\t\tfmt.Errorf(\"Window of jobCreatorUI is nil!\")\n\t} else {\n\t\tui.window.ShowAll()\n\t}\n\tgtk.Main()\n}", "func (app *appImpl) RunOnMain(f func()) {\n\tif app.mainQueue == nil {\n\t\tf()\n\t} else {\n\t\tdone := make(chan bool)\n\t\tapp.mainQueue <- funcRun{f: f, done: done}\n\t\t<-done\n\t}\n}", "func (g *Game) Run(in <-chan sdl.Event, r *sdl.Renderer) <-chan Event {\n\tout := make(chan Event)\n\tgo func() {\n\t\tdefer close(out)\n\n\t\tg.reset()\n\n\t\ttick := time.Tick(10 * time.Millisecond)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tg.handleEvent(event)\n\t\t\tcase <-tick:\n\t\t\t\tif g.hasCollisions() {\n\t\t\t\t\tg.isGameOver = true\n\t\t\t\t}\n\n\t\t\t\tif !g.isGameOver {\n\t\t\t\t\tg.generatePipes()\n\t\t\t\t\tg.moveScene()\n\t\t\t\t\tg.updateScore()\n\t\t\t\t\tg.deleteHiddenPipes()\n\t\t\t\t} else {\n\t\t\t\t\tg.bird.Fall()\n\t\t\t\t}\n\n\t\t\t\tg.moveBird()\n\n\t\t\t\tif err := g.paint(r); err != nil {\n\t\t\t\t\tout <- &ErrorEvent{Err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif g.doesBirdHitsGround() && g.isGameOver {\n\t\t\t\t\tout <- &EndGameEvent{Score: g.score, BestScore: g.bestScore}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}()\n\treturn out\n}", "func (p *ControlPanel) RunWindow(opts *widget.RunWindowOptions) error {\n\tvar (\n\t\tnwo *screen.NewWindowOptions\n\t\tt *theme.Theme\n\t)\n\tif opts != nil {\n\t\tnwo = &opts.NewWindowOptions\n\t\tt = &opts.Theme\n\t}\n\tvar err error\n\tp.w, err = p.s.NewWindow(nwo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer p.w.Release()\n\n\tpaintPending := false\n\n\tgef := gesture.EventFilter{EventDeque: p.w}\n\tfor {\n\t\te := p.w.NextEvent()\n\n\t\tif e = gef.Filter(e); e == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch e := e.(type) {\n\t\tcase lifecycle.Event:\n\t\t\tp.root.OnLifecycleEvent(e)\n\t\t\tif e.To == lifecycle.StageDead {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase gesture.Event, mouse.Event:\n\t\t\tp.root.OnInputEvent(e, image.Point{})\n\n\t\tcase paint.Event:\n\t\t\tctx := &node.PaintContext{\n\t\t\t\tTheme: t,\n\t\t\t\tScreen: p.s,\n\t\t\t\tDrawer: p.w,\n\t\t\t\tSrc2Dst: f64.Aff3{\n\t\t\t\t\t1, 0, 0,\n\t\t\t\t\t0, 1, 0,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif err := p.root.Paint(ctx, image.Point{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.w.Publish()\n\t\t\tpaintPending = false\n\n\t\tcase size.Event:\n\t\t\tif dpi := float64(e.PixelsPerPt) * unit.PointsPerInch; dpi != t.GetDPI() {\n\t\t\t\tnewT := new(theme.Theme)\n\t\t\t\tif t != nil {\n\t\t\t\t\t*newT = *t\n\t\t\t\t}\n\t\t\t\tnewT.DPI = dpi\n\t\t\t\tt = newT\n\t\t\t}\n\n\t\t\twindowSize := e.Size()\n\t\t\tp.root.Measure(t, windowSize.X, windowSize.Y)\n\t\t\tp.root.Wrappee().Rect = e.Bounds()\n\t\t\tp.root.Layout(t)\n\t\t\t// TODO: call Mark(node.MarkNeedsPaint)?\n\n\t\tcase panelUpdate:\n\n\t\tcase error:\n\t\t\treturn e\n\t\t}\n\n\t\tif !paintPending && p.root.Wrappee().Marks.NeedsPaint() {\n\t\t\tpaintPending = true\n\t\t\tp.w.Send(paint.Event{})\n\t\t}\n\t}\n}", "func (e *Executor) Run() { e.loop() }", "func run(ctx context.Context) error {\n\t// Create the control channel on which the hub will push client control notyfications to the game\n\tcontrolCh := make(chan *model.ControlNotify)\n\t// Create the game\n\tgame := game.NewGameController(ctx, time.Millisecond*33, controlCh)\n\t// Create the hub\n\thub := core.NewWsHub(ctx, controlCh)\n\t// Create the server\n\tserver := server.NewServer(ctx)\n\n\t// Pass in callback functions the these objects\n\thub.SetRequestFn(game.Request) // the hub can call the game with arbitary client requests (login)\n\thub.SetLogoutFn(game.Logout) // the hub can call the game with when a conn is dropped, to remove the player\n\tgame.SetBroadcastFn(hub.BroadcastGameUpdate) // the game can call the hub to broadcast state update\n\tgame.SetConnStatusFn(hub.ChangeConnStatus) // the game can call the hub to change a connection's status (ingame)\n\tserver.SetConnectFn(hub.Connect) // the server can call the hub to add a new WebSocket connection (new client)\n\n\t// Start the game and the hub\n\tgame.Start()\n\thub.Start()\n\t// Start the server, return any error\n\treturn server.Start()\n}", "func (s *Service) renderMainWindow() error {\n\tif s.mainwin == nil {\n\t\tvar err error\n\t\ts.mainwin, err = gc.NewWindow(s.screenRows, s.screenCols, 0, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\ts.mainwin.Clear()\n\ts.mainwin.ColorOn(2)\n\ts.mainwin.MoveWindow(0, 0)\n\ts.mainwin.Resize(s.screenRows, s.screenCols)\n\ts.mainwin.Box(0, 0)\n\ts.mainwin.Refresh()\n\treturn nil\n}", "func (w *windowImpl) GoRunOnWin(f func()) {\n\tif w.IsClosed() {\n\t\treturn\n\t}\n\tgo func() {\n\t\tw.runQueue <- funcRun{f: f, done: nil}\n\t}()\n}", "func (w *windowImpl) GoRunOnWin(f func()) {\n\tif w.IsClosed() {\n\t\treturn\n\t}\n\tgo func() {\n\t\tw.runQueue <- funcRun{f: f, done: nil}\n\t}()\n}", "func main() {\n\tlog.Println(\"Done.\")\n\tapp.Run(func() error {\n\t\tw1 := NewWindow()\n\t\t//w1.Self = w1\n\t\tw1.SetObjID(\"window1\")\n\t\tw1.SetHints(gui.HintResizable)\n\t\tw1.Create(0, 0)\n\t\tw1.SetTitle(\"w1 resizable\")\n\t\tw1.Show()\n\t\t// w1.ToggleFullScreen()\n\t\tw1.Destroy()\n\t\tw2 := NewWindow()\n\t\tw2.SetObjID(\"window2\")\n\t\tw2.Create(200, 200)\n\t\tw2.SetTitle(\"w2 fixed\")\n\t\tw2.Show()\n\t\t// w2.ToggleFullScreen()\n\t\t// runtime.GC()\n\t\treturn nil\n\t}, nil)\n}", "func (l *LaunchControl) Run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tdefer cancel()\n\tch := make(chan Event, ReadBufferDepth)\n\twg := sync.WaitGroup{}\n\n\tfor i := 0; i < NumChannels; i++ {\n\t\tif err := l.Reset(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// The first swap enables double buffering.\n\t\tif err := l.SwapBuffers(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := l.SetTemplate(0); err != nil {\n\t\treturn err\n\t}\n\n\tlcfg := drivers.ListenConfig{\n\t\tTimeCode: false,\n\t\tActiveSense: false,\n\t\tSysEx: true,\n\t\tOnErr: func(err error) {\n\t\t\t_ = l.handleError(err)\n\t\t},\n\t}\n\n\tvar err error\n\tl.stopFn, err = l.inputDriver.Listen(func(msg []byte, milliseconds int32) {\n\t\tif len(msg) == 3 {\n\t\t\tch <- Event{\n\t\t\t\tTimestamp: milliseconds,\n\t\t\t\tStatus: msg[0],\n\t\t\t\tData1: msg[1],\n\t\t\t\tData2: msg[2],\n\t\t\t}\n\t\t} else {\n\t\t\tl.sysexEvent(msg)\n\t\t}\n\t}, lcfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase evt := <-ch:\n\t\t\t\tl.event(evt)\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tticker := time.NewTicker(FlashPeriod)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tl.lock.Lock()\n\t\t\t\tl.flashes++\n\t\t\t\tch := l.currentChannel\n\t\t\t\tl.lock.Unlock()\n\n\t\t\t\t_ = l.SwapBuffers(ch)\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-l.errorChan:\n\t\treturn err\n\t}\n}", "func (c *thickClient) run() {\n\t// Read in command line args\n\timageFilename := flag.String(\"im\", \"images/me.png\", \"image to pixelsound\")\n\tinputAudioFilename := flag.String(\"audio\", \"audio_inputs/my_name_is_doug_dimmadome.mp3\", \"audio file to use for pixelsound (if needed)\")\n\tmouse := flag.Bool(\"mouse\", false, \"use the mouse to play pixels instead of traverse function\")\n\tkeyboard := flag.Bool(\"keyboard\", false, \"use the keyboard to play pixels instead of traverse function\")\n\tqueue := flag.Bool(\"queue\", false, \"all pixels moused over or key pressed to are played sequentially, as opposed to the most recent pixel only\")\n\ttraverseFunc := flag.String(\"t\", \"TtoBLtoR\", \"traversal function to use\")\n\tsonifyFunc := flag.String(\"s\", \"SineColor\", \"sonification function to use\")\n\tflag.Parse()\n\n\t// Load image\n\tim, _, err := LoadImageFromFile(*imageFilename)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"unable to load image %s: %s\", *imageFilename, err))\n\t}\n\n\t// Resize image to pretty small\n\tim = resize.Resize(100, 0, im, resize.NearestNeighbor)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"unable to resize image: %s\", err))\n\t}\n\n\t// Configure UI window\n\tcfg := pixelgl.WindowConfig{\n\t\tTitle: \"Pixelsound\",\n\t\tBounds: pixel.R(0, 0, float64(im.Bounds().Max.X), float64(im.Bounds().Max.Y)),\n\t\tVSync: true,\n\t}\n\twin, err := pixelgl.NewWindow(cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"unable to create window: %s\", err))\n\t}\n\n\t// Start observing input\n\tgo MouseInput(win)\n\n\t// Create image sprite\n\tpd := pixel.PictureDataFromImage(im)\n\tsprite := pixel.NewSprite(pd, pd.Bounds())\n\n\t// Create imdraw\n\timd := imdraw.New(nil)\n\n\t// Setup necessary audio inputs\n\taudioFilename := *inputAudioFilename\n\tvar f *os.File\n\tvar ext string\n\tif audioFilename != \"\" {\n\t\tf, err = os.Open(audioFilename)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"unable to open file %s: %s\", audioFilename, err)\n\t\t}\n\t\tsplit := strings.Split(audioFilename, \".\")\n\t\text = strings.ToLower(split[len(split)-1])\n\t}\n\n\t// Create PixelSound player\n\tsr := beep.SampleRate(44100)\n\tplayer := player.NewPlayer(sr, 2048, player.WithPointChan())\n\n\t// Instantiate and play PixelSound\n\tt, ok := traversal.TraverseFuncs[*traverseFunc]\n\tif !ok {\n\t\tlog.Fatalf(\"no traversal function named %s\", *traverseFunc)\n\t}\n\t_, ok = sonification.SonifyFuncNames[*sonifyFunc]\n\tif !ok {\n\t\tlog.Fatalf(\"no sonification function named %s\", *sonifyFunc)\n\t}\n\tvar s api.SonifyFunc\n\tswitch *sonifyFunc {\n\tcase \"SineColor\":\n\t\ts = sonification.NewSineColor(sr)\n\tcase \"AudioScrubber\":\n\t\ts = sonification.NewAudioScrubber(f, ext)\n\t}\n\tps := &api.PixelSounder{\n\t\tT: t,\n\t\tS: s,\n\t}\n\tplayer.SetImagePixelSound(im, ps)\n\n\t// PLAY W/MOUSE\n\tif *mouse {\n\t\t// Register play pixel on mouse movement\n\t\tstop := OnMouseMove(func(p pixel.Vec) {\n\t\t\tplayer.PlayPixel(convertPixelToImage(win, p), *queue)\n\t\t})\n\t\tdefer stop()\n\t} else if *keyboard {\n\t\t// Setup play pixel by arrow keys\n\t\tkeyboardPixelLocation := pixel.Vec{\n\t\t\tX: 0,\n\t\t\tY: win.Bounds().Max.Y,\n\t\t}\n\n\t\t// LEFT ARROW\n\t\tstopL := OnKeyPress(pixelgl.KeyLeft, func(b pixelgl.Button) {\n\t\t\tnewX := keyboardPixelLocation.X - 1\n\t\t\tif newX < 0 {\n\t\t\t\tnewX = win.Bounds().Max.X\n\t\t\t}\n\t\t\tkeyboardPixelLocation.X = newX\n\t\t\tplayer.PlayPixel(convertPixelToImage(win, keyboardPixelLocation), *queue)\n\t\t}, true)\n\t\tdefer stopL()\n\n\t\t// RIGHT ARROW\n\t\tstopR := OnKeyPress(pixelgl.KeyRight, func(b pixelgl.Button) {\n\t\t\tnewX := keyboardPixelLocation.X + 1\n\t\t\tif newX > win.Bounds().Max.X {\n\t\t\t\tnewX = 0\n\t\t\t}\n\t\t\tkeyboardPixelLocation.X = newX\n\t\t\tplayer.PlayPixel(convertPixelToImage(win, keyboardPixelLocation), *queue)\n\t\t}, true)\n\t\tdefer stopR()\n\n\t\t// UP ARROW\n\t\tstopU := OnKeyPress(pixelgl.KeyUp, func(b pixelgl.Button) {\n\t\t\tnewY := keyboardPixelLocation.Y + 1\n\t\t\tif newY > win.Bounds().Max.Y {\n\t\t\t\tnewY = 0\n\t\t\t}\n\t\t\tkeyboardPixelLocation.Y = newY\n\t\t\tplayer.PlayPixel(convertPixelToImage(win, keyboardPixelLocation), *queue)\n\t\t}, true)\n\t\tdefer stopU()\n\n\t\t// DOWN ARROW\n\t\tstopD := OnKeyPress(pixelgl.KeyDown, func(b pixelgl.Button) {\n\t\t\tnewY := keyboardPixelLocation.Y - 1\n\t\t\tif newY < 0 {\n\t\t\t\tnewY = win.Bounds().Max.Y\n\t\t\t}\n\t\t\tkeyboardPixelLocation.Y = newY\n\t\t\tplayer.PlayPixel(convertPixelToImage(win, keyboardPixelLocation), *queue)\n\t\t}, true)\n\t\tdefer stopD()\n\t} else { // PLAY W/TRAVERSAL\n\t\tplayer.Play(im, ps, image.Point{0, 0})\n\t}\n\n\t// Draw initial picture\n\tsprite.Draw(win, pixel.IM.Moved(win.Bounds().Center()))\n\n\t// UI main loop\n\tfor !win.Closed() {\n\t\tselect {\n\t\tcase point := <-player.PointChan:\n\t\t\tDrawImage(win, sprite, imd, im.At(point.X, point.Y), point)\n\t\tdefault:\n\t\t}\n\t\twin.Update()\n\t\tMouseInput(win)\n\t\tKeyboardUpdate(win)\n\t}\n}", "func (gb *GameBoy) Run() {\n\tif err := gb.APU.Start(); err != nil {\n\t\tpanic(err)\n\t}\n\tdsTick := false\n\tfor {\n\t\tselect {\n\t\tcase _, _ = <-gb.exitChan:\n\t\t\tgb.APU.Stop()\n\t\t\treturn\n\t\tdefault:\n\t\t\tgb.Timer.Prepare()\n\t\t\tgb.CPU.Step()\n\t\t\tgb.MMU.Step()\n\t\t\tgb.Timer.Step()\n\t\t\tgb.Serial.Step()\n\t\t\tif !dsTick {\n\t\t\t\tgb.APU.Step()\n\t\t\t\tgb.PPU.Step()\n\t\t\t\tdsTick = gb.CPU.DoubleSpeed()\n\t\t\t} else {\n\t\t\t\tdsTick = false\n\t\t\t}\n\t\t}\n\t}\n}", "func loop() {\n\n\tcfg := pixelgl.WindowConfig{\n\t\tTitle: \"Life...finds a way.\",\n\t\tBounds: winBounds,\n\t\tVSync: true,\n\t}\n\twin, err := pixelgl.NewWindow(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// sprite creation\n\tredPic := p.MakePictureData(p.R(0, 0, 1, 1))\n\tredPic.Pix[0] = colornames.Red\n\tred := p.NewSprite(redPic, redPic.Bounds())\n\n\tbatch := p.NewBatch(&p.TrianglesData{}, redPic)\n\n\t// game state\n\tboard := g.Patterns[initPattern]\n\tpaused := false\n\titerations := 0\n\n\t// update the game state (board) every iterWait duration\n\t// independently of the graphical draw loop\n\tgo func() {\n\t\twait := time.NewTicker(iterWait)\n\t\tfor !win.Closed() {\n\t\t\tselect {\n\t\t\tcase <-wait.C:\n\t\t\t\tif !paused {\n\t\t\t\t\tboard = g.Advance(board)\n\t\t\t\t\titerations++\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t\twait.Stop()\n\t}()\n\n\t// various state for drawing\n\tcam := camera{Position: p.ZV, Speed: 250.0, Zoom: 1.0, ZSpeed: 1.1}\n\tframes := 0\n\tsecond := time.Tick(time.Second)\n\tlast := time.Now()\n\n\tfor !win.Closed() {\n\t\tdt := time.Since(last).Seconds()\n\t\tlast = time.Now()\n\n\t\tcamMatrix := p.IM.\n\t\t\tScaled(cam.Position, cam.Zoom).\n\t\t\tMoved(win.Bounds().Center().Sub(cam.Position))\n\t\twin.SetMatrix(camMatrix)\n\n\t\t// update user controlled things\n\t\tif win.Pressed(pixelgl.KeyLeft) {\n\t\t\tcam.Position.X -= cam.Speed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyRight) {\n\t\t\tcam.Position.X += cam.Speed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyDown) {\n\t\t\tcam.Position.Y -= cam.Speed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyUp) {\n\t\t\tcam.Position.Y += cam.Speed * dt\n\t\t}\n\t\tif win.JustPressed(pixelgl.KeySpace) {\n\t\t\tpaused = !paused\n\t\t}\n\t\t// win.SetTitle(fmt.Sprintf(\"Mouse (%.2f, %.2f)\", mouse.X, mouse.Y))\n\t\tif win.JustPressed(pixelgl.MouseButtonLeft) && paused {\n\t\t\t// toggle a point's existence.\n\t\t\t// use Round to change mouse floats to ints. Simple\n\t\t\t// truncation will often place dot in wrong spot since\n\t\t\t// Pixel uses the sprite's center as it's position.\n\t\t\tmouse := camMatrix.Unproject(win.MousePosition())\n\t\t\tpoint := g.Point{round(mouse.X), round(mouse.Y)}\n\t\t\tif board[point] {\n\t\t\t\tdelete(board, point)\n\t\t\t} else {\n\t\t\t\tboard[point] = true\n\t\t\t}\n\t\t}\n\t\tif win.JustPressed(pixelgl.MouseButtonRight) && paused {\n\t\t\t// allow user to increment the board state 1 iteration\n\t\t\tboard = g.Advance(board)\n\t\t\titerations++\n\t\t}\n\t\tcam.Zoom *= math.Pow(cam.ZSpeed, win.MouseScroll().Y)\n\n\t\t// render game state\n\t\tbatch.Clear()\n\t\tfor point := range board {\n\t\t\tred.Draw(batch, p.IM.Moved(pToV(point)))\n\t\t}\n\n\t\t// draw\n\t\tif paused {\n\t\t\twin.Clear(colornames.Lightgray)\n\t\t} else {\n\t\t\twin.Clear(colornames.White)\n\t\t}\n\t\tbatch.Draw(win)\n\t\twin.Update()\n\n\t\t// various metrics in titlebar\n\t\tframes++\n\t\tselect {\n\t\tcase <-second:\n\t\t\twin.SetTitle(fmt.Sprintf(\n\t\t\t\t\"%s | FPS: %d | Paused: %v | %d cells %d iterations\",\n\t\t\t\tcfg.Title, frames, paused, len(board), iterations))\n\t\t\tframes = 0\n\t\tdefault:\n\t\t}\n\t}\n}", "func (v *Viewer) Run(ctx context.Context) {\n\tv.ui.Run()\n}", "func gameLoop() {\n\tlast := time.Now()\n\tfor !global.gWin.Closed() {\n\t\tdt := time.Since(last).Seconds()\n\t\tlast = time.Now()\n\n\t\tglobal.gWin.Clear(global.gClearColor)\n\n\t\t// Update systems\n\n\t\tglobal.gController.Update(dt)\n\t\tglobal.gCamera.Update(dt)\n\t\tglobal.gWorld.Draw(dt)\n\n\t\tglobal.gWin.Update()\n\t}\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 (g *Game) Run() error {\n\tg.state = sRunning\n\n\t// TODO randomly (totally or from set of criteria) select a maze\n\t// TODO would be nice to able to dynamically create one!\n\tif err := g.importMaze(mazes[2]); err != nil {\n\t\treturn errors.WithMessage(err, \"failed to import maze\")\n\t}\n\n\tfor {\n\t\tif !debug.Debug {\n\t\t\tterminal.Clear()\n\t\t}\n\n\t\tif g.state == sWin {\n\t\t\tg.Msg = \"You won!\"\n\t\t}\n\n\t\tif err := g.updateView(); err != nil {\n\t\t\treturn errors.WithMessage(err, \"failed to update view\")\n\t\t}\n\n\t\tviewport, err := g.render()\n\t\tif err != nil {\n\t\t\treturn errors.WithMessage(err, \"failed to render scene\")\n\t\t}\n\t\tfmt.Print(viewport)\n\n\t\tif g.state == sWin {\n\t\t\tdebug.Println(\"Game was won\")\n\t\t\treturn nil\n\t\t}\n\n\t\treader := bufio.NewReader(os.Stdin)\n\n\t\tchar, _, err := reader.ReadRune()\n\t\tif err != nil {\n\t\t\treturn errors.WithMessage(err, \"error reading rune from terminal\")\n\t\t}\n\n\t\t// TODO remove need to hit return!\n\n\t\tswitch char {\n\t\tcase 'w':\n\t\t\tdebug.Println(\"Move forward\")\n\t\t\tg.moveForward()\n\t\t\tbreak\n\t\tcase 's':\n\t\t\tdebug.Println(\"Move backward\")\n\t\t\tg.moveBackwards()\n\t\t\tbreak\n\t\tcase 'd':\n\t\t\tdebug.Println(\"Turn right\")\n\t\t\tg.rotateRight()\n\t\t\tbreak\n\t\tcase 'a':\n\t\t\tdebug.Println(\"Turn left\")\n\t\t\tg.rotateLeft()\n\t\t\tbreak\n\t\tcase 'q':\n\t\t\tdebug.Println(\"Exiting game\")\n\t\t\tfmt.Println(\"Goodbye!\")\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tg.Msg = \"Sorry, I didn't understand that one!\"\n\t\t}\n\t\tdebug.Printf(\"Player is now at (%v). Facing (%c)\\n\", g.player.p, g.player.o)\n\t}\n}", "func (a *App) Run() error {\n\tdirs := generateDirectories(a.Config.Directories, a.Config.Depth)\n\tif a.Config.QuickMode {\n\t\treturn a.execQuickMode(dirs)\n\t}\n\t// create a gui.Gui struct and run the gui\n\tgui, err := gui.New(a.Config.Mode, dirs)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn gui.Run()\n}", "func MainLoop() {\n\t// Backend socket talks to workers over inproc\n\tbackend, _ := zmq.NewSocket(zmq.DEALER)\n\tdefer backend.Close()\n\tbackend.Bind(\"inproc://backend\")\n\n\t// Launch pool of worker threads, precise number is not critical\n\tfor i := 0; i < 5; i++ {\n\t\tgo eventHandler()\n\t}\n\n\t// Connect backend to frontend via a proxy\n\terr := zmq.Proxy(frontend, backend, nil)\n\tlog.Fatalln(\"Proxy interrupted:\", err)\n}", "func main() {\n\tfmt.Println(\"Starting...\")\n\t// TODO: Init only the needed subsystems\n\tif err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {\n\t\tpanic(err)\n\t}\n\tdefer sdl.Quit()\n\n\t//var gameController *sdl.Joystick\n\tif sdl.NumJoysticks() < 1 {\n\t\tfmt.Println(\"Warning: No joysticks connected!\")\n\t} else {\n\t\tfmt.Println(\"Joystick detected\")\n\t\tfmt.Println(sdl.NumJoysticks())\n\t\t// Why extra controller ?...\n\t\tgameController := sdl.JoystickOpen(0)\n\t\t// TODO: maybe open and if nil do not use to avoid if else ...\n\t\tfmt.Println(gameController.Name())\n\t\tdefer gameController.Close()\n\t}\n\n\twindow, err := sdl.CreateWindow(\"test\", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600,\n\t\tsdl.WINDOW_SHOWN)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tpanicOnErr(window.Destroy())\n\t}()\n\n\tsurface, err := window.GetSurface()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpanicOnErr(surface.FillRect(nil, 0))\n\n\trect := sdl.Rect{X: 0, Y: 0, W: 100, H: 100}\n\tconst colorRed = 0xffff0000\n\tpanicOnErr(surface.FillRect(&rect, colorRed))\n\tpanicOnErr(window.UpdateSurface())\n\n\trunning := true\n\tfor running {\n\t\t// TODO: Fix time step fps.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tfor event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {\n\t\t\t// This will process all the events, TODO: should it go into the main loop ?\n\t\t\tfmt.Println(\"Event\", event)\n\t\t\tswitch event := event.(type) {\n\t\t\tcase *sdl.QuitEvent:\n\t\t\t\trunning = false\n\t\t\tcase *sdl.KeyboardEvent:\n\t\t\t\tfmt.Println(\"Key event detected\")\n\t\t\t\tif event.Type == sdl.KEYUP {\n\t\t\t\t\tif event.Keysym.Scancode == sdl.SCANCODE_RETURN || event.Keysym.Sym == sdl.SCANCODE_SPACE {\n\t\t\t\t\t\tfmt.Println(\"Keyup\", event.Keysym.Scancode, event.Keysym.Mod, event.Keysym.Sym)\n\t\t\t\t\t\tfmt.Println(\"Start Game\")\n\t\t\t\t\t} else if event.Keysym.Scancode == sdl.SCANCODE_ESCAPE {\n\t\t\t\t\t\trunning = false\n\t\t\t\t\t\tfmt.Println(\"Keyup\", event.Keysym.Scancode, event.Keysym.Mod, event.Keysym.Sym)\n\t\t\t\t\t\tfmt.Println(\"Escape...\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Println(event.Type)\n\t\t\tcase *sdl.JoyAxisEvent:\n\t\t\t\tfmt.Println(\"value:\", event.Value)\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(\"Quit\")\n}", "func gfxLoop(w window.Window, d gfx.Device) {\n\n\tgame.Init(w, d)\n\n\tfor {\n\t\tgame.Update(w, d)\n\t}\n}", "func (app *App) Run() (err error) {\n\treturn app.Renderer.Run()\n}", "func (i *IRC) Run() {\n\ti.wg.Add(1)\n\tgo func() {\n\t\tdefer i.wg.Done()\n\t\ti.conn.Loop()\n\t}()\n}", "func (d *GlobalDispatcher) Run() {\n\trun(d, d.MaxWorkers, d.WorkerPool)\n}", "func runStatusWindow() error {\n\tif nbmRunStatusWindow.Lock() {\n\t\tdefer nbmRunStatusWindow.Unlock()\n\n\t\tmw := declarative.MainWindow{\n\t\t\tAssignTo: &statusWindow,\n\t\t\tName: \"statusmw\",\n\t\t\tTitle: \"Status Data\",\n\t\t\tIcon: appIcon,\n\t\t\tSize: declarative.Size{Width: 300, Height: 250},\n\t\t\tLayout: declarative.VBox{MarginsZero: true},\n\t\t\tChildren: []declarative.Widget{\n\t\t\t\tdeclarative.Composite{\n\t\t\t\t\tLayout: declarative.Grid{Rows: 2},\n\t\t\t\t\tStretchFactor: 4,\n\t\t\t\t\tChildren: []declarative.Widget{\n\t\t\t\t\t\tdeclarative.TableView{\n\t\t\t\t\t\t\tName: \"statustv\",\n\t\t\t\t\t\t\tColumnsOrderable: true,\n\t\t\t\t\t\t\tAlternatingRowBG: true,\n\t\t\t\t\t\t\tHeaderHidden: true,\n\t\t\t\t\t\t\tLastColumnStretched: true,\n\t\t\t\t\t\t\tColumns: []declarative.TableViewColumn{\n\t\t\t\t\t\t\t\t{Name: \"Index\", Hidden: true},\n\t\t\t\t\t\t\t\t{Name: \"Name\"},\n\t\t\t\t\t\t\t\t{Name: \"Value\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tModel: newStatusTableDataModel(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdeclarative.PushButton{\n\t\t\t\t\t\t\tText: \"OK\",\n\t\t\t\t\t\t\tOnClicked: func() {\n\t\t\t\t\t\t\t\tstatusWindow.Close()\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\t// create window\n\t\terr := mw.Create()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// disable maximize, minimize, and resizing\n\t\thwnd := statusWindow.Handle()\n\t\twin.SetWindowLong(hwnd, win.GWL_STYLE, win.GetWindowLong(hwnd, win.GWL_STYLE) & ^(win.WS_MAXIMIZEBOX|win.WS_MINIMIZEBOX|win.WS_SIZEBOX))\n\n\t\t// start message loop\n\t\tstatusWindow.Run()\n\t} else {\n\t\t// bring already running status window to top\n\t\tstatusWindow.Show()\n\t}\n\n\treturn nil\n}", "func gameLoop(grid *game.Grid, controls *panel.Controls, status *panel.Status) {\n\tfor {\n\t\tif !paused {\n\t\t\tgrid.NextGeneration()\n\t\t}\n\n\t\t// Clear terminal window before rendering if needed.\n\t\tif clearUI {\n\t\t\tui.Clear()\n\t\t\tclearUI = false\n\t\t}\n\t\tui.Render(grid, controls, status)\n\n\t\t// Limit framerate if needed.\n\t\tif speed != game.Unlimited && !paused {\n\t\t\ttime.Sleep(time.Duration(speed) * time.Millisecond)\n\t\t}\n\t}\n}", "func (d *Dashboard) Run() {\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termbox.Close()\n\ttermbox.SetInputMode(termbox.InputEsc)\n\ttermbox.SetOutputMode(termbox.Output256)\n\tif err := d.redraw(); err != nil {\n\t\tfmt.Println(\"Error: %s\", err)\n\t\treturn\n\t}\n\teventChannel := make(chan termbox.Event, 10)\n\tgo d.termboxEventPoller(eventChannel)\n\nmainloop:\n\tfor {\n\t\tselect {\n\t\tcase ev, ok := <-eventChannel:\n\t\t\tif !ok {\n\t\t\t\tbreak mainloop\n\t\t\t}\n\t\t\tswitch ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Key {\n\t\t\t\tcase termbox.KeyEsc:\n\t\t\t\t\tbreak mainloop\n\t\t\t\tdefault:\n\t\t\t\t\tif ev.Ch == 'q' {\n\t\t\t\t\t\tbreak mainloop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventError:\n\t\t\t\tfmt.Printf(\"Error: %s\\n\", ev.Err)\n\t\t\t\tbreak mainloop\n\t\t\tcase termbox.EventResize:\n\t\t\t\ttermbox.Clear(termbox.ColorDefault, termbox.ColorDefault)\n\t\t\t\tif err := d.redraw(); err != nil {\n\t\t\t\t\tfmt.Println(\"Error: %s\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := d.redraw(); err != nil {\n\t\t\t\tfmt.Println(\"Error: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase buildUpdate := <-d.fetcher.BuildChannel():\n\t\t\td.builds = buildUpdate.builds\n\t\t\td.err = buildUpdate.err\n\t\t\tif err := d.redraw(); err != nil {\n\t\t\t\tfmt.Println(\"Error: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (server *Server) Run() {\n\tserver.goroutineWG.Add(1)\n\tgo server.run()\n}", "func (app *UIApp) Render() {\n\tn.GL.ClearColor(1, 1, 1, 1)\n\tn.GL.Clear(n.GlColorBufferBit)\n\n\tapp.batch.Begin()\n\tfor _, box := range app.boxs {\n\t\tapp.batch.SetSprite(box.sprite)\n\t\tapp.batch.Draw(box.rect, n.White)\n\t}\n\n\t//mouse := n.Input().GetMousePosition()\n\t//t := n.NewTransform2D(mouse, 0, Vector2{1, 1})\n\t//app.batch.Draw(app.cursor, Vector2{0.5, 0.5}, t, 0xffffff, 1)\n\n\t//app.batch.Draw(app.sprite, Vector2{0, 0}, Vector2{0, 0}, Vector2{1, 1}, 0, 0xffffff, 1)\n\tapp.batch.End()\n}", "func outerloop(screen *ebiten.Image) error {\r\n\r\n //screen.Fill(color.NRGBA{0xff, 0xff, 128, 0xff}) // \r\n screen.Fill(color.NRGBA{154, 158, 5, 0xff}) \r\n\r\n if ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) &&\r\n mouseReleased {\r\n mx, my := ebiten.CursorPosition()\r\n mouseReleased = false\r\n if Button_Click(mx,my) == startButtonCode {\r\n fmt.Printf(\"click button\\n\")\r\n //mode = modeGameScreen\r\n //MG_Init()\r\n buttonRunTimer.set(buttonRunTimer.kButtonStart,30) // 60 is 1 seconds\\\r\n \r\n } else if Button_Click(mx,my) == quitButtonCode {\r\n buttonQuitTimer.set(buttonRunTimer.kButtonStart,30)\r\n }\r\n } else if ! ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\r\n mouseReleased = true\r\n }\r\n\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyQ) {\r\n \texitProgram()\r\n }\r\n \r\n Button_Draw(screen)\r\n\r\n // timers are to allow the user to see the button press animation\r\n buttonRunTimer.inc()\r\n if buttonRunTimer.check() {\r\n fmt.Printf(\"buttonRunTimer execcute!\\n\")\r\n buttonRunTimer.reset()\r\n mode = modeGameScreen\r\n MG_Init()\r\n \r\n }\r\n\r\n buttonQuitTimer.inc()\r\n if buttonQuitTimer.check() {\r\n fmt.Printf(\"quit execcute!\\n\")\r\n buttonQuitTimer.reset() // unnecessary but for consistency\r\n exitProgram()\r\n }\r\n\r\n\t//digitsDraw(screen)\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyJ) && PushKeyOnce(\"J\") {\r\n fmt.Print(\"key J\\n\")\r\n //PushKeyOnce(\"J\")\r\n }\r\n if ebiten.IsKeyPressed(ebiten.KeyU) && PushKeyOnce(\"U\") {\r\n fmt.Print(\"key U\\n\")\r\n //PushKeyOnce(\"U\")\r\n }\r\n ebitenutil.DebugPrint(screen, \"Memory Game \\nin Ebiten\\n\")\r\n return nil\r\n}", "func (ec *EventCtrl) EventLoop() {\n\tgo func() {\n\t\tec.debug(\"SYSTEM Start event loop\")\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase e := <-ec.event:\n\t\t\t\tec.debug(\"SYSTEM Handling event:\", getHookName(e.EventType), \"on\", e.Filename)\n\t\t\t\toutputs, err := ec.runEventHook(e)\n\t\t\t\tif err == ErrNoCommand {\n\t\t\t\t\tec.debug(\"SYSTEM no hooks on:\", getHookName(e.EventType))\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tPrintError(\"SYSTEM Run hook error:\", err)\n\t\t\t\t} else {\n\t\t\t\t\tPrintSuccess(\"SYSTEM Invoke\", getHookName(e.EventType), \"-> output:\", strings.Trim(strings.Join(outputs, \"\\n\"), \"\\n\\t \"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func (m *Manager) Run() error {\n\tif m.running == false {\n\t\tif err := m.Start(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\t// Wait until we get shutdown signal\n\t\t<-m.signals\n\n\t\t// Stop the waiter\n\t\tm.wait.Done()\n\t}()\n\n\t// Make sure we wait until we get signals\n\tm.wait.Add(1)\n\tm.wait.Wait()\n\n\t// Stop all bots and return\n\tm.Stop()\n\treturn nil\n}", "func (app *appImpl) GoRunOnMain(f func()) {\n\tgo func() {\n\t\tapp.mainQueue <- funcRun{f: f, done: nil}\n\t}()\n}", "func Run() error {\n\tengine := qml.NewEngine()\n\n\ttemp := &ChessBoard{}\n\n\tchessBoard = temp\n\n\ttemp2 := &mylib.CapturedPieces{}\n\tcapturedPieces = temp2\n\n\ttemp3 := &Game{}\n\tgame = temp3\n\n\ttmp4 := &ChatMsg{}\n\tchatting = tmp4\n\n\ttmp5 := &ChatMsg{}\n\tglobalchatting = tmp5\n\n\tchessBoard.initialize()\n\n\tgame.InGame = false\n\n\tengine.Context().SetVar(\"game\", game)\n\tengine.Context().SetVar(\"chessBoard\", chessBoard)\n\tengine.Context().SetVar(\"capturedPieces\", capturedPieces)\n\tengine.Context().SetVar(\"chatting\", chatting)\n\tengine.Context().SetVar(\"globalchatting\", globalchatting)\n\n\tcomponent, err := engine.LoadFile(\"../src/Pass_The_Queen/qml/Application.qml\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twindow := component.CreateWindow(nil)\n\n\twindow.Show()\n\n\tgame_start = 1\n\tmy_name = os.Args[1]\n\tin_room = false\n\tin_game = false\n\trooms = make(map[string]string)\n\n\tmessenger.Msnger = messenger.NewMessenger(my_name)\n\n\tbuf := make([]byte, 1024)\n\n\t//Check the error log to see if node crashed in the middle of a game\n\tfi, err := os.Open(fmt.Sprintf(\"%v.log\", my_name))\n\tlast_msg := \"\"\n\tif err == nil {\n\t\tfor {\n\t\t\tn, err := fi.Read(buf)\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\tlog.Fatal(\"\", err)\n\t\t\t}\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlast_msg = string(buf)\n\t\t}\n\t}\n\tfi.Close()\n\n\tlast_msg_bits := strings.Split(last_msg, \" \")\n\n\t//Open up the error log writer\n\tfo, err = os.Create(fmt.Sprintf(\"%v.log\", my_name))\n\tif err != nil {\n\t\tlog.Fatal(\"\", err)\n\t}\n\tdefer fo.Close()\n\n\tmessenger.Msnger.Login()\n\n\tfmt.Println(last_msg)\n\n\t//If last message was START_GAME the game crashed in the middle of a game\n\tif last_msg_bits[0] == \"GAME_START\" {\n\t\t//FIXME: code below does not set GUI into right state\n\t\t//\tfmt.Println(\"success\")\n\t\t//\tmy_room = last_msg_bits[1]\n\t\t//\tboardNum, _ := strconv.Atoi(last_msg_bits[2])\n\t\t//\tgame_color, _ = strconv.Atoi(last_msg_bits[3])\n\t\t//\tgame_team, _ = strconv.Atoi(last_msg_bits[4])\n\t\t//\tfor i := 5; i < len(last_msg_bits); i++ {\n\t\t//\t\tlast_msg_bits[i] = strings.TrimRight(last_msg_bits[i], \" \")\n\t\t//\t\troom_members = append(room_members, last_msg_bits[i])\n\t\t//}\n\t\t//messenger.Msnger.Leave_global()\n\t\t//messenger.Msnger.Join_local(room_members)\n\t\t//StartGame(my_room, my_name, boardNum, game_color, game_team)\n\t}\n\n\tgo process_messages()\n\n\twindow.Wait()\n\n\treturn nil\n}", "func run() {\n\tcfg := pixelgl.WindowConfig{\n\t\tTitle: \"Giri's Gravity Simulations!\",\n\t\tBounds: pixel.R(0, 0, winHeight, winWidth),\n\t\t//VSync: true,\n\t}\n\n\twin, err := pixelgl.NewWindow(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twin.SetSmooth(true)\n\tpic, err := loadPicture(\"hiking.png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar bodyFrames [N]*pixel.Sprite\n\tfor i:=0;i<N;i++{\n\t\tbodyFrames[i] = pixel.NewSprite(pic, pic.Bounds())\n\t}\n\n\t// Camera Setup\n\tvar(\n\t\tcamPos = Vector{0,0}\n\t\tcamSpeed float64 = 600\n\t\tcamZoomSpeed = 1.2\n\t\tcamZoom = 1.0\n\t)\n\n\t// Body Initialisation\n\tvar Bodies [N]Body\n\n\tBodies[0] = Body{40, Vector{rand.Float64()*metric-metric/2, rand.Float64()*metric-metric/2}, Vector{rand.Float64()*2,rand.Float64()*2}, Vector{0,0}, 0}\n\tBodies[1] = Body{40, Vector{rand.Float64()*metric-metric/2, rand.Float64()*metric-metric/2}, Vector{rand.Float64()*2,rand.Float64()*2}, Vector{0,0}, 0}\n\tBodies[2] = Body{10, Vector{rand.Float64()*metric-metric/2, rand.Float64()*metric-metric/2}, Vector{rand.Float64()*2,rand.Float64()*2}, Vector{0,0}, 1.0}\n\tfmt.Println(Bodies[0].pos, Bodies[1].pos, Bodies[2].pos,)\n\n\t// Fps Setup\n\tvar (\n\t\tframes = 0\n\t\tsecond = time.Tick(time.Second)\n\t)\n\n\t// Computing of Trajectories\n\tlast := time.Now()\n\tfor !win.Closed() {\n\t\twin.Clear(colornames.Midnightblue)\n\n\t\tdt := time.Since(last).Seconds()\n\t\tlast = time.Now()\n\n\t\t// Keypress Activities\n\t\tif win.Pressed(pixelgl.KeyLeft) {\n\t\t\tcamPos.x += camSpeed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyRight) {\n\t\t\tcamPos.x -= camSpeed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyUp) {\n\t\t\tcamPos.y -= camSpeed * dt\n\t\t}\n\t\tif win.Pressed(pixelgl.KeyDown) {\n\t\t\tcamPos.y += camSpeed * dt\n\t\t}\n\t\tcamZoom *= math.Pow(camZoomSpeed, win.MouseScroll().Y)\n\n\t\t// Computation of Trajectories\n\t\tfor i:=0;i<N;i++{\n\t\t\tBodies[i].acc = Bodies[i].getGravity(Bodies)\n\t\t}\n\t\tfor i:=0;i<N;i++{\n\t\t\tBodies[i].vel = Bodies[i].getVel()\n\t\t\tBodies[i].pos = Bodies[i].getPos()\n\t\t\tvar x, y = Bodies[i].pos.x+winWidth/2, Bodies[i].pos.y+winHeight/2\n\t\t\tmat := pixel.IM\n\t\t\tmat = mat.Moved(pixel.V(x,y)).Scaled(pixel.V(x,y),zoom).Scaled(pixel.V(x,y),Bodies[i].mass/5).Moved(pixel.V(camPos.x,camPos.y)).Scaled(pixel.V(winWidth/2,winHeight/2),camZoom)\n\t\t\tbodyFrames[i].Draw(win, mat)\n\t\t}\n\t\twin.Update()\n\t\tframes++\n\t\tselect {\n\t\tcase <-second:\n\t\t\twin.SetTitle(fmt.Sprintf(\"%s | FPS: %d\", cfg.Title, frames))\n\t\t\tframes = 0\n\t\tdefault:\n\t\t}\n\t}\n}", "func (h *Server) Run() {\n\n\th.g.StartServer()\n}", "func main() {\n\tpixelgl.Run(run)\n}" ]
[ "0.68362325", "0.6632658", "0.65929407", "0.65919864", "0.6479984", "0.64564955", "0.63060695", "0.6271096", "0.62061435", "0.61521715", "0.6062181", "0.6053579", "0.6020126", "0.5969148", "0.5958348", "0.59452575", "0.59320587", "0.5922841", "0.58962166", "0.58803695", "0.5869415", "0.5799483", "0.5797087", "0.5754956", "0.5734513", "0.5733007", "0.5716845", "0.57015455", "0.567158", "0.56705624", "0.56684124", "0.5653149", "0.56435895", "0.5637294", "0.56298685", "0.556443", "0.55624586", "0.5541209", "0.5529542", "0.55074275", "0.5492066", "0.5463119", "0.54622513", "0.5418091", "0.5417907", "0.54131377", "0.54072475", "0.5384694", "0.5347731", "0.5346373", "0.5334466", "0.53329927", "0.53278095", "0.53278095", "0.53224224", "0.52994865", "0.52966213", "0.5279", "0.5274175", "0.5273576", "0.5267563", "0.5264662", "0.52550536", "0.5246824", "0.5228297", "0.5208259", "0.5206612", "0.52057105", "0.5196088", "0.5183504", "0.5183504", "0.5176309", "0.51755416", "0.51512265", "0.51020133", "0.5092914", "0.5052247", "0.5049166", "0.5038003", "0.50380015", "0.50045085", "0.5002742", "0.4993593", "0.49750683", "0.49693805", "0.49398923", "0.49386808", "0.49357522", "0.49295077", "0.49182296", "0.4900103", "0.4889415", "0.48862", "0.487345", "0.48700032", "0.48695734", "0.48543727", "0.48493645", "0.48401013", "0.4837104" ]
0.66125727
2
NewWin32LobAppRegistryDetection instantiates a new win32LobAppRegistryDetection and sets the default values.
func NewWin32LobAppRegistryDetection()(*Win32LobAppRegistryDetection) { m := &Win32LobAppRegistryDetection{ Win32LobAppDetection: *NewWin32LobAppDetection(), } odataTypeValue := "#microsoft.graph.win32LobAppRegistryDetection" m.SetOdataType(&odataTypeValue) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewWin32LobAppRegistryRule()(*Win32LobAppRegistryRule) {\n m := &Win32LobAppRegistryRule{\n Win32LobAppRule: *NewWin32LobAppRule(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppRegistryRule\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func NewWin32LobAppFileSystemDetection()(*Win32LobAppFileSystemDetection) {\n m := &Win32LobAppFileSystemDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppFileSystemDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func NewWin32LobAppProductCodeDetection()(*Win32LobAppProductCodeDetection) {\n m := &Win32LobAppProductCodeDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppProductCodeDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryDetection(), nil\n}", "func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}", "func (m *Win32LobAppRegistryDetection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Win32LobAppDetection.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteBoolValue(\"check32BitOn64System\", m.GetCheck32BitOn64System())\n if err != nil {\n return err\n }\n }\n if m.GetDetectionType() != nil {\n cast := (*m.GetDetectionType()).String()\n err = writer.WriteStringValue(\"detectionType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"detectionValue\", m.GetDetectionValue())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"keyPath\", m.GetKeyPath())\n if err != nil {\n return err\n }\n }\n if m.GetOperator() != nil {\n cast := (*m.GetOperator()).String()\n err = writer.WriteStringValue(\"operator\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"valueName\", m.GetValueName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}", "func (m *Win32LobAppRegistryDetection) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Win32LobAppDetection.GetFieldDeserializers()\n res[\"check32BitOn64System\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCheck32BitOn64System(val)\n }\n return nil\n }\n res[\"detectionType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseWin32LobAppRegistryDetectionType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDetectionType(val.(*Win32LobAppRegistryDetectionType))\n }\n return nil\n }\n res[\"detectionValue\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDetectionValue(val)\n }\n return nil\n }\n res[\"keyPath\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetKeyPath(val)\n }\n return nil\n }\n res[\"operator\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseWin32LobAppDetectionOperator)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOperator(val.(*Win32LobAppDetectionOperator))\n }\n return nil\n }\n res[\"valueName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetValueName(val)\n }\n return nil\n }\n return res\n}", "func NewRegistry(b biz.RegistryBiz) *RegistryHandler {\n\treturn &RegistryHandler{\n\t\tSearch: registrySearch(b),\n\t\tFind: registryFind(b),\n\t\tDelete: registryDelete(b),\n\t\tSave: registrySave(b),\n\t}\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}", "func New() *PollerRegistry {\n\treturn &PollerRegistry{\n\t\tRegistry: make(map[string]*poller.Poller),\n\t\tToDB: make(chan interface{}),\n\t\tUpdateStatus: make(chan string),\n\t}\n}", "func NewRegistry(opts ...registry.Option) registry.Registry {\r\n\treturn registry.NewRegistry(opts...)\r\n}", "func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}", "func NewLob(baseAPI, apiKey, userAgent string) *lob {\n\treturn &lob{\n\t\tBaseAPI: baseAPI,\n\t\tAPIKey: apiKey,\n\t\tUserAgent: userAgent,\n\t}\n}", "func NewBitmaps(library io.StoreLibrary) (bitmaps *Bitmaps, err error) {\n\tvar mfdArt [model.LanguageCount]*io.DynamicChunkStore\n\n\tfor i := 0; i < model.LanguageCount && err == nil; i++ {\n\t\tmfdArt[i], err = library.ChunkStore(localized[i].mfdart)\n\t}\n\n\tif err == nil {\n\t\tbitmaps = &Bitmaps{mfdArt: mfdArt}\n\t}\n\n\treturn\n}", "func New(ctx context.Context, m map[string]interface{}) (storage.Registry, error) {\n\tvar c config\n\tif err := cfg.Decode(m, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &reg{c: &c}, nil\n}", "func New(opts ...Option) *Registry {\n\tregistry := &Registry{}\n\n\t// apply options\n\tfor _, opt := range opts {\n\t\topt(registry)\n\t}\n\n\treturn registry\n}", "func NewRegistry(opts ...registry.Option) registry.Registry {\n\treturn mdns.NewRegistry(opts...)\n}", "func NewRegistry(conf RegistryConfig) Monitor {\n\treturn &registry{\n\t\tlisteners: conf.Listeners,\n\t\tregistryClient: conf.RegistryClient,\n\t\tpollInterval: conf.PollInterval,\n\t}\n}", "func New(glabel string, flags int) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, LflagsDef, nil, false)\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tServicesMap: make(map[string]ServiceList),\n\t}\n}", "func NewRegistry() *bsoncodec.Registry {\n\treturn NewRegistryBuilder().Build()\n}", "func NewAndroidLobApp()(*AndroidLobApp) {\n m := &AndroidLobApp{\n MobileLobApp: *NewMobileLobApp(),\n }\n odataTypeValue := \"#microsoft.graph.androidLobApp\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func NewRegistry(maxLat time.Duration) *Registry {\n\tr := &Registry{\n\t\tstart: timeutil.Now(),\n\t\tcumulative: make(map[string]*hdrhistogram.Histogram),\n\t\tprevTick: make(map[string]time.Time),\n\t\thistogramPool: &sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn hdrhistogram.New(minLatency.Nanoseconds(), maxLat.Nanoseconds(), sigFigs)\n\t\t\t},\n\t\t},\n\t}\n\tr.mu.registered = make(map[string][]*NamedHistogram)\n\treturn r\n}", "func NewRegistry(userNS *auth.UserNamespace) *Registry {\n\treturn &Registry{\n\t\treg: ipc.NewRegistry(userNS),\n\t}\n}", "func NewRegistry() *Registry {\n\tr := &Registry{}\n\tr.functions = make(map[string]*function)\n\treturn r\n}", "func New(reg *api.Registry, store ApiObjectProvider) *Registry {\n\treturn &Registry{\n\t\tapiProvider: store,\n\t\tapiRegistry: reg,\n\t}\n}", "func NewRegistry() Registry {\n\treturn make(Registry)\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tmodules: make([]bar.Module, 0),\n\t}\n}", "func NewGetModelRegistryDefault(code int) *GetModelRegistryDefault {\n\treturn &GetModelRegistryDefault{\n\t\t_statusCode: code,\n\t}\n}", "func New(ringWeight int) LoadBalancer {\n\t// TODO: Implement this!\n\tnewLB := new(loadBalancer)\n\tnewLB.sortedNames = make([]MMENode, 0)\n\tnewLB.weight = ringWeight\n\tnewLB.hashRing = NewRing()\n\tif 7 == 2 {\n\t\tfmt.Println(ringWeight)\n\t}\n\treturn newLB\n}", "func newRegistry(logger logr.Logger, config globalregistry.RegistryConfig) (globalregistry.Registry, error) {\n\tvar err error\n\tc := &registry{\n\t\tlogger: logger,\n\t\tRegistryConfig: config,\n\t\tClient: http.DefaultClient,\n\t}\n\tc.projects, err = newProjectAPI(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.remoteRegistries = newRemoteRegistries(c)\n\tc.replications = newReplicationAPI(c)\n\tc.parsedUrl, err = url.Parse(config.GetAPIEndpoint())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.scanners = newScannerAPI(c)\n\treturn c, nil\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\toutlets: make([]*Outlet, 0),\n\t\toutletMap: make(map[string]*Outlet),\n\t\tgroups: make([]*Group, 0),\n\t\tgroupMap: make(map[string]*Group),\n\t}\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\trateLimiters: make(map[string]*rate.Limiter),\n\t}\n}", "func New(handlers ...ImageHandler) *Goba {\n\treturn &Goba{handlers: handlers}\n}", "func NewReg(ctx app.Ctx) *Reg {\n\treturn &Reg{\n\t\tctx: ctx,\n\t\tl: map[string]H{},\n\t}\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\ttypes: make(map[string]reflect.Type),\n\t\tmu: sync.Mutex{},\n\t}\n}", "func New(registryURL string) *Registry {\n\tregistryURL = strings.TrimRight(registryURL, \"/\")\n\tregistryURL = fmt.Sprintf(\"%s/v2\", registryURL)\n\n\treturn &Registry{\n\t\turl: registryURL,\n\t}\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tall: make(map[string]*Job),\n\t}\n}", "func NewRegistry() Registry {\n\tfr := make(Registry)\n\tfr.mustRegister(BuiltIns...)\n\treturn fr\n}", "func NewRegistry() *Registry {\n\tt := Registry{}\n\tt.Reset()\n\n\treturn &t\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tentries: make(map[datatransfer.TypeIdentifier]Processor),\n\t}\n}", "func NewRegistry() *Registry {\n\tregistry := Registry{}\n\tregistry.lock = &sync.Mutex{}\n\treturn &registry\n}", "func New() registry.Registry {\n\treturn &InMemRegistry{\n\t\tpeers: make(map[string]*peerData),\n\t}\n}", "func NewWindowsUniversalAppX()(*WindowsUniversalAppX) {\n m := &WindowsUniversalAppX{\n MobileLobApp: *NewMobileLobApp(),\n }\n odataTypeValue := \"#microsoft.graph.windowsUniversalAppX\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func New(name string) (*Wireguard, error) {\n\tattrs := netlink.NewLinkAttrs()\n\tattrs.Name = name\n\tattrs.MTU = 1420\n\n\twg := &Wireguard{attrs: &attrs}\n\tif err := netlink.LinkAdd(wg); err != nil && !os.IsExist(err) {\n\t\treturn nil, err\n\t}\n\n\t// always make sure we load the full attributes\n\treturn GetByName(name)\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func NewRegistry() *Registry {\n\treturn new(Registry)\n}", "func NewSpecial(glabel string, flags int, logFlagsGroup int, iowr IowrStruct) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, logFlagsGroup, &iowr, false)\n}", "func NewRemoteRegistry() *RemoteRegistry {\n\treturn &RemoteRegistry{\n\t\tmodelByName: make(map[string]*RemotelyKnownModel),\n\t}\n}", "func NewLocalRegistry(artHome string) *LocalRegistry {\n\tr := &LocalRegistry{\n\t\tRepositories: []*Repository{},\n\t\tArtHome: artHome,\n\t}\n\t// load local registry\n\tr.Load()\n\treturn r\n}", "func ScanBLSEntries(l ulog.Logger, fsRoot string, variables map[string]string, grubDefaultSavedEntry string) ([]boot.OSImage, error) {\n\tentriesDir := filepath.Join(fsRoot, blsEntriesDir)\n\n\tfiles, err := filepath.Glob(filepath.Join(entriesDir, \"*.conf\"))\n\tif err != nil || len(files) == 0 {\n\t\t// Try blsEntriesDir2\n\t\tentriesDir = filepath.Join(fsRoot, blsEntriesDir2)\n\t\tfiles, err = filepath.Glob(filepath.Join(entriesDir, \"*.conf\"))\n\t\tif err != nil || len(files) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no BootLoaderSpec entries found: %w\", err)\n\t\t}\n\t}\n\n\t// loader.conf is not in the real spec; it's an implementation detail\n\t// of systemd-boot. It is specified in\n\t// https://www.freedesktop.org/software/systemd/man/loader.conf.html\n\tloaderConf, err := parseConf(filepath.Join(fsRoot, \"loader\", \"loader.conf\"))\n\tif err != nil {\n\t\t// loader.conf is optional.\n\t\tloaderConf = make(map[string]string)\n\t}\n\n\t// TODO: Rank entries by version or machine-id attribute as suggested\n\t// in the spec (but not mandated, surprisingly).\n\timgs := make(map[string]boot.OSImage)\n\tfor _, f := range files {\n\t\tidentifier := strings.TrimSuffix(filepath.Base(f), \".conf\")\n\n\t\t// If the config file name is the same as the Grub default option, pass true for grubDefaultFlag\n\t\tvar img boot.OSImage\n\t\tvar err error\n\t\tif strings.Compare(identifier, grubDefaultSavedEntry) == 0 {\n\t\t\timg, err = parseBLSEntry(f, fsRoot, variables, true)\n\t\t} else {\n\t\t\timg, err = parseBLSEntry(f, fsRoot, variables, false)\n\t\t}\n\t\tif err != nil {\n\t\t\tl.Printf(\"BootLoaderSpec skipping entry %s: %v\", f, err)\n\t\t\tcontinue\n\t\t}\n\t\timgs[identifier] = img\n\t}\n\n\treturn sortImages(loaderConf, imgs), nil\n}", "func New(min, max uint16) (*Registry, error) {\n\tif min > max {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"Minimum port %d must be less than maximum port %d\",\n\t\t\t\tmin, max)\n\t}\n\n\treturn &Registry{\n\t\tbyname: make(map[string]*service, 100),\n\t\tbyport: make(map[uint16]*service, 100),\n\t\tportMin: min,\n\t\tportMax: max,\n\t\tportNext: min,\n\t}, nil\n}", "func NewWindowsInformationProtectionDeviceRegistration()(*WindowsInformationProtectionDeviceRegistration) {\n m := &WindowsInformationProtectionDeviceRegistration{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\ttypeEncoders: new(typeEncoderCache),\n\t\ttypeDecoders: new(typeDecoderCache),\n\t\tkindEncoders: new(kindEncoderCache),\n\t\tkindDecoders: new(kindDecoderCache),\n\t}\n}", "func NewRegistry() Registry {\n\treturn &registry{\n\t\tmodelsByGoType: make(map[reflect.Type]*knownModel),\n\t\tmodelsByProtoName: make(map[string]*knownModel),\n\t\tmodelsByName: make(map[string]*knownModel),\n\t}\n}", "func NewRegistryAdd(m map[string]interface{}) (*RegistryAdd, error) {\n\tol := newOptionLoader(m)\n\n\tra := &RegistryAdd{\n\t\tapp: ol.LoadApp(),\n\t\tname: ol.LoadString(OptionName),\n\t\turi: ol.LoadString(OptionURI),\n\t\tversion: ol.LoadString(OptionVersion),\n\t\tisOverride: ol.LoadBool(OptionOverride),\n\n\t\tregistryAddFn: registry.Add,\n\t}\n\n\tif ol.err != nil {\n\t\treturn nil, ol.err\n\t}\n\n\treturn ra, nil\n}", "func NewRegistry() ObjectRegistry {\n\timpl := &registry{actionChannel: make(actionChannel)}\n\tgo impl.run()\n\n\treturn impl\n}", "func New(fname string, runTests bool) error {\n\tml = make(map[string]lfList)\n\treturn readFilterList(fname, runTests)\n}", "func NewDummyLBInterface() *DummyLBInterface {\n\treturn &DummyLBInterface{\n\t\tmake(map[seesaw.VIP]bool),\n\t\tmake(map[uint16]bool),\n\t\tmake(map[string]map[seesaw.AF]bool),\n\t}\n}", "func CreateAndroidLobAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidLobApp(), nil\n}", "func NewRegistry(ctx *pulumi.Context,\n\tname string, args *RegistryArgs, opts ...pulumi.ResourceOption) (*Registry, error) {\n\tif args == nil {\n\t\targs = &RegistryArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Registry\n\terr := ctx.RegisterResource(\"aws-native:eventschemas:Registry\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func NewLongpoll(vk *api.VK, mode Mode) (*Longpoll, error) {\n\tlp := &Longpoll{\n\t\tVK: vk,\n\t\tMode: mode,\n\t\tVersion: 3,\n\t\tWait: 25,\n\t\tfuncList: make(FuncList),\n\t\tClient: http.DefaultClient,\n\t}\n\n\terr := lp.updateServer(true)\n\n\treturn lp, err\n}", "func InitializeRegistry(\n\tcommandMap stringmap.StringMap,\n\tkarmaMap stringmap.StringMap,\n\tvoteMap stringmap.StringMap,\n\tgist api.Gist,\n\tconfig *config.Config,\n\tclock model.UTCClock,\n\ttimer model.UTCTimer,\n\tcommandChannel chan<- *model.Command) *feature.Registry {\n\n\t// Initializing builtin features.\n\t// TODO(jvoytko): investigate the circularity that emerged to see if there's\n\t// a better pattern here.\n\tfeatureRegistry := feature.NewRegistry()\n\tallFeatures := []feature.Feature{\n\t\tfactsphere.NewFeature(featureRegistry),\n\t\thelp.NewFeature(featureRegistry),\n\t\tkarma.NewFeature(featureRegistry, karmaMap),\n\t\tkarmalist.NewFeature(featureRegistry, karmaMap, gist),\n\t\tlearn.NewFeature(featureRegistry, commandMap),\n\t\tlist.NewFeature(featureRegistry, commandMap, gist),\n\t\tmoderation.NewFeature(featureRegistry, config),\n\t\tvote.NewFeature(featureRegistry, voteMap, clock, timer, commandChannel),\n\t}\n\n\tfor _, f := range allFeatures {\n\t\terr := featureRegistry.Register(f)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn featureRegistry\n}", "func NewRegistry(name string) (*Registry, error) {\n\tref := registry.Reference{\n\t\tRegistry: name,\n\t}\n\tif err := ref.ValidateRegistry(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Registry{\n\t\tRepositoryOptions: RepositoryOptions{\n\t\t\tReference: ref,\n\t\t},\n\t}, nil\n}", "func New(resolution int) HMSketch {\n\tvar x HMSketch\n\tx.Resolution = resolution\n\tx.Registers = make([]hist.Histogram, 0)\n\tx.Index = make(map[int64]int)\n\tx = x.insert(map[string]string{\"__global__\": \"__global__\"}, 0, 0)\n\treturn x\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tLogger: logger.NewLogger(\"dapr.state.registry\"),\n\t\tstateStores: make(map[string]func(logger.Logger) state.Store),\n\t\tversionsSet: make(map[string]components.Versioning),\n\t}\n}", "func NewWinLogWatcher() (*WinLogWatcher, error) {\n\tcHandle, err := GetSystemRenderContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WinLogWatcher{\n\t\tshutdown: make(chan interface{}),\n\t\terrChan: make(chan error),\n\t\teventChan: make(chan *WinLogEvent),\n\t\trenderContext: cHandle,\n\t\twatches: make(map[string]*channelWatcher),\n\t\tRenderKeywords: true,\n\t\tRenderMessage: true,\n\t\tRenderLevel: true,\n\t\tRenderTask: true,\n\t\tRenderProvider: true,\n\t\tRenderOpcode: true,\n\t\tRenderChannel: true,\n\t\tRenderId: true,\n\t}, nil\n}", "func New() (g *Glutton, err error) {\n\tg = &Glutton{}\n\tg.protocolHandlers = make(map[string]protocolHandlerFunc, 0)\n\tviper.SetDefault(\"var-dir\", \"/var/lib/glutton\")\n\tif err = g.makeID(); err != nil {\n\t\treturn nil, err\n\t}\n\tg.logger = NewLogger(g.id.String())\n\n\t// Loading the congiguration\n\tg.logger.Info(\"Loading configurations from: config/conf.yaml\", zap.String(\"reporter\", \"glutton\"))\n\tg.conf, err = config.Init(g.logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trulesPath := g.conf.GetString(\"rules_path\")\n\trulesFile, err := os.Open(rulesPath)\n\tdefer rulesFile.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tg.rules, err = freki.ReadRulesFromFile(rulesFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn g, nil\n\n}", "func New(lDs, gDs Placeholder, dfn DriverNotifyFunc, ifn Placeholder, pg plugingetter.PluginGetter) (*DrvRegistry, error) {\n\treturn &DrvRegistry{\n\t\tNetworks: Networks{Notify: dfn},\n\t\tpluginGetter: pg,\n\t}, nil\n}", "func New(r *registry.R) *FlowBuilder {\n\treturn &FlowBuilder{\n\t\tregistry: r,\n\t\tOperationMap: map[string]flow.Operation{},\n\t\tnodeTrack: map[string]bool{},\n\t}\n}", "func NewInTreeRegistry() framework.Registry {\r\n\treturn framework.Registry{\r\n\t\ttainttoleration.Name: tainttoleration.New,\r\n\t\tnodeaffinity.Name: nodeaffinity.New,\r\n\t\tnodename.Name: nodename.New,\r\n\t\tnodestatus.Name: nodestatus.New,\r\n nodeports.Name: nodeports.New,\r\n nodeunschedulable.Name: nodeunschedulable.New,\r\n noderesources.FitName: noderesources.NewFit,\r\n interpodaffinity.Name: interpodaffinity.New,\r\n imagelocality.Name: imagelocality.New,\r\n volumebinding.Name: volumebinding.New,\r\n volumerestrictions.Name: volumerestrictions.New,\r\n resourcepriority.Name: resourcepriority.New,\r\n repeatpriority.Name: repeatpriority.New,\r\n\t}\r\n}", "func NewInterfaceRegistry() InterfaceRegistry {\n\tregistry, err := NewInterfaceRegistryWithOptions(InterfaceRegistryOptions{\n\t\tProtoFiles: proto.HybridResolver,\n\t\tSigningOptions: signing.Options{\n\t\t\tAddressCodec: failingAddressCodec{},\n\t\t\tValidatorAddressCodec: failingAddressCodec{},\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn registry\n}", "func NewApp(name string, scopes []string, redirectURI string) (g *Gondole, err error) {\n\t// Load configuration, will register if none is found\n\tcnf, err := LoadConfig(name)\n\tif err != nil {\n\t\t// Nothing exist yet\n\t\tcnf := Config{\n\t\t\tDefault: name,\n\t\t}\n\t\terr = cnf.Write()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: can not write config for %s\", name)\n\t\t}\n\n\t\t// Now register this through OAuth\n\t\tif scopes == nil {\n\t\t\tscopes = ourScopes\n\t\t}\n\n\t\tg, err = registerApplication(name, scopes, redirectURI)\n\n\t} else {\n\t\tg = &Gondole{\n\t\t\tName: cnf.Name,\n\t\t\tID: cnf.ID,\n\t\t\tSecret: cnf.BearerToken,\n\t\t}\n\t}\n\n\treturn\n}", "func NewRegistry(settings ...Settings) *Registry {\n\treturn NewSwarmRegistry(nil, nil, settings...)\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tnodesView: make(map[identity.ID]*View),\n\t}\n}", "func NewWindowsInformationProtectionDataRecoveryCertificate()(*WindowsInformationProtectionDataRecoveryCertificate) {\n m := &WindowsInformationProtectionDataRecoveryCertificate{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewDefaultRegistry() framework.Registry {\n\treturn framework.Registry{\n\t\t// This is just a test plugin to showcase the setup, it should be deleted once\n\t\t// we have at least one legitimate plugin here.\n\t\tnoop.Name: noop.New,\n\t}\n}", "func newGame() *game {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tg := &game{}\n\tg.State = \"lobby\"\n\tg.StateTime = time.Now()\n\tg.Name = \"MafiosoGame\"\n\tg.Winner = \"\"\n\tg.Players = make([]*player, 0)\n\tif g.Id != \"\" {\n\t\tgameList[g.Id] = g\n\t}\n\treturn g\n}", "func NewRegistry(c RemoteClientFactory, l log.Logger) Registry {\n\treturn &registry{\n\t\tfactory: c,\n\t\tLogger: l,\n\t}\n}", "func NewWindowsMalwareCategoryCount()(*WindowsMalwareCategoryCount) {\n m := &WindowsMalwareCategoryCount{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func registFrameClass(name *uint16, wndProc uintptr) W.ATOM {\n\twc := new (W.WNDCLASSEX)\n\twc.CbSize = uint32(unsafe.Sizeof(*wc))\n\twc.Style = W.CS_HREDRAW | W.CS_VREDRAW\n\twc.LpfnWndProc = wndProc\n\twc.CbClsExtra = 0\n\twc.CbWndExtra = 0\n\twc.HInstance = hInstance\n\twc.HIcon = 0\n\twc.HCursor = W.LoadCursor(0, W.MAKEINTRESOURCE(W.IDC_ARROW))\n\twc.HbrBackground = W.HBRUSH(W.WHITE_BRUSH)\n\twc.LpszMenuName = nil\n\twc.LpszClassName = name\n\twc.HIconSm = 0\n\treturn W.RegisterClassEx(wc)\n}", "func (*llcFactory) New(args *xreg.XactArgs) xreg.BucketEntry {\n\treturn &llcFactory{t: args.T, uuid: args.UUID}\n}", "func NewRegistryKeyState()(*RegistryKeyState) {\n m := &RegistryKeyState{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewWindowsKioskProfile()(*WindowsKioskProfile) {\n m := &WindowsKioskProfile{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewRegistry() *Registry {\n\treturn &Registry{\n\t\ttypeForTag: typeForTag{},\n\t\ttagForType: tagForType{},\n\t\tfactoryForType: factoryForType{},\n\t}\n}", "func newll(glabel string, flags int, logFlags int, iowr *IowrStruct, panicErr bool) (*GlvlStruct, error) {\n\tg := &GlvlStruct{firstIowr: IowrDefault()}\n\tif iowr != nil {\n\t\tg.firstIowr = *iowr\n\t}\n\t// test g.firstIowr.Error = nil\n\n\tmuGrplogCount.Lock()\n\tgrplogCount++\n\tg.Name = fmt.Sprintf(\"%s<%d>\", glabel, grplogCount) //ensure an unique name\n\tmuGrplogCount.Unlock()\n\n\tfor _, v := range g.lvlList() {\n\t\tif *v.iowr == nil {\n\t\t\terrnew := errors.New(v.name + \" io.Writer is nil, if you want to discard use ioutil.Discard\")\n\t\t\tif panicErr {\n\t\t\t\tlog.Panic(errnew)\n\t\t\t}\n\t\t\treturn nil, errnew\n\t\t}\n\t\t*v.level = &LvlStruct{\n\t\t\tlog: log.New(*v.iowr, glabel+v.Blab, logFlags),\n\t\t\tlogOutput: *v.iowr,\n\t\t\tflags: flags,\n\t\t\tmu: &g.mu,\n\t\t\tpar: g,\n\t\t\tname: v.name,\n\t\t\talign: alignStruct{filea: LogAlignFileDef, funca: LogAlignFuncDef},\n\t\t}\n\t}\n\treturn g, nil\n}", "func NewHclFirmware(classId string, objectType string) *HclFirmware {\n\tthis := HclFirmware{}\n\tthis.ClassId = classId\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func (b BotAppNotModified) construct() BotAppClass { return &b }", "func createLobby(maxRounds int, startingTeam int, team1Name string, team2Name string) Lobby {\n\n\t// Firstly generate uuids\n\tlobbyUUID := generateUUID()\n\tteam1UIDGenerated := generateUUID()\n\tteam2UIDGenerated := generateUUID()\n\n\tlobby := Lobby{\n\t\tLobbyUID: lobbyUUID,\n\t\tTeam1UID: team1UIDGenerated,\n\t\tTeam1Name: team1Name,\n\t\tTeam2Name: team2Name,\n\t\tTeam2UID: team2UIDGenerated,\n\t\tTeam1link: fmt.Sprintf(`/pv/%v/%v`, lobbyUUID, team1UIDGenerated),\n\t\tTeam2link: fmt.Sprintf(`/pv/%v/%v`, lobbyUUID, team2UIDGenerated),\n\t\tMaxRounds: maxRounds,\n\t\tEnabled: false,\n\t\tStartingTeam: startingTeam,\n\t}\n\n\t// By default whenever a new lobby is generated then a game on nagrand is added.\n\t// With the exception of there being a potential different map for single play.\n\tif maxRounds != 1 {\n\t\tlobby.createDefaultGame(startingTeam)\n\t}\n\n\tif maxRounds == 1 {\n\t\tlobby.createGame(startingTeam, 1)\n\t}\n\n\treturn lobby\n\n}", "func NewRegulator(driver storagedriver.StorageDriver, limit uint64) storagedriver.StorageDriver {\n\treturn &regulator{\n\t\tStorageDriver: driver,\n\t\tCond: sync.NewCond(&sync.Mutex{}),\n\t\tavailable: limit,\n\t}\n}", "func (m *Win32LobAppRegistryDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func NewRegistryBuilder() *bsoncodec.RegistryBuilder {\n\trb := bsoncodec.NewRegistryBuilder()\n\tbsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb)\n\tbsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb)\n\tbson.PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb)\n\n\tstructcodec, _ := bsoncodec.NewStructCodec(bsoncodec.DefaultStructTagParser,\n\t\tbsonoptions.StructCodec().\n\t\t\tSetDecodeZeroStruct(true).\n\t\t\tSetEncodeOmitDefaultStruct(true).\n\t\t\tSetOverwriteDuplicatedInlinedFields(false).\n\t\t\tSetAllowUnexportedFields(true))\n\temptyInterCodec := bsoncodec.NewEmptyInterfaceCodec(\n\t\tbsonoptions.EmptyInterfaceCodec().\n\t\t\tSetDecodeBinaryAsSlice(true))\n\tmapCodec := bsoncodec.NewMapCodec(\n\t\tbsonoptions.MapCodec().\n\t\t\tSetDecodeZerosMap(true).\n\t\t\tSetEncodeNilAsEmpty(true).\n\t\t\tSetEncodeKeysWithStringer(true))\n\tuintcodec := bsoncodec.NewUIntCodec(bsonoptions.UIntCodec().SetEncodeToMinSize(true))\n\n\trb.RegisterTypeDecoder(tEmpty, emptyInterCodec).\n\t\tRegisterDefaultDecoder(reflect.String, bsoncodec.NewStringCodec(bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false))).\n\t\tRegisterDefaultDecoder(reflect.Struct, structcodec).\n\t\tRegisterDefaultDecoder(reflect.Map, mapCodec).\n\t\tRegisterTypeEncoder(tByteSlice, bsoncodec.NewByteSliceCodec(bsonoptions.ByteSliceCodec().SetEncodeNilAsEmpty(true))).\n\t\tRegisterDefaultEncoder(reflect.Struct, structcodec).\n\t\tRegisterDefaultEncoder(reflect.Slice, bsoncodec.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))).\n\t\tRegisterDefaultEncoder(reflect.Map, mapCodec).\n\t\tRegisterDefaultEncoder(reflect.Uint, uintcodec).\n\t\tRegisterDefaultEncoder(reflect.Uint8, uintcodec).\n\t\tRegisterDefaultEncoder(reflect.Uint16, uintcodec).\n\t\tRegisterDefaultEncoder(reflect.Uint32, uintcodec).\n\t\tRegisterDefaultEncoder(reflect.Uint64, uintcodec).\n\t\tRegisterTypeMapEntry(bsontype.Int32, tInt).\n\t\tRegisterTypeMapEntry(bsontype.DateTime, tTime).\n\t\tRegisterTypeMapEntry(bsontype.Array, tInterfaceSlice).\n\t\tRegisterTypeMapEntry(bsontype.Type(0), tM).\n\t\tRegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).\n\t\tRegisterHookEncoder(tGetter, bsoncodec.ValueEncoderFunc(GetterEncodeValue)).\n\t\tRegisterHookDecoder(tSetter, bsoncodec.ValueDecoderFunc(SetterDecodeValue))\n\n\treturn rb\n}", "func newRegistry(builders []adapter.RegisterFn) *registry {\n\tr := &registry{make(BuildersByName)}\n\tfor idx, builder := range builders {\n\t\tglog.V(3).Infof(\"Registering [%d] %#v\", idx, builder)\n\t\tbuilder(r)\n\t}\n\t// ensure interfaces are satisfied.\n\t// should be compiled out.\n\tvar _ adapter.Registrar = r\n\tvar _ builderFinder = r\n\treturn r\n}", "func (m *Win32LobAppRegistryRule) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Win32LobAppRule.GetFieldDeserializers()\n res[\"check32BitOn64System\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetCheck32BitOn64System)\n res[\"comparisonValue\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetComparisonValue)\n res[\"keyPath\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKeyPath)\n res[\"operationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWin32LobAppRegistryRuleOperationType , m.SetOperationType)\n res[\"operator\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWin32LobAppRuleOperator , m.SetOperator)\n res[\"valueName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetValueName)\n return res\n}", "func NewListRegistryOK() *ListRegistryOK {\n\treturn &ListRegistryOK{}\n}", "func NewRegistryBuilder() *bsoncodec.RegistryBuilder {\n\trb := bsoncodec.NewRegistryBuilder()\n\tbsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb)\n\tbsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb)\n\tprimitiveCodecs.RegisterPrimitiveCodecs(rb)\n\treturn rb\n}", "func newAlfredWatcher() *alfredWatcher {\n w, _ := inotify.NewWatcher()\n aw := &alfredWatcher{\n watcher: w,\n list: make(map[string]uint32),\n }\n return aw\n}", "func NewRegistry(address common.Address, backend bind.ContractBackend) (*Registry, error) {\n\tcontract, err := bindRegistry(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Registry{RegistryCaller: RegistryCaller{contract: contract}, RegistryTransactor: RegistryTransactor{contract: contract}, RegistryFilterer: RegistryFilterer{contract: contract}}, nil\n}" ]
[ "0.69928527", "0.63613343", "0.6318046", "0.61856246", "0.5193109", "0.5166172", "0.51250374", "0.50861037", "0.5074907", "0.4938517", "0.49354273", "0.49308693", "0.4923182", "0.48366225", "0.48020795", "0.4768719", "0.4762157", "0.47500703", "0.47480088", "0.47457948", "0.47138864", "0.46902812", "0.46800044", "0.46622846", "0.4661411", "0.46299523", "0.46252912", "0.46078986", "0.46070394", "0.4595699", "0.45955405", "0.45832646", "0.4575747", "0.4569474", "0.45596096", "0.45301026", "0.4504634", "0.45023748", "0.45001176", "0.44998884", "0.44952232", "0.44671676", "0.44639376", "0.44589555", "0.44439495", "0.44332692", "0.44309023", "0.44305104", "0.44168958", "0.44140163", "0.4407839", "0.440678", "0.4404898", "0.43959117", "0.43875661", "0.43750593", "0.4373116", "0.436989", "0.43494648", "0.43421683", "0.4338302", "0.43287307", "0.4327358", "0.43224442", "0.4315271", "0.43136516", "0.43125498", "0.43113768", "0.43079445", "0.430135", "0.4298462", "0.428248", "0.4281313", "0.42748934", "0.42732334", "0.42719904", "0.42684227", "0.42676303", "0.42628476", "0.42532364", "0.42420155", "0.42385745", "0.42365184", "0.42338502", "0.42331633", "0.42325923", "0.42319733", "0.423154", "0.42215505", "0.4216715", "0.4209413", "0.4209028", "0.42081338", "0.42074665", "0.4206197", "0.42023224", "0.41970575", "0.41888008", "0.41861245", "0.41844708" ]
0.8352202
0
CreateWin32LobAppRegistryDetectionFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewWin32LobAppRegistryDetection(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}", "func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}", "func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}", "func CreateWindowsInformationProtectionDeviceRegistrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDeviceRegistration(), nil\n}", "func NewWin32LobAppRegistryDetection()(*Win32LobAppRegistryDetection) {\n m := &Win32LobAppRegistryDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppRegistryDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CreateAndroidLobAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidLobApp(), nil\n}", "func CreateRegistryKeyStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRegistryKeyState(), nil\n}", "func CreateApplicationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewApplication(), nil\n}", "func CreateDetectionRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDetectionRule(), nil\n}", "func CreateWindowsKioskProfileFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsKioskProfile(), nil\n}", "func CreateWindowsInformationProtectionDataRecoveryCertificateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDataRecoveryCertificate(), nil\n}", "func CreateManagedAppPolicyFromDiscriminatorValue(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.androidManagedAppProtection\":\n return NewAndroidManagedAppProtection(), nil\n case \"#microsoft.graph.defaultManagedAppProtection\":\n return NewDefaultManagedAppProtection(), nil\n case \"#microsoft.graph.iosManagedAppProtection\":\n return NewIosManagedAppProtection(), nil\n case \"#microsoft.graph.managedAppConfiguration\":\n return NewManagedAppConfiguration(), nil\n case \"#microsoft.graph.managedAppProtection\":\n return NewManagedAppProtection(), nil\n case \"#microsoft.graph.mdmWindowsInformationProtectionPolicy\":\n return NewMdmWindowsInformationProtectionPolicy(), nil\n case \"#microsoft.graph.targetedManagedAppConfiguration\":\n return NewTargetedManagedAppConfiguration(), nil\n case \"#microsoft.graph.targetedManagedAppProtection\":\n return NewTargetedManagedAppProtection(), nil\n case \"#microsoft.graph.windowsInformationProtection\":\n return NewWindowsInformationProtection(), nil\n case \"#microsoft.graph.windowsInformationProtectionPolicy\":\n return NewWindowsInformationProtectionPolicy(), nil\n }\n }\n }\n }\n return NewManagedAppPolicy(), nil\n}", "func CreateWindowsUniversalAppXFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsUniversalAppX(), nil\n}", "func CreateBookingBusinessFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBookingBusiness(), nil\n}", "func NewWin32LobAppRegistryRule()(*Win32LobAppRegistryRule) {\n m := &Win32LobAppRegistryRule{\n Win32LobAppRule: *NewWin32LobAppRule(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppRegistryRule\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func CreateWorkbookFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookFilter(), nil\n}", "func CreateAndroidCustomConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidCustomConfiguration(), 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 CreateIosDeviceTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceType(), nil\n}", "func CreateDriveFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDrive(), nil\n}", "func CreateServicePrincipalRiskDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewServicePrincipalRiskDetection(), nil\n}", "func CreateVulnerabilityFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewVulnerability(), nil\n}", "func CreateAndroidManagedStoreAppFromDiscriminatorValue(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.androidManagedStoreWebApp\":\n return NewAndroidManagedStoreWebApp(), nil\n }\n }\n }\n }\n return NewAndroidManagedStoreApp(), nil\n}", "func CreateMicrosoftManagedDesktopFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMicrosoftManagedDesktop(), nil\n}", "func CreateInformationProtectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewInformationProtection(), nil\n}", "func CreateWorkbookFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbook(), nil\n}", "func CreateMalwareFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMalware(), nil\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func CreateWorkforceIntegrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkforceIntegration(), nil\n}", "func CreateMicrosoftStoreForBusinessAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMicrosoftStoreForBusinessApp(), nil\n}", "func CreateAndroidWorkProfileGeneralDeviceConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidWorkProfileGeneralDeviceConfiguration(), nil\n}", "func CreateAndroidDeviceOwnerKioskModeAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidDeviceOwnerKioskModeApp(), nil\n}", "func CreateIosDeviceFeaturesConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewIosDeviceFeaturesConfiguration(), 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 CreateWindows10XVpnConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindows10XVpnConfiguration(), nil\n}", "func CreateDiscoveredSensitiveTypeFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDiscoveredSensitiveType(), nil\n}", "func CreateProgramControlFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewProgramControl(), nil\n}", "func CreateWorkbookOperationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookOperation(), nil\n}", "func CreateDeviceHealthFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceHealth(), nil\n}", "func CreateDeviceManagementIntentDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementIntentDeviceState(), nil\n}", "func CreateMacAppIdentifierFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMacAppIdentifier(), 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 CreateDeviceCategoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCategory(), nil\n}", "func CreateWorkbookWorksheetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookWorksheet(), nil\n}", "func CreateDeviceComplianceScriptDeviceStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceComplianceScriptDeviceState(), nil\n}", "func CreateAuthenticationMethodFromDiscriminatorValue(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.emailAuthenticationMethod\":\n return NewEmailAuthenticationMethod(), nil\n case \"#microsoft.graph.fido2AuthenticationMethod\":\n return NewFido2AuthenticationMethod(), nil\n case \"#microsoft.graph.microsoftAuthenticatorAuthenticationMethod\":\n return NewMicrosoftAuthenticatorAuthenticationMethod(), nil\n case \"#microsoft.graph.passwordAuthenticationMethod\":\n return NewPasswordAuthenticationMethod(), nil\n case \"#microsoft.graph.phoneAuthenticationMethod\":\n return NewPhoneAuthenticationMethod(), nil\n case \"#microsoft.graph.softwareOathAuthenticationMethod\":\n return NewSoftwareOathAuthenticationMethod(), nil\n case \"#microsoft.graph.temporaryAccessPassAuthenticationMethod\":\n return NewTemporaryAccessPassAuthenticationMethod(), nil\n case \"#microsoft.graph.windowsHelloForBusinessAuthenticationMethod\":\n return NewWindowsHelloForBusinessAuthenticationMethod(), nil\n }\n }\n }\n }\n return NewAuthenticationMethod(), nil\n}", "func CreateEdgeSearchEngineCustomFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewEdgeSearchEngineCustom(), nil\n}", "func CreateUserExperienceAnalyticsAnomalyDeviceFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUserExperienceAnalyticsAnomalyDevice(), nil\n}", "func CreateDeviceManagementConfigurationPolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationPolicy(), nil\n}", "func CreateAndroidCompliancePolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidCompliancePolicy(), nil\n}", "func CreateMobileAppInstallTimeSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMobileAppInstallTimeSettings(), nil\n}", "func CreateBrowserSiteListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBrowserSiteList(), nil\n}", "func CreateDeviceCompliancePolicyPolicySetItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceCompliancePolicyPolicySetItem(), nil\n}", "func CreateDeviceManagementSettingDependencyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettingDependency(), nil\n}", "func CreateWorkbookNamedItemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookNamedItem(), nil\n}", "func CreateDeviceManagementSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementSettings(), 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 CreateReminderFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReminder(), nil\n}", "func CreateUserExperienceAnalyticsDeviceStartupHistoryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewUserExperienceAnalyticsDeviceStartupHistory(), nil\n}", "func CreateIdentityProviderBaseFromDiscriminatorValue(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.appleManagedIdentityProvider\":\n return NewAppleManagedIdentityProvider(), nil\n case \"#microsoft.graph.builtInIdentityProvider\":\n return NewBuiltInIdentityProvider(), nil\n case \"#microsoft.graph.internalDomainFederation\":\n return NewInternalDomainFederation(), nil\n case \"#microsoft.graph.samlOrWsFedExternalDomainFederation\":\n return NewSamlOrWsFedExternalDomainFederation(), nil\n case \"#microsoft.graph.samlOrWsFedProvider\":\n return NewSamlOrWsFedProvider(), nil\n case \"#microsoft.graph.socialIdentityProvider\":\n return NewSocialIdentityProvider(), nil\n }\n }\n }\n }\n return NewIdentityProviderBase(), nil\n}", "func CreateGovernancePolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGovernancePolicy(), nil\n}", "func CreateDeviceEnrollmentWindowsHelloForBusinessConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceEnrollmentWindowsHelloForBusinessConfiguration(), nil\n}", "func CreateCustomAccessPackageWorkflowExtensionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCustomAccessPackageWorkflowExtension(), nil\n}", "func CreateConditionalAccessDeviceStatesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewConditionalAccessDeviceStates(), nil\n}", "func CreateMacOSMinimumOperatingSystemFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMacOSMinimumOperatingSystem(), nil\n}", "func CreateTargetManagerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewTargetManager(), nil\n}", "func CreateSchemaExtensionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchemaExtension(), nil\n}", "func CreateCommsNotificationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCommsNotification(), nil\n}", "func CreateMicrosoftStoreForBusinessContainedAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMicrosoftStoreForBusinessContainedApp(), 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 CreateMacOSEnterpriseWiFiConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMacOSEnterpriseWiFiConfiguration(), nil\n}", "func CreateExactMatchDataStoreFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewExactMatchDataStore(), nil\n}", "func CreateDeviceManagementConfigurationSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceManagementConfigurationSetting(), nil\n}", "func CreateCloudCommunicationsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewCloudCommunications(), nil\n}", "func CreateLabelActionBaseFromDiscriminatorValue(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.addFooter\":\n return NewAddFooter(), nil\n case \"#microsoft.graph.addHeader\":\n return NewAddHeader(), nil\n case \"#microsoft.graph.addWatermark\":\n return NewAddWatermark(), nil\n case \"#microsoft.graph.encryptContent\":\n return NewEncryptContent(), nil\n case \"#microsoft.graph.encryptWithTemplate\":\n return NewEncryptWithTemplate(), nil\n case \"#microsoft.graph.encryptWithUserDefinedRights\":\n return NewEncryptWithUserDefinedRights(), nil\n case \"#microsoft.graph.markContent\":\n return NewMarkContent(), nil\n case \"#microsoft.graph.protectGroup\":\n return NewProtectGroup(), nil\n case \"#microsoft.graph.protectOnlineMeetingAction\":\n return NewProtectOnlineMeetingAction(), nil\n case \"#microsoft.graph.protectSite\":\n return NewProtectSite(), nil\n }\n }\n }\n }\n return NewLabelActionBase(), nil\n}", "func CreateWindowsInformationProtectionAppLearningSummaryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionAppLearningSummary(), 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 CreateProtectGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewProtectGroup(), nil\n}", "func CreateSettingFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSetting(), nil\n}", "func CreateSchemaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSchema(), nil\n}", "func NewWin32LobAppProductCodeDetection()(*Win32LobAppProductCodeDetection) {\n m := &Win32LobAppProductCodeDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppProductCodeDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CreateBookingNamedEntityFromDiscriminatorValue(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.bookingBusiness\":\n return NewBookingBusiness(), nil\n case \"#microsoft.graph.bookingCustomer\":\n return NewBookingCustomer(), nil\n case \"#microsoft.graph.bookingPerson\":\n return NewBookingPerson(), nil\n case \"#microsoft.graph.bookingService\":\n return NewBookingService(), nil\n case \"#microsoft.graph.bookingStaffMember\":\n return NewBookingStaffMember(), nil\n }\n }\n }\n }\n return NewBookingNamedEntity(), nil\n}", "func CreateSetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSet(), nil\n}", "func CreateSynchronizationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSynchronization(), nil\n}", "func CreateManagedDeviceOverviewFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewManagedDeviceOverview(), nil\n}", "func CreateReportsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewReports(), nil\n}", "func CreateEdiscoverySearchFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewEdiscoverySearch(), nil\n}", "func CreateBusinessScenarioPlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBusinessScenarioPlanner(), nil\n}", "func NewDiscriminator(disc *low.Discriminator) *Discriminator {\n\td := new(Discriminator)\n\td.low = disc\n\td.PropertyName = disc.PropertyName.Value\n\tmapping := make(map[string]string)\n\tfor k, v := range disc.Mapping.Value {\n\t\tmapping[k.Value] = v.Value\n\t}\n\td.Mapping = mapping\n\treturn d\n}", "func CreateDeviceOperatingSystemSummaryFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeviceOperatingSystemSummary(), 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 CreateGroupFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewGroup(), nil\n}", "func CreateStoreFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewStore(), nil\n}", "func CreateSimulationAutomationRunFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewSimulationAutomationRun(), nil\n}", "func NewWin32LobAppFileSystemDetection()(*Win32LobAppFileSystemDetection) {\n m := &Win32LobAppFileSystemDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppFileSystemDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CreateWindowsMalwareCategoryCountFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsMalwareCategoryCount(), nil\n}", "func CreateListFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewList(), nil\n}", "func CreateBgpConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewBgpConfiguration(), nil\n}" ]
[ "0.79248315", "0.77870834", "0.7597286", "0.688303", "0.67968935", "0.6721281", "0.65258247", "0.64671457", "0.63796526", "0.6349763", "0.63148403", "0.63032705", "0.62638336", "0.6011352", "0.60016245", "0.59657604", "0.596529", "0.5954428", "0.59539", "0.59302485", "0.59269863", "0.5921153", "0.5904186", "0.59016657", "0.5858297", "0.5853009", "0.5837259", "0.58279717", "0.58147687", "0.5813939", "0.58047736", "0.5794352", "0.5787687", "0.57672393", "0.5756251", "0.57508004", "0.5746238", "0.5734532", "0.5719895", "0.57175887", "0.5678523", "0.56737775", "0.56572604", "0.56502455", "0.56296307", "0.55988467", "0.55982137", "0.5592573", "0.5592493", "0.55763495", "0.55710274", "0.5568849", "0.55654025", "0.5552103", "0.5545679", "0.5535747", "0.553499", "0.55279857", "0.5527332", "0.55253994", "0.5514523", "0.55018824", "0.549923", "0.5491537", "0.5488179", "0.54849666", "0.54847026", "0.5478803", "0.5471763", "0.54640037", "0.5444405", "0.54361045", "0.5430163", "0.5426218", "0.5411664", "0.5404786", "0.5401029", "0.53972435", "0.53972435", "0.53590536", "0.5352942", "0.5350009", "0.53453255", "0.5344177", "0.53434885", "0.53425086", "0.53415096", "0.5340402", "0.533636", "0.53312194", "0.53304344", "0.5322863", "0.5297177", "0.52962744", "0.5279372", "0.5276767", "0.5276371", "0.52758133", "0.5255852", "0.524863" ]
0.8787148
0
GetCheck32BitOn64System gets the check32BitOn64System property value. A value indicating whether this registry path is for checking 32bit app on 64bit system
func (m *Win32LobAppRegistryDetection) GetCheck32BitOn64System()(*bool) { val, err := m.GetBackingStore().Get("check32BitOn64System") if err != nil { panic(err) } if val != nil { return val.(*bool) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) GetCheck32BitOn64System()(*bool) {\n return m.check32BitOn64System\n}", "func (m *Win32LobAppFileSystemDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (m *Win32LobAppRegistryRule) SetCheck32BitOn64System(value *bool)() {\n m.check32BitOn64System = value\n}", "func (m *Win32LobAppRegistryDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppFileSystemDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}", "func Is64BitCPU() bool {\n\treturn strconv.IntSize == 64\n}", "func Xlstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_LSTAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"lstat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func GetSystemRegistryQuota(pdwQuotaAllowed *DWORD, pdwQuotaUsed *DWORD) bool {\n\tret1 := syscall3(getSystemRegistryQuota, 2,\n\t\tuintptr(unsafe.Pointer(pdwQuotaAllowed)),\n\t\tuintptr(unsafe.Pointer(pdwQuotaUsed)),\n\t\t0)\n\treturn ret1 != 0\n}", "func (m *MacOSMinimumOperatingSystem) GetV1012()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_12\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func SysInt64(name string) int64 {\r\n\treturn converter.StrToInt64(SysString(name))\r\n}", "func Is64(t *Type) bool", "func (r *AMD64Registers) Get(n int) (uint64, error) {\n\treg := x86asm.Reg(n)\n\tconst (\n\t\tmask8 = 0x000f\n\t\tmask16 = 0x00ff\n\t\tmask32 = 0xffff\n\t)\n\n\tswitch reg {\n\t// 8-bit\n\tcase x86asm.AL:\n\t\treturn r.rax & mask8, nil\n\tcase x86asm.CL:\n\t\treturn r.rcx & mask8, nil\n\tcase x86asm.DL:\n\t\treturn r.rdx & mask8, nil\n\tcase x86asm.BL:\n\t\treturn r.rbx & mask8, nil\n\tcase x86asm.AH:\n\t\treturn (r.rax >> 8) & mask8, nil\n\tcase x86asm.CH:\n\t\treturn (r.rcx >> 8) & mask8, nil\n\tcase x86asm.DH:\n\t\treturn (r.rdx >> 8) & mask8, nil\n\tcase x86asm.BH:\n\t\treturn (r.rbx >> 8) & mask8, nil\n\tcase x86asm.SPB:\n\t\treturn r.rsp & mask8, nil\n\tcase x86asm.BPB:\n\t\treturn r.rbp & mask8, nil\n\tcase x86asm.SIB:\n\t\treturn r.rsi & mask8, nil\n\tcase x86asm.DIB:\n\t\treturn r.rdi & mask8, nil\n\tcase x86asm.R8B:\n\t\treturn r.r8 & mask8, nil\n\tcase x86asm.R9B:\n\t\treturn r.r9 & mask8, nil\n\tcase x86asm.R10B:\n\t\treturn r.r10 & mask8, nil\n\tcase x86asm.R11B:\n\t\treturn r.r11 & mask8, nil\n\tcase x86asm.R12B:\n\t\treturn r.r12 & mask8, nil\n\tcase x86asm.R13B:\n\t\treturn r.r13 & mask8, nil\n\tcase x86asm.R14B:\n\t\treturn r.r14 & mask8, nil\n\tcase x86asm.R15B:\n\t\treturn r.r15 & mask8, nil\n\n\t// 16-bit\n\tcase x86asm.AX:\n\t\treturn r.rax & mask16, nil\n\tcase x86asm.CX:\n\t\treturn r.rcx & mask16, nil\n\tcase x86asm.DX:\n\t\treturn r.rdx & mask16, nil\n\tcase x86asm.BX:\n\t\treturn r.rbx & mask16, nil\n\tcase x86asm.SP:\n\t\treturn r.rsp & mask16, nil\n\tcase x86asm.BP:\n\t\treturn r.rbp & mask16, nil\n\tcase x86asm.SI:\n\t\treturn r.rsi & mask16, nil\n\tcase x86asm.DI:\n\t\treturn r.rdi & mask16, nil\n\tcase x86asm.R8W:\n\t\treturn r.r8 & mask16, nil\n\tcase x86asm.R9W:\n\t\treturn r.r9 & mask16, nil\n\tcase x86asm.R10W:\n\t\treturn r.r10 & mask16, nil\n\tcase x86asm.R11W:\n\t\treturn r.r11 & mask16, nil\n\tcase x86asm.R12W:\n\t\treturn r.r12 & mask16, nil\n\tcase x86asm.R13W:\n\t\treturn r.r13 & mask16, nil\n\tcase x86asm.R14W:\n\t\treturn r.r14 & mask16, nil\n\tcase x86asm.R15W:\n\t\treturn r.r15 & mask16, nil\n\n\t// 32-bit\n\tcase x86asm.EAX:\n\t\treturn r.rax & mask32, nil\n\tcase x86asm.ECX:\n\t\treturn r.rcx & mask32, nil\n\tcase x86asm.EDX:\n\t\treturn r.rdx & mask32, nil\n\tcase x86asm.EBX:\n\t\treturn r.rbx & mask32, nil\n\tcase x86asm.ESP:\n\t\treturn r.rsp & mask32, nil\n\tcase x86asm.EBP:\n\t\treturn r.rbp & mask32, nil\n\tcase x86asm.ESI:\n\t\treturn r.rsi & mask32, nil\n\tcase x86asm.EDI:\n\t\treturn r.rdi & mask32, nil\n\tcase x86asm.R8L:\n\t\treturn r.r8 & mask32, nil\n\tcase x86asm.R9L:\n\t\treturn r.r9 & mask32, nil\n\tcase x86asm.R10L:\n\t\treturn r.r10 & mask32, nil\n\tcase x86asm.R11L:\n\t\treturn r.r11 & mask32, nil\n\tcase x86asm.R12L:\n\t\treturn r.r12 & mask32, nil\n\tcase x86asm.R13L:\n\t\treturn r.r13 & mask32, nil\n\tcase x86asm.R14L:\n\t\treturn r.r14 & mask32, nil\n\tcase x86asm.R15L:\n\t\treturn r.r15 & mask32, nil\n\n\t// 64-bit\n\tcase x86asm.RAX:\n\t\treturn r.rax, nil\n\tcase x86asm.RCX:\n\t\treturn r.rcx, nil\n\tcase x86asm.RDX:\n\t\treturn r.rdx, nil\n\tcase x86asm.RBX:\n\t\treturn r.rbx, nil\n\tcase x86asm.RSP:\n\t\treturn r.rsp, nil\n\tcase x86asm.RBP:\n\t\treturn r.rbp, nil\n\tcase x86asm.RSI:\n\t\treturn r.rsi, nil\n\tcase x86asm.RDI:\n\t\treturn r.rdi, nil\n\tcase x86asm.R8:\n\t\treturn r.r8, nil\n\tcase x86asm.R9:\n\t\treturn r.r9, nil\n\tcase x86asm.R10:\n\t\treturn r.r10, nil\n\tcase x86asm.R11:\n\t\treturn r.r11, nil\n\tcase x86asm.R12:\n\t\treturn r.r12, nil\n\tcase x86asm.R13:\n\t\treturn r.r13, nil\n\tcase x86asm.R14:\n\t\treturn r.r14, nil\n\tcase x86asm.R15:\n\t\treturn r.r15, nil\n\t}\n\n\treturn 0, proc.ErrUnknownRegister\n}", "func (m *MacOSMinimumOperatingSystem) GetV110()(*bool) {\n val, err := m.GetBackingStore().Get(\"v11_0\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (h *ZipDirEntry) isZip64() bool {\n\treturn h.CompressedSize64 >= uint32max || h.UncompressedSize64 >= uint32max\n}", "func (m *MacOSMinimumOperatingSystem) GetV1011()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_11\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (m *MacOSMinimumOperatingSystem) GetV108()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_8\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func GetInt64(key string) int64 {\n\ts, contains := getFromMode(key)\n\tif !contains {\n\t\ts, contains = getFromGlobal(key)\n\t}\n\tif contains {\n\t\ti, err := strconv.ParseInt(s, 10, 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"GetInt64 error:\", err)\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\tfmt.Println(\"values of\", key, \"is not set!\")\n\treturn 0\n}", "func GetUint64(key string, def uint64) uint64 {\n\ts, ok := os.LookupEnv(key)\n\tif !ok {\n\t\treturn def\n\t}\n\n\tv, err := strconv.ParseUint(s, decimalBase, bitSize64)\n\tif err != nil {\n\t\treturn def\n\t}\n\n\treturn v\n}", "func (this *DatastoreConfigSnapshot) GetInt64(key string) (value int64, err error) {\n\t// If a datastore-specific configuration is available\n\tif this.DedicatedConfig != nil {\n\t\t// Lookup the value for the given key\n\t\tvalue, err = this.DedicatedConfig.GetInt64(key)\n\n\t\t// If the key was found\n\t\tif err == nil {\n\t\t\t// Return its value\n\t\t\treturn\n\t\t}\n\t}\n\n\tif this.GlobalConfig == nil {\n\t\treturn\n\t}\n\n\t// Otherwise, look up the key in the global configuration and return its value if found\n\treturn this.GlobalConfig.GetInt64(key)\n}", "func (m *MacOSMinimumOperatingSystem) GetV1010()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_10\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func Xfstat64(tls TLS, fildes int32, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_FSTAT64, uintptr(fildes), buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"fstat64(%v, %#x) %v %v\\n\", fildes, buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func Xstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_STAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"stat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func PtraceGetRegsMips64le(pid int, regsout *PtraceRegsMips64le) error {\r\n\treturn ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))\r\n}", "func PropValNum64(reply *xproto.GetPropertyReply, err error) (int64, error) {\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif reply.Format != 32 {\n\t\treturn 0, fmt.Errorf(\"PropValNum: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\treturn int64(xgb.Get32(reply.Value)), nil\n}", "func (this *DynMap) GetInt64(key string) (int64, bool) {\n\ttmp, ok := this.Get(key)\n\tif !ok {\n\t\treturn -1, ok\n\t}\n\tval, err := ToInt64(tmp)\n\tif err == nil {\n\t\treturn val, true\n\t}\n\treturn -1, false\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}", "func MSB64(x uint64) uint64", "func GetLogicalProcessorInformationEx(relationshipType LOGICAL_PROCESSOR_RELATIONSHIP, buffer LPWSTR, returnedLength *DWORD) DWORD {\n\tret1 := syscall3(getLogicalProcessorInformationEx, 3,\n\t\tuintptr(relationshipType),\n\t\tuintptr(unsafe.Pointer(buffer)),\n\t\tuintptr(unsafe.Pointer(returnedLength)))\n\treturn DWORD(ret1)\n}", "func (b *Bus) Read64(addr mirv.Address) (uint64, error) {\n\tblk := b.p\n\tif !blk.contains(addr) {\n\t\tblk = b.find(addr)\n\t}\n\treturn blk.m.Read64(addr - blk.s)\n}", "func (b *BananaPhone) GetSysID(funcname string) (uint16, error) {\n\tr, e := b.getSysID(funcname, 0, false)\n\tif e != nil {\n\t\tvar err MayBeHookedError\n\t\tif b.isAuto && errors.As(e, &err) {\n\t\t\tvar e2 error\n\t\t\tb.banana, e2 = pe.Open(`C:\\Windows\\system32\\ntdll.dll`)\n\t\t\tif e2 != nil {\n\t\t\t\treturn 0, e2\n\t\t\t}\n\t\t\tr, e = b.getSysID(funcname, 0, false)\n\t\t}\n\t}\n\treturn r, e\n}", "func (me TdtypeType) IsWinreg() bool { return me.String() == \"winreg\" }", "func getTickCount64() int64 {\n\tret, _, _ := procGetTickCount64.Call()\n\treturn int64(ret)\n}", "func (m *MacOSMinimumOperatingSystem) GetV1015()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_15\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (c *Config) GetUint64(pattern string, def ...interface{}) uint64 {\n\tif j := c.getJson(); j != nil {\n\t\treturn j.GetUint64(pattern, def...)\n\t}\n\treturn 0\n}", "func GetSystemRLimit() (uint64, error) {\n\treturn math.MaxInt32, nil\n}", "func Len64(x uint64) (n int) {\n\tif x >= 1<<32 {\n\t\tx >>= 32\n\t\tn = 32\n\t}\n\tif x >= 1<<16 {\n\t\tx >>= 16\n\t\tn += 16\n\t}\n\tif x >= 1<<8 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\treturn n + int(len8tab[x])\n}", "func Len64(x uint64) (n int) {\n\tif x >= 1<<32 {\n\t\tx >>= 32\n\t\tn = 32\n\t}\n\tif x >= 1<<16 {\n\t\tx >>= 16\n\t\tn += 16\n\t}\n\tif x >= 1<<8 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\treturn n + int(len8tab[x])\n}", "func GetenvInt64(key string, dflt ...int64) int64 {\n\tif val := strings.TrimSpace(os.Getenv(key)); val != \"\" {\n\t\tif b, err := strconv.ParseInt(val, 0, 64); err == nil {\n\t\t\treturn b\n\t\t}\n\t}\n\n\tif len(dflt) > 0 {\n\t\treturn dflt[0]\n\t}\n\n\treturn 0\n}", "func GetInt64(section, option string) int64 {\n\treturn cfg.GetInt64(section, option)\n}", "func (m *MacOSMinimumOperatingSystem) GetV1014()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_14\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func BKDRHash64(str string) uint64 {\n\tlist := []byte(str)\n\tvar seed uint64 = 131 // 31 131 1313 13131 131313 etc..\n\tvar hash uint64 = 0\n\tfor i := 0; i < len(list); i++ {\n\t\thash = hash*seed + uint64(list[i])\n\t}\n\treturn (hash & 0x7FFFFFFFFFFFFFFF)\n}", "func GetInt64Value(model ModelT, t TermT, val *int64) int32 {\n\treturn int32(C.yices_get_int64_value(ymodel(model), C.term_t(t), (*C.int64_t)(val)))\n}", "func (m *AndroidManagedStoreApp) GetIsSystemApp()(*bool) {\n val, err := m.GetBackingStore().Get(\"isSystemApp\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (c *Config) GetInt64(pattern string, def ...interface{}) int64 {\n\tif j := c.getJson(); j != nil {\n\t\treturn j.GetInt64(pattern, def...)\n\t}\n\treturn 0\n}", "func (c *Config) GetI64(name string, defvals ...int64) int64 {\n\tif c == nil || c.mx == nil {\n\t\tif len(defvals) == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\treturn defvals[0]\n\t}\n\n\tc.mx.RLock()\n\tval := c.data[strings.ToLower(name)]\n\tc.mx.RUnlock()\n\n\tif val == \"\" {\n\t\tif len(defvals) == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\treturn defvals[0]\n\t}\n\n\t// HEX Parsing\n\tif len(val) >= 3 && val[0:2] == \"0x\" {\n\t\tvalHex, err := strconv.ParseInt(val[2:], 16, 0)\n\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\n\t\treturn valHex\n\t}\n\n\tvalInt, err := strconv.ParseInt(val, 10, 0)\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn valInt\n}", "func IsMacSysExt() bool {\n\tif runtime.GOOS != \"darwin\" {\n\t\treturn false\n\t}\n\tif b, ok := isMacSysExt.Load().(bool); ok {\n\t\treturn b\n\t}\n\texe, err := os.Executable()\n\tif err != nil {\n\t\treturn false\n\t}\n\tv := filepath.Base(exe) == \"io.tailscale.ipn.macsys.network-extension\"\n\tisMacSysExt.Store(v)\n\treturn v\n}", "func TestGet64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestGetN(testN, hm)\n}", "func Wow64RevertWow64FsRedirection(olValue uintptr) bool {\n\tret1 := syscall3(wow64RevertWow64FsRedirection, 1,\n\t\tolValue,\n\t\t0,\n\t\t0)\n\treturn ret1 != 0\n}", "func (payload *Payload) GetInt64(key string) (int64, bool) {\n\tval, ok := payload.data[key]\n\treturn convertToInt64(val, false), ok\n}", "func (m *MacOSMinimumOperatingSystem) GetV109()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_9\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (n *node64s) Match(key uint64, bits int) (*node64, bool) {\n\tif n == nil {\n\t\treturn nil, false\n\t}\n\n\tif bits < 0 {\n\t\tbits = 0\n\t} else if bits > key64BitSize {\n\t\tbits = key64BitSize\n\t}\n\n\tr := n.match(key, uint8(bits))\n\tif r == nil {\n\t\treturn nil, false\n\t}\n\n\treturn r.value, true\n}", "func opUI64Bitshl(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) << ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (m *MacOSMinimumOperatingSystem) GetV120()(*bool) {\n val, err := m.GetBackingStore().Get(\"v12_0\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func CLZ64(in int64) int32 {\n\tin_upper := int32(in >> 32)\n\tif in_upper == 0 {\n\t\treturn 32 + CLZ32(int32(in))\n\t} else {\n\t\t/* Search in the upper 32 bits */\n\t\treturn CLZ32(in_upper)\n\t}\n}", "func GetSystemInfo(args []string) util.NativeCmdResult {\n\treturn util.NativeCmdResult{\n\t\tStdout: []byte(getSystemInfo()),\n\t\tStderr: nil,\n\t\tErr: nil,\n\t\tExitCode: util.SUCCESS_EXIT_CODE,\n\t}\n}", "func (p *PCG64) Uint32() uint32 {\n\treturn uint32(p.Uint64() >> 32)\n}", "func GetUint64(section, option string) uint64 {\n\treturn cfg.GetUint64(section, option)\n}", "func mipsOpcode32bit(opc *mipsOpcode) bool {\n\treturn (opc.mask >> 16) != 0\n}", "func isARM64Instance(instanceType string) bool {\n\tr := regexp.MustCompile(\"(a1|.\\\\dgd?)\\\\.(medium|\\\\d*x?large|metal)\")\n\tif r.MatchString(instanceType) {\n\t\treturn true\n\t}\n\treturn false\n}", "func WindowsWorkstationChecks() {\n\n}", "func readll() int64 {\n\treturn readInt64()\n}", "func (m *MacOSMinimumOperatingSystem) GetV107()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_7\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (r *AMD64Registers) TLS() uint64 {\n\treturn r.tls\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetSecurityRequireVerifyApps()(*bool) {\n return m.securityRequireVerifyApps\n}", "func readll() int64 {\n\treturn _readInt64()\n}", "func readll() int64 {\n\treturn _readInt64()\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfileRequirePassword()(*bool) {\n return m.workProfileRequirePassword\n}", "func getRegBin(root registry.Key, path string, name string) ([]byte, error) {\n\tkey, err := registry.OpenKey(root, path, registry.READ)\n\tdefer key.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbin, _, err := key.GetBinaryValue(name)\n\treturn bin, err\n}", "func (p *Config) GetNativeProcessorType(programHash hashing.HashValue) (string, bool) {\n\tif _, ok := p.coreContracts[programHash]; ok {\n\t\treturn vmtypes.Core, true\n\t}\n\tif _, ok := p.GetNativeProcessor(programHash); ok {\n\t\treturn vmtypes.Native, true\n\t}\n\treturn \"\", false\n}", "func WindowsType() {\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`, registry.QUERY_VALUE)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer k.Close()\n\n\ts, _, err := k.GetStringValue(\"EditionID\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif strings.Contains(s, \"Server\") {\n\t\tWindowsServerChecks()\n\t} else {\n\t\tWindowsWorkstationChecks()\n\t}\n}", "func (s *Store) Hash64() uint64 {\n\treturn s.txthash\n}", "func (m *Win32LobAppRegistryRule) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Win32LobAppRule.GetFieldDeserializers()\n res[\"check32BitOn64System\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetCheck32BitOn64System)\n res[\"comparisonValue\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetComparisonValue)\n res[\"keyPath\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKeyPath)\n res[\"operationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWin32LobAppRegistryRuleOperationType , m.SetOperationType)\n res[\"operator\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWin32LobAppRuleOperator , m.SetOperator)\n res[\"valueName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetValueName)\n return res\n}", "func opI64Bitshl(expr *CXExpression, fp int) {\n\toutB0 := int64(ReadI64(fp, expr.Inputs[0]) << uint64(ReadI64(fp, expr.Inputs[1])))\n\tWriteI64(GetOffset_i64(fp, expr.Outputs[0]), outB0)\n}", "func (*OpenconfigSystem_System_Cpus_Cpu) IsYANGGoStruct() {}", "func Uint64(name string, defaultValue uint64) uint64 {\n\tif strVal, ok := os.LookupEnv(name); ok {\n\t\tif i64, err := strconv.ParseUint(strVal, 10, 64); err == nil {\n\t\t\treturn i64\n\t\t}\n\t}\n\n\treturn defaultValue\n}", "func (r *ARM64Registers) GAddr() (uint64, bool) {\n\treturn r.Regs[28], !r.iscgo\n}", "func (m *WindowsMalwareCategoryCount) GetActiveMalwareDetectionCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"activeMalwareDetectionCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func readVarInt64(r io.Reader) (int64, error) {\n\t// Since we are being given seven bits per byte, we can fit 9 1/8 bytes\n\t// of input into our eight bytes of value, so don't read more than 10 bytes.\n\tbits, err := readVarNumber(10, r)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// 0xFE == 0b1111_1110.\n\tif (len(bits) == 10) && (bits[9]&0xFE != 0) {\n\t\treturn 0, errors.Errorf(\"number is too big to fit into int64: % #x\", bits)\n\t}\n\n\tvar ret int64\n\t// Compact all of the bits into an int64, ignoring the stop bit.\n\t// Turn [0111 1111] [1110 1111] into [0011 1111] [1110 1111].\n\tfor i, b := range bits {\n\t\tret <<= 7\n\t\t// Need to ignore the sign bit. We add the sign later.\n\t\tif i == 0 {\n\t\t\tret |= int64(b & 0x3F)\n\t\t} else {\n\t\t\tret |= int64(b & 0x7F)\n\t\t}\n\t}\n\n\t// The second bit of the number is the sign bit.\n\tif bits[0]&0x40 != 0 {\n\t\tret *= -1\n\t}\n\n\treturn ret, nil\n}", "func eb64(bits uint64, hi uint8, lo uint8) uint64 {\n\tm := uint64(((1 << (hi - lo)) - 1) << lo)\n\treturn (bits & m) >> lo\n}", "func (rw *ReadWrite) GetInt64() int64 {\n\tshift := uint(0)\n\tn := uint64(0)\n\tfor {\n\t\tb := rw.GetByte_()\n\t\tn |= uint64(b&0x7f) << shift\n\t\tshift += 7\n\t\tif 0 == (b & 0x80) {\n\t\t\tbreak\n\t\t}\n\t}\n\ttmp := ((int64(n<<63) >> 63) ^ int64(n)) >> 1\n\ttmp = tmp ^ int64(n&(1<<63))\n\treturn tmp\n}", "func (m *DeviceHealthAttestationState) GetBitLockerStatus()(*string) {\n val, err := m.GetBackingStore().Get(\"bitLockerStatus\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *TeamworkSoftwareUpdateHealth) GetOperatingSystemSoftwareUpdateStatus()(TeamworkSoftwareUpdateStatusable) {\n val, err := m.GetBackingStore().Get(\"operatingSystemSoftwareUpdateStatus\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(TeamworkSoftwareUpdateStatusable)\n }\n return nil\n}", "func GetHandleInformation(hObject HANDLE, lpdwFlags *uint32) bool {\n\tret1 := syscall3(getHandleInformation, 2,\n\t\tuintptr(hObject),\n\t\tuintptr(unsafe.Pointer(lpdwFlags)),\n\t\t0)\n\treturn ret1 != 0\n}", "func shift64RightJamming(a uint64, count int16) uint64 {\n\tif count == 0 {\n\t\treturn a\n\t} else if count < 64 {\n\t\treturn a>>count | x1((a<<((-count)&63)) != 0)\n\t} else if a != 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func count64(bitMask []uint64) (result uint64) {\n\n\tfor i := 0; i < len(bitMask); i++ {\n\t\tresult += uint64(bits.OnesCount64(bitMask[i]))\n\t}\n\treturn\n}", "func TestGetInt64Var(t *testing.T) {\n\tfor _, tt := range getInt64VarFlagTests {\n\t\tt.Run(tt.valueIn, func(t *testing.T) {\n\t\t\tos.Clearenv()\n\n\t\t\tif err := os.Setenv(variableName, tt.valueIn); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tv, err := GetInt64Var(variableName, tt.fallback)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tif v != tt.valueOut {\n\t\t\t\tt.Errorf(\"Variable %s not equal to value '%v'\", variableName, tt.valueOut)\n\t\t\t}\n\t\t})\n\t}\n}", "func (o SharedAccessPolicyOutput) RegistryRead() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *SharedAccessPolicy) pulumi.BoolPtrOutput { return v.RegistryRead }).(pulumi.BoolPtrOutput)\n}", "func (m *Win32LobAppRegistryDetection) GetOperator()(*Win32LobAppDetectionOperator) {\n val, err := m.GetBackingStore().Get(\"operator\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppDetectionOperator)\n }\n return nil\n}", "func (c *Config) GetU64(name string, defvals ...uint64) uint64 {\n\tif len(defvals) != 0 {\n\t\treturn uint64(c.GetI64(name, int64(defvals[0])))\n\t}\n\n\treturn uint64(c.GetI64(name))\n}", "func (*OpenconfigSystem_System_Cpus_Cpu_State_Total) IsYANGGoStruct() {}", "func (me *BitStream) ReadBitsLong(n int) uint32 {\n\ttmp := me.ShowBitsLong(n)\n\tme.Index += n\n\treturn tmp\n}", "func (child MagicU32) MagicBit() bool {\n\treturn (child & (1 << 31)) > 0\n}", "func hash64(key, mask uint64) uint64 {\n\tkey = (^key + (key << 21)) & mask\n\tkey = key ^ key>>24\n\tkey = ((key + (key << 3)) + (key << 8)) & mask\n\tkey = key ^ key>>14\n\tkey = ((key + (key << 2)) + (key << 4)) & mask\n\tkey = key ^ key>>28\n\tkey = (key + (key << 31)) & mask\n\treturn key\n}", "func (difficulty *Difficulty) Bits() uint32 {\n\tdifficulty.RLock()\n\tdefer difficulty.RUnlock()\n\treturn difficulty.bits\n}", "func GetUint64(key string) uint64 { return viper.GetUint64(key) }", "func cpuidMaxExt() uint32 {\n\teax, _, _, _ := cpuid(0x80000000, 0)\n\treturn eax\n}", "func (c *Config) GetFloat64(pattern string, def ...interface{}) float64 {\n\tif j := c.getJson(); j != nil {\n\t\treturn j.GetFloat64(pattern, def...)\n\t}\n\treturn 0\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfilePasswordBlockTrustAgents()(*bool) {\n return m.workProfilePasswordBlockTrustAgents\n}", "func FindX86_64ReturnInstructions(data []byte) ([]uint64, error) {\n\t// x86_64 => mode is 64\n\tmode := 64\n\treturnOffsets := []uint64{}\n\tcursor := 0\n\tfor cursor < len(data) {\n\t\tinstruction, err := x86asm.Decode(data[cursor:], mode)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to decode x86-64 instruction at offset %d within function machine code: %w\", cursor, err)\n\t\t}\n\n\t\tif instruction.Op == x86asm.RET {\n\t\t\treturnOffsets = append(returnOffsets, uint64(cursor))\n\t\t}\n\n\t\tcursor += instruction.Len\n\t}\n\n\treturn returnOffsets, nil\n}" ]
[ "0.8441771", "0.818702", "0.74417126", "0.7327586", "0.7049355", "0.5609109", "0.50374573", "0.49397087", "0.48814422", "0.48766637", "0.4864678", "0.48252845", "0.4820567", "0.47325158", "0.46962094", "0.46929163", "0.46125704", "0.45937026", "0.4560345", "0.45471245", "0.4529155", "0.45218644", "0.4520674", "0.44994944", "0.44990066", "0.44902235", "0.44824266", "0.44645318", "0.44622156", "0.44516936", "0.44454378", "0.44323182", "0.44282085", "0.44237906", "0.44053268", "0.44016185", "0.43857712", "0.43857712", "0.43533853", "0.43492156", "0.4341166", "0.43294477", "0.4316951", "0.4311765", "0.4311726", "0.42754737", "0.42689148", "0.4260943", "0.42584434", "0.4256384", "0.42542896", "0.4245955", "0.42414805", "0.42334566", "0.42333746", "0.42206064", "0.421985", "0.4211203", "0.42094335", "0.4196513", "0.41835508", "0.41822508", "0.4179998", "0.41718158", "0.41681945", "0.4166207", "0.4166207", "0.4162602", "0.4159575", "0.41358107", "0.4133287", "0.413192", "0.4129827", "0.41288748", "0.41277313", "0.41255686", "0.41253632", "0.41179746", "0.41168463", "0.41154662", "0.41148135", "0.411464", "0.4103921", "0.40986958", "0.40971324", "0.4088451", "0.4084642", "0.40838197", "0.4079134", "0.4076733", "0.40755016", "0.40744394", "0.407093", "0.4069786", "0.40692535", "0.40663984", "0.4064258", "0.40626523", "0.40601918", "0.405494" ]
0.83624035
1
GetDetectionType gets the detectionType property value. Contains all supported registry data detection type.
func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) { val, err := m.GetBackingStore().Get("detectionType") if err != nil { panic(err) } if val != nil { return val.(*Win32LobAppRegistryDetectionType) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppFileSystemDetection) GetDetectionType()(*Win32LobAppFileSystemDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppFileSystemDetectionType)\n }\n return nil\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *ServicePrincipalRiskDetection) GetDetectionTimingType()(*RiskDetectionTimingType) {\n val, err := m.GetBackingStore().Get(\"detectionTimingType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RiskDetectionTimingType)\n }\n return nil\n}", "func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (f *feature) GetType() FeatureTypes {\n\treturn f.Type\n}", "func (r *Registration) GetRegistryAuthorizationType() string {\n\tvar auth string\n\tif r.Metadata != nil && r.Metadata.Properties != nil {\n\t\tif v, ok := r.Metadata.Properties[authorizationType]; ok {\n\t\t\tauth = v\n\t\t}\n\t}\n\n\tif auth != authorizationBasic && auth != authorizationBearer {\n\t\tauth = authorizationBasic\n\t}\n\n\treturn auth\n}", "func (r Virtual_Guest) GetGpuType() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getGpuType\", nil, &r.Options, &resp)\n\treturn\n}", "func GetTypeEnum(val reflect.Type) (ret int, err error) {\n\tswitch val.Kind() {\n\tcase reflect.Int8:\n\t\tret = TypeBitField\n\tcase reflect.Uint8:\n\t\tret = TypePositiveBitField\n\tcase reflect.Int16:\n\t\tret = TypeSmallIntegerField\n\tcase reflect.Uint16:\n\t\tret = TypePositiveSmallIntegerField\n\tcase reflect.Int32:\n\t\tret = TypeInteger32Field\n\tcase reflect.Uint32:\n\t\tret = TypePositiveInteger32Field\n\tcase reflect.Int64:\n\t\tret = TypeBigIntegerField\n\tcase reflect.Uint64:\n\t\tret = TypePositiveBigIntegerField\n\tcase reflect.Int:\n\t\tret = TypeIntegerField\n\tcase reflect.Uint:\n\t\tret = TypePositiveIntegerField\n\tcase reflect.Float32:\n\t\tret = TypeFloatField\n\tcase reflect.Float64:\n\t\tret = TypeDoubleField\n\tcase reflect.Bool:\n\t\tret = TypeBooleanField\n\tcase reflect.String:\n\t\tret = TypeStringField\n\tcase reflect.Struct:\n\t\tswitch val.String() {\n\t\tcase \"time.Time\":\n\t\t\tret = TypeDateTimeField\n\t\tdefault:\n\t\t\tret = TypeStructField\n\t\t}\n\tcase reflect.Slice:\n\t\tret = TypeSliceField\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupport field type:%v\", val.String())\n\t}\n\n\treturn\n}", "func (m *Device) GetKind() (val string, set bool) {\n\tif m.Kind == nil {\n\t\treturn\n\t}\n\n\treturn *m.Kind, true\n}", "func (o *PlatformImage) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func GetBuiltinProcessorType(programHash hashing.HashValue) (string, bool) {\n\tif _, err := core.GetProcessor(programHash); err == nil {\n\t\treturn core.VMType, true\n\t}\n\tif _, ok := native.GetProcessor(programHash); ok {\n\t\treturn native.VMType, true\n\t}\n\treturn \"\", false\n}", "func (o *MonitorSearchResult) GetClassification() string {\n\tif o == nil || o.Classification == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Classification\n}", "func (f *Forest) GetTypeSyncer(gvk schema.GroupVersionKind) TypeSyncer {\n\tfor _, t := range f.types {\n\t\tif t.GetGVK() == gvk {\n\t\t\treturn t\n\t\t}\n\t}\n\treturn nil\n}", "func (m *WindowsInformationProtectionDeviceRegistration) GetDeviceType()(*string) {\n val, err := m.GetBackingStore().Get(\"deviceType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *Ga4ghChemotherapy) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (m *FileEvidence) GetDetectionStatus()(*DetectionStatus) {\n val, err := m.GetBackingStore().Get(\"detectionStatus\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*DetectionStatus)\n }\n return nil\n}", "func DetectRendererType(filename string, input io.Reader) string {\n\tbuf, err := io.ReadAll(input)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tfor _, renderer := range renderers {\n\t\tif detector, ok := renderer.(RendererContentDetector); ok && detector.CanRender(filename, bytes.NewReader(buf)) {\n\t\t\treturn renderer.Name()\n\t\t}\n\t}\n\treturn \"\"\n}", "func (r Virtual_Storage_Repository) GetType() (resp datatypes.Virtual_Storage_Repository_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Storage_Repository\", \"getType\", nil, &r.Options, &resp)\n\treturn\n}", "func (m *Device) GetType() (val string, set bool) {\n\tif m.Type == nil {\n\t\treturn\n\t}\n\n\treturn *m.Type, true\n}", "func GetDetector(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *DetectorState, opts ...pulumi.ResourceOption) (*Detector, error) {\n\tvar resource Detector\n\terr := ctx.ReadResource(\"aws-native:guardduty:Detector\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *ConsulServiceRegistry) Kind() string {\n\treturn Kind\n}", "func (m *RegistryKeyState) GetValueType()(*RegistryValueType) {\n return m.valueType\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\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 (r Notification_Occurrence_Event) GetNotificationOccurrenceEventType() (resp datatypes.Notification_Occurrence_Event_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Notification_Occurrence_Event\", \"getNotificationOccurrenceEventType\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *VerificationTraits) GetType() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Type\n}", "func (o *LogsPipelineProcessor) GetType() LogsPipelineProcessorType {\n\tif o == nil {\n\t\tvar ret LogsPipelineProcessorType\n\t\treturn ret\n\t}\n\treturn o.Type\n}", "func (o *EquipmentBaseSensor) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (r Virtual_Disk_Image) GetType() (resp datatypes.Virtual_Disk_Image_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Disk_Image\", \"getType\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *AutoscalerResourceLimitsGPULimit) GetType() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&2 != 0\n\tif ok {\n\t\tvalue = o.type_\n\t}\n\treturn\n}", "func (si *SexpHashSelector) Type() *RegisteredType {\n\treturn GoStructRegistry.Lookup(\"hashSelector\")\n}", "func (r *ociClient) Type() string {\n\treturn cdv2.OCIRegistryType\n}", "func (m *DeviceComplianceScriptDeviceState) GetDetectionState()(*RunState) {\n val, err := m.GetBackingStore().Get(\"detectionState\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RunState)\n }\n return nil\n}", "func (d *Driver) Type() string {\n\treturn string(d.ecosystem)\n}", "func (o *SyntheticsBrowserTest) GetType() SyntheticsBrowserTestType {\n\tif o == nil {\n\t\tvar ret SyntheticsBrowserTestType\n\t\treturn ret\n\t}\n\treturn o.Type\n}", "func (o *KubernetesEthernetMatcher) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (r Virtual_Guest_Block_Device_Template_Group) GetImageType() (resp datatypes.Virtual_Disk_Image_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"getImageType\", nil, &r.Options, &resp)\n\treturn\n}", "func GetType(entropyName string) uint32 {\n\tswitch strings.ToUpper(entropyName) {\n\n\tcase \"HUFFMAN\":\n\t\treturn HUFFMAN_TYPE\n\n\tcase \"ANS0\":\n\t\treturn ANS0_TYPE\n\n\tcase \"ANS1\":\n\t\treturn ANS1_TYPE\n\n\tcase \"RANGE\":\n\t\treturn RANGE_TYPE\n\n\tcase \"FPAQ\":\n\t\treturn FPAQ_TYPE\n\n\tcase \"CM\":\n\t\treturn CM_TYPE\n\n\tcase \"TPAQ\":\n\t\treturn TPAQ_TYPE\n\n\tcase \"TPAQX\":\n\t\treturn TPAQX_TYPE\n\n\tcase \"NONE\":\n\t\treturn NONE_TYPE\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported entropy codec type: '%s'\", entropyName))\n\t}\n}", "func (hfsc *HfscClass) Type() string {\n\treturn \"hfsc\"\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) GetRuleType()(*DeviceManagementApplicabilityRuleType) {\n val, err := m.GetBackingStore().Get(\"ruleType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*DeviceManagementApplicabilityRuleType)\n }\n return nil\n}", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (p *Config) GetNativeProcessorType(programHash hashing.HashValue) (string, bool) {\n\tif _, ok := p.coreContracts[programHash]; ok {\n\t\treturn vmtypes.Core, true\n\t}\n\tif _, ok := p.GetNativeProcessor(programHash); ok {\n\t\treturn vmtypes.Native, true\n\t}\n\treturn \"\", false\n}", "func (o *Ga4ghSearchFusionDetectionResponse) GetFusiondetection() []Ga4ghFusionDetection {\n\tif o == nil || o.Fusiondetection == nil {\n\t\tvar ret []Ga4ghFusionDetection\n\t\treturn ret\n\t}\n\treturn *o.Fusiondetection\n}", "func GetType(value reflect.Type) Type {\n\tindirect := GetIndirectType(value)\n\tswitch indirect.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn Int64Type\n\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn Int64Type\n\n\tcase reflect.String:\n\t\treturn StringType\n\n\tcase reflect.Struct:\n\t\tif indirect == nullStringType {\n\t\t\treturn OptionalStringType\n\t\t}\n\t\tif indirect == nullInt64Type {\n\t\t\treturn OptionalInt64Type\n\t\t}\n\t}\n\treturn UnsupportedType\n}", "func (image *Image) GetType() string {\n\treturn \"Microsoft.Compute/images\"\n}", "func (m *Drive) GetDriveType()(*string) {\n return m.driveType\n}", "func (o *MonitorSearchResult) GetType() MonitorType {\n\tif o == nil || o.Type == nil {\n\t\tvar ret MonitorType\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (d UserData) Type() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"Type\", \"type\"))\n\tif !d.Has(models.NewFieldName(\"Type\", \"type\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (r Virtual_Guest) GetType() (resp datatypes.Virtual_Guest_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getType\", nil, &r.Options, &resp)\n\treturn\n}", "func (m *MatchInfo) GetGameType(client *static.Client) (static.GameType, error) {\n\treturn client.GetGameType(m.GameType)\n}", "func (m *Property) GetType() (val string, set bool) {\n\tif m.Type == nil {\n\t\treturn\n\t}\n\n\treturn *m.Type, true\n}", "func (o *Ga4ghTumourboard) GetTypeOfValidation() string {\n\tif o == nil || o.TypeOfValidation == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.TypeOfValidation\n}", "func getRegistryType(fullType string) *registry.Type {\n\ttList := strings.Split(fullType, \":\")\n\tif len(tList) != 2 {\n\t\treturn nil\n\t}\n\n\treturn &registry.Type{\n\t\tName: tList[0],\n\t\tVersion: tList[1],\n\t}\n}", "func (c *DNSChecker) Type() string {\n\treturn \"dns\"\n}", "func (c *DNSChecker) Type() string {\n\treturn \"dns\"\n}", "func (machine *VirtualMachine) GetType() string {\n\treturn \"Microsoft.Compute/virtualMachines\"\n}", "func (machine *VirtualMachine) GetType() string {\n\treturn \"Microsoft.Compute/virtualMachines\"\n}", "func (r Virtual_Disk_Image) GetStorageRepositoryType() (resp datatypes.Virtual_Storage_Repository_Type, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Disk_Image\", \"getStorageRepositoryType\", nil, &r.Options, &resp)\n\treturn\n}", "func (o GuestOsFeatureOutput) Type() GuestOsFeatureTypePtrOutput {\n\treturn o.ApplyT(func(v GuestOsFeature) *GuestOsFeatureType { return v.Type }).(GuestOsFeatureTypePtrOutput)\n}", "func (p *Provider) GetType() config.PlatformType {\n\treturn config.GCPPlatformType\n}", "func (f *DialectMessageField) GetFType() DialectFieldType {\n\treturn f.ftype\n}", "func (o *StoragePhysicalDiskAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (client *XenClient) VGPUGetType(self string) (result string, err error) {\n\tobj, err := client.APICall(\"VGPU.get_type\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}", "func (e Extrinsic) Type() uint8 {\n\treturn e.Version & ExtrinsicUnmaskVersion\n}", "func (o *MicrosoftGraphVerifiedDomain) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func GetRouterType() string {\n\tif RouterDefinition.Router.Infra != \"\" {\n\t\treturn RouterDefinition.Router.Infra\n\t}\n\treturn DefaultRouterType\n}", "func GetPlatformType(kclient client.Client) (*configv1.PlatformType, error) {\n\tinfra, err := GetInfrastructureObject(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &infra.Status.PlatformStatus.Type, nil\n}", "func (m *UnifiedRoleManagementPolicyNotificationRule) GetNotificationType()(*string) {\n return m.notificationType\n}", "func (e *Edge) GetType() string {\n\treturn e.Type\n}", "func (o GuestOsFeatureResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GuestOsFeatureResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (s *GDrive) Type() string {\n\treturn \"gdrive\"\n}", "func GetGestureDetected() Gestures {\n\tret := C.GetGestureDetected()\n\tv := (Gestures)(ret)\n\treturn v\n}", "func getNetStructType(kv *kernel.Version) uint64 {\n\tif kv.IsRH7Kernel() {\n\t\treturn netStructHasProcINum\n\t}\n\treturn netStructHasNS\n}", "func (m *TeamworkTag) GetTagType()(*TeamworkTagType) {\n val, err := m.GetBackingStore().Get(\"tagType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*TeamworkTagType)\n }\n return nil\n}", "func DetectType(typ api.CQLinterType, project api.Project) bool {\n\tlinter, ok := ByType[typ]\n\treturn ok && DetectLinter(linter, project)\n}", "func (m *GroupPolicyDefinition) GetClassType()(*GroupPolicyDefinitionClassType) {\n val, err := m.GetBackingStore().Get(\"classType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*GroupPolicyDefinitionClassType)\n }\n return nil\n}", "func (g *GistFile) GetType() string {\n\tif g == nil || g.Type == nil {\n\t\treturn \"\"\n\t}\n\treturn *g.Type\n}", "func WindowsType() {\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`, registry.QUERY_VALUE)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer k.Close()\n\n\ts, _, err := k.GetStringValue(\"EditionID\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif strings.Contains(s, \"Server\") {\n\t\tWindowsServerChecks()\n\t} else {\n\t\tWindowsWorkstationChecks()\n\t}\n}", "func (client *WANDSLLinkConfig1) GetModulationType() (NewModulationType string, err error) {\n\treturn client.GetModulationTypeCtx(context.Background())\n}", "func (m Message) GetCPRegType(f *field.CPRegTypeField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m Message) GetCPRegType(f *field.CPRegTypeField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (o *Handoff) GetHandoffType() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&128 != 0\n\tif ok {\n\t\tvalue = o.handoffType\n\t}\n\treturn\n}", "func (m *kubeGenericRuntimeManager) Type() string {\n\tif runtime, err := m.runtimeRegistry.GetPrimaryRuntimeService(); err == nil {\n\t\treturn m.RuntimeType(runtime.ServiceApi)\n\t}\n\treturn \"unknownType\"\n}", "func (o *ManualDependency) GetKind() string {\n\tif o == nil || o.Kind == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Kind\n}", "func (o RegistryTaskBaseImageTriggerOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskBaseImageTrigger) string { return v.Type }).(pulumi.StringOutput)\n}", "func (c FieldsCollection) Type() *models.Field {\n\treturn c.MustGet(\"Type\")\n}", "func (x SyntheticMonitorEntity) GetType() string {\n\treturn x.Type\n}", "func (o *CalendareventsIdJsonEventReminders) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {\n\tflag := f.Lookup(name)\n\tif flag == nil {\n\t\terr := fmt.Errorf(\"flag accessed but not defined: %s\", name)\n\t\treturn nil, err\n\t}\n\n\tif flag.Value.Type() != ftype {\n\t\terr := fmt.Errorf(\"trying to get %s value of flag of type %s\", ftype, flag.Value.Type())\n\t\treturn nil, err\n\t}\n\n\tsval := flag.Value.String()\n\tresult, err := convFunc(sval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (v1 v1RPMInfo) GetRPMType() string {\n\treturn v1.Type\n}", "func (m *Group) GetClassification()(*string) {\n return m.classification\n}", "func (t TypeField) getType() string {\n\treturn t.IsType\n}", "func (v2 v2RPMInfo) GetRPMType() string {\n\treturn v2.Type\n}", "func getSpecType(file *anypoint.ExchangeFile, specContent []byte) (string, error) {\n\tif file.Classifier == apic.Wsdl {\n\t\treturn apic.Wsdl, nil\n\t}\n\n\tif specContent != nil {\n\t\tjsonMap := make(map[string]interface{})\n\t\terr := json.Unmarshal(specContent, &jsonMap)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif _, isSwagger := jsonMap[\"swagger\"]; isSwagger {\n\t\t\treturn apic.Oas2, nil\n\t\t} else if _, isOpenAPI := jsonMap[\"openapi\"]; isOpenAPI {\n\t\t\treturn apic.Oas3, nil\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func (_e *MockCALIdentifyTag_Expecter) GetValueType() *MockCALIdentifyTag_GetValueType_Call {\n\treturn &MockCALIdentifyTag_GetValueType_Call{Call: _e.mock.On(\"GetValueType\")}\n}", "func PermissionClassificationTypePHigh() *PermissionClassificationType {\n\tv := PermissionClassificationTypeVHigh\n\treturn &v\n}" ]
[ "0.67219144", "0.6149949", "0.57620186", "0.5496027", "0.54775685", "0.528229", "0.52672976", "0.5143704", "0.5137406", "0.50295734", "0.50217456", "0.4986631", "0.49292427", "0.49167252", "0.49129754", "0.4896166", "0.4861257", "0.4857358", "0.48417208", "0.4831465", "0.4806809", "0.47967124", "0.47857922", "0.4784222", "0.47838208", "0.47607878", "0.47490007", "0.474438", "0.47367325", "0.4728576", "0.47263926", "0.47235033", "0.47144732", "0.47072476", "0.4697402", "0.4689755", "0.46692574", "0.46681276", "0.4664468", "0.46636698", "0.46581516", "0.463978", "0.4636636", "0.46311024", "0.4615102", "0.46055773", "0.46022403", "0.4585805", "0.4585506", "0.4579929", "0.45706737", "0.45643094", "0.45632982", "0.4559699", "0.45485654", "0.4548348", "0.45459518", "0.45459518", "0.45436406", "0.45436406", "0.45331785", "0.45257667", "0.45152932", "0.45114642", "0.4507652", "0.45066345", "0.45027062", "0.45011395", "0.449682", "0.44943666", "0.44934964", "0.44913736", "0.44857186", "0.44809684", "0.4475168", "0.44704106", "0.44657594", "0.44652998", "0.44606084", "0.44601628", "0.4455173", "0.4451396", "0.4451262", "0.4451262", "0.44435576", "0.44321895", "0.44302356", "0.44297257", "0.44282684", "0.4425457", "0.44204172", "0.44203138", "0.4418153", "0.44151622", "0.44137782", "0.44088343", "0.44061062", "0.44060606", "0.44051734", "0.4402654" ]
0.7379886
0
GetDetectionValue gets the detectionValue property value. The registry detection value
func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) { val, err := m.GetBackingStore().Get("detectionValue") if err != nil { panic(err) } if val != nil { return val.(*string) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryRule) GetComparisonValue()(*string) {\n return m.comparisonValue\n}", "func (m *Win32LobAppRegistryDetection) GetValueName()(*string) {\n val, err := m.GetBackingStore().Get(\"valueName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *DeviceComplianceScriptDeviceState) GetDetectionState()(*RunState) {\n val, err := m.GetBackingStore().Get(\"detectionState\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RunState)\n }\n return nil\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}", "func (m *FileEvidence) GetDetectionStatus()(*DetectionStatus) {\n val, err := m.GetBackingStore().Get(\"detectionStatus\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*DetectionStatus)\n }\n return nil\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigCategoricalThresholdConfigPtrOutput) Value() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreEntityTypeMonitoringConfigCategoricalThresholdConfig) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Value\n\t}).(pulumi.Float64PtrOutput)\n}", "func (o *KubernetesEthernetMatcher) GetValue() string {\n\tif o == nil || o.Value == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigCategoricalThresholdConfigOutput) Value() pulumi.Float64Output {\n\treturn o.ApplyT(func(v AiFeatureStoreEntityTypeMonitoringConfigCategoricalThresholdConfig) float64 { return v.Value }).(pulumi.Float64Output)\n}", "func (o *LabelProperties) GetValue() *string {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.Value\n\n}", "func (o *FeatureFlag) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (m *Win32LobAppRegistryRule) GetValueName()(*string) {\n return m.valueName\n}", "func (rule *GameRule) GetValue() interface{} {\n\treturn rule.value\n}", "func (p Prometheus) Value() (float64, error) {\n\tresp, err := http.Get(p.URL)\n\tif err != nil {\n\t\treturn -1.0, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn -1.0, err\n\t}\n\tfvalue, err := p.findValue(resp.Body)\n\tif err != nil {\n\t\treturn -1.0, err\n\t}\n\treturn fvalue, nil\n}", "func (o MetricValueStatusPatchOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricValueStatusPatch) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (g *Pin) GetValue()(val bool){\n\tif g.mode == OUTPUT {\n\t\treturn g.value\n\t}\n\tbuf := make([]byte,1,1)\n\tattempts := 0\n\tfor success:=false; success != true; {\n\t\tfile,err := os.OpenFile(g.path+VALUE_FILE_NAME,os.O_RDONLY,os.ModeTemporary)\n\t\tdefer file.Close()\n\t\tattempts++\n\t\tif err != nil {\n\t\t\tif attempts > FILE_ACCESS_BOUND {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tfile.Read(buf)\n\t\t\tsuccess = true\n\t\t}\n\t}\n\tfile_val,_ := strconv.Atoi(string(buf[0]))\n\n\tif g.activeLow {\n\t\tif file_val == 1 {\n\t\t\tval = true\n\t\t} else {\n\t\t\tval = false\n\t\t}\n\t} else {\n\t\tif file_val == 1 {\n\t\t\tval = false\n\t\t} else {\n\t\t\tval = true\n\t\t}\n\t}\n\n\tg.value = val\n\treturn val\n}", "func (g UGaugeSnapshot) Value() uint64 { return uint64(g) }", "func (o *EquipmentBaseSensor) GetValue() string {\n\tif o == nil || o.Value == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (s *GattDescriptor1) ReadValue(options map[string]interface{}) ([]byte, *dbus.Error) {\n\tb, err := s.config.characteristic.config.service.config.app.HandleDescriptorRead(\n\t\ts.config.characteristic.config.service.properties.UUID, s.config.characteristic.properties.UUID,\n\t\ts.properties.UUID)\n\n\tvar dberr *dbus.Error\n\tif err != nil {\n\t\tif err.code == -1 {\n\t\t\t// No registered callback, so we'll just use our stored value\n\t\t\tb = s.properties.Value\n\t\t} else {\n\t\t\tdberr = dbus.NewError(err.Error(), nil)\n\t\t}\n\t}\n\n\treturn b, dberr\n}", "func (a *Awaitility) GetMetricValue(t *testing.T, family string, labelAndValues ...string) float64 {\n\tvalue, err := metrics.GetMetricValue(a.RestConfig, a.MetricsURL, family, labelAndValues)\n\trequire.NoError(t, err)\n\treturn value\n}", "func (o FioSpecPodConfigPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (b *Beacon) Value(ctx context.Context, epochID types.EpochID) (uint32, error) {\n\t// TODO(nkryuchkov): remove when beacon sync is done\n\tbeaconSyncEnabled := false\n\tif !beaconSyncEnabled {\n\t\treturn uint32(epochID), nil\n\t}\n\n\t// check cache\n\tif val, ok := b.cache.Get(epochID); ok {\n\t\treturn val.(uint32), nil\n\t}\n\n\t// TODO: do we need a lock here?\n\tv, err := b.beaconGetter.GetBeacon(epochID)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvalue := binary.LittleEndian.Uint32(v)\n\tb.WithContext(ctx).With().Debug(\"hare eligibility beacon value for epoch\",\n\t\tepochID,\n\t\tlog.String(\"beacon_hex\", util.Bytes2Hex(v)),\n\t\tlog.Uint32(\"beacon_dec\", value))\n\n\t// update and return\n\tb.cache.Add(epochID, value)\n\treturn value, nil\n}", "func (s *Uint8Setting) Value() interface{} {\n\treturn *s.Uint8Value\n}", "func (o IopingSpecPodConfigPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (b *MetricsBPFMap) GetValue() float64 {\n\tebpfMap, err := ebpf.NewMapFromID(b.MapID)\n\tif err != nil {\n\t\t// We have observed in smaller configuration VM's, if we restart KF's\n\t\t// Stale mapID's are reported, in such cases re-checking map id\n\t\tlog.Warn().Err(err).Msgf(\"GetValue : NewMapFromID failed ID %d, re-looking up of map id\", b.MapID)\n\t\ttmpBPF, err := b.BPFProg.GetBPFMap(b.Name)\n\t\tif err != nil {\n\t\t\tlog.Warn().Err(err).Msgf(\"GetValue: Update new map ID %d\", tmpBPF.MapID)\n\t\t\treturn 0\n\t\t}\n\t\tlog.Info().Msgf(\"GetValue: Update new map ID %d\", tmpBPF.MapID)\n\t\tb.MapID = tmpBPF.MapID\n\t\tebpfMap, err = ebpf.NewMapFromID(b.MapID)\n\t\tif err != nil {\n\t\t\tlog.Warn().Err(err).Msgf(\"GetValue : retry of NewMapFromID failed ID %d\", b.MapID)\n\t\t\treturn 0\n\t\t}\n\t}\n\tdefer ebpfMap.Close()\n\n\tvar value int64\n\tif err = ebpfMap.Lookup(unsafe.Pointer(&b.key), unsafe.Pointer(&value)); err != nil {\n\t\tlog.Warn().Err(err).Msgf(\"GetValue Lookup failed : Name %s ID %d\", b.Name, b.MapID)\n\t\treturn 0\n\t}\n\n\tvar retVal float64\n\tswitch b.aggregator {\n\tcase \"scalar\":\n\t\tretVal = float64(value)\n\tcase \"max-rate\":\n\t\tb.Values = b.Values.Next()\n\t\tb.Values.Value = math.Abs(float64(float64(value) - b.lastValue))\n\t\tb.lastValue = float64(value)\n\t\tretVal = b.MaxValue()\n\tcase \"avg\":\n\t\tb.Values.Value = value\n\t\tb.Values = b.Values.Next()\n\t\tretVal = b.AvgValue()\n\tdefault:\n\t\tlog.Warn().Msgf(\"unsupported aggregator %s and value %d\", b.aggregator, value)\n\t}\n\n\treturn retVal\n}", "func MrbProcValue(p RProc) Value { return p.Value() }", "func (o MetadataFilterLabelMatchOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetadataFilterLabelMatch) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (*InstFPExt) isValue() {}", "func (vm *VM) Value(ref Ref) *Value {\n\tv, ok := vm.loadValue(ref)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn v\n}", "func (s *Float64Setting) Value() interface{} {\n\treturn *s.Float64Value\n}", "func (o PgbenchSpecPodConfigPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (e REnv) Value() Value { return mrbObjValue(unsafe.Pointer(e.p)) }", "func (o offlineFallback) GetValue() interface{} {\n\treturn bool(o)\n}", "func (self *attain_obj_t) GetVal() float64 {\n\treturn self.Val\n}", "func (g *GaugeFloat64) Value() float64 {\n\treturn math.Float64frombits(atomic.LoadUint64(&g.val))\n}", "func (o *CreateRiskRulesData) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func Get(gnum int) value.Value {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\treturn values[gnum]\n}", "func (o *ResourceDefinitionFilter) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (s *Uint64Setting) Value() interface{} {\n\treturn *s.Uint64Value\n}", "func (o MetricValueStatusPatchPtrOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MetricValueStatusPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Value\n\t}).(pulumi.StringPtrOutput)\n}", "func (flag *flag) GetValue() string {\n\treturn flag.FlagValue.String()\n}", "func (o loadFromOnline) GetValue() interface{} {\n\treturn bool(o)\n}", "func (o DrillSpecPodConfigPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func GetValue(tv *gpb.TypedValue) (interface{}, error) {\n\tvar (\n\t\tjsondata []byte\n\t\tvalue interface{}\n\t\terr error\n\t)\n\n\tswitch tv.Value.(type) {\n\tcase *gpb.TypedValue_AsciiVal:\n\t\tvalue = tv.GetAsciiVal()\n\tcase *gpb.TypedValue_BoolVal:\n\t\tvalue = tv.GetBoolVal()\n\tcase *gpb.TypedValue_BytesVal:\n\t\tvalue = tv.GetBytesVal()\n\tcase *gpb.TypedValue_DecimalVal:\n\t\tvalue = float64(tv.GetDecimalVal().Digits) / math.Pow(10, float64(tv.GetDecimalVal().Precision))\n\tcase *gpb.TypedValue_FloatVal:\n\t\tvalue = tv.GetFloatVal()\n\tcase *gpb.TypedValue_IntVal:\n\t\tvalue = tv.GetIntVal()\n\tcase *gpb.TypedValue_StringVal:\n\t\tvalue = tv.GetStringVal()\n\tcase *gpb.TypedValue_UintVal:\n\t\tvalue = tv.GetUintVal()\n\tcase *gpb.TypedValue_JsonIetfVal:\n\t\tjsondata = tv.GetJsonIetfVal()\n\tcase *gpb.TypedValue_JsonVal:\n\t\tjsondata = tv.GetJsonVal()\n\tcase *gpb.TypedValue_LeaflistVal:\n\t\telems := tv.GetLeaflistVal().GetElement()\n\t\tvalue, err = getLeafList(elems)\n\tdefault:\n\t\terr = fmt.Errorf(\"unknown value type %+v\", tv.Value)\n\t}\n\n\tif jsondata != nil {\n\t\terr = json.Unmarshal(jsondata, &value)\n\t}\n\n\treturn value, err\n}", "func (l *ActivityDumpRuntimeSetting) Get() (interface{}, error) {\n\tval := config.SystemProbe.Get(l.ConfigKey)\n\treturn val, nil\n}", "func Get_Value(value *vector_tile.Tile_Value) interface{} {\n\tif value.StringValue != nil {\n\t\treturn *value.StringValue\n\t} else if value.FloatValue != nil {\n\t\treturn *value.FloatValue\n\t} else if value.DoubleValue != nil {\n\t\treturn *value.DoubleValue\n\t} else if value.IntValue != nil {\n\t\treturn *value.IntValue\n\t} else if value.UintValue != nil {\n\t\treturn *value.UintValue\n\t} else if value.SintValue != nil {\n\t\treturn *value.SintValue\n\t} else if value.BoolValue != nil {\n\t\treturn *value.BoolValue\n\t} else {\n\t\treturn \"\"\n\t}\n\treturn \"\"\n}", "func (s *sensorReading) GetValue() float32 {\n\treturn s.value\n}", "func (s *Float32Setting) Value() interface{} {\n\treturn *s.Float32Value\n}", "func (t *Target) GetValue(name string) string {\n\treturn t.labels.Get(name)\n}", "func GetDockerImageValue(stepName string) (string, error) {\n\tconfigOptions.contextConfig = true\n\tconfigOptions.stepName = stepName\n\tstepConfig, err := getConfig()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar dockerImageValue string\n\tdockerImageValue, ok := stepConfig.Config[\"dockerImage\"].(string)\n\tif !ok {\n\t\tlog.Entry().Infof(\"Config value of %v to compare with is not a string\", stepConfig.Config[\"dockerImage\"])\n\t}\n\n\treturn dockerImageValue, nil\n}", "func propValue(v *pb.PropertyValue, m pb.Property_Meaning) (interface{}, error) {\n\tswitch {\n\tcase v.Int64Value != nil:\n\t\tif m == pb.Property_GD_WHEN {\n\t\t\treturn fromUnixMicro(*v.Int64Value), nil\n\t\t} else {\n\t\t\treturn *v.Int64Value, nil\n\t\t}\n\tcase v.BooleanValue != nil:\n\t\treturn *v.BooleanValue, nil\n\tcase v.StringValue != nil:\n\t\tif m == pb.Property_BLOB {\n\t\t\treturn []byte(*v.StringValue), nil\n\t\t} else if m == pb.Property_BLOBKEY {\n\t\t\treturn appengine.BlobKey(*v.StringValue), nil\n\t\t} else if m == pb.Property_BYTESTRING {\n\t\t\treturn ByteString(*v.StringValue), nil\n\t\t} else if m == pb.Property_ENTITY_PROTO {\n\t\t\tvar ent pb.EntityProto\n\t\t\terr := proto.Unmarshal([]byte(*v.StringValue), &ent)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn protoToEntity(&ent)\n\t\t} else {\n\t\t\treturn *v.StringValue, nil\n\t\t}\n\tcase v.DoubleValue != nil:\n\t\treturn *v.DoubleValue, nil\n\tcase v.Referencevalue != nil:\n\t\tkey, err := referenceValueToKey(v.Referencevalue)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn key, nil\n\tcase v.Pointvalue != nil:\n\t\t// NOTE: Strangely, latitude maps to X, longitude to Y.\n\t\treturn appengine.GeoPoint{Lat: v.Pointvalue.GetX(), Lng: v.Pointvalue.GetY()}, nil\n\t}\n\treturn nil, nil\n}", "func (l *NodeLoad) GetValue(resource, device string) (float64, error) {\n\tvalueMap := structs.Map(l)\n\tvalue, ok := valueMap[resource]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"%s not found, supporting: %v\", resource, l.GetTags())\n\t}\n\n\treturn value.(float64), nil\n}", "func (mii ModifiedIntegrityImpact) Value(ii IntegrityImpact) float64 {\n\tif mii.String() == ModifiedAttackComplexityNotDefined.String() {\n\t\tif v, ok := integrityImpactValueMap[ii]; ok {\n\t\t\treturn v\n\t\t}\n\t\treturn 0.0\n\t} else {\n\t\tif v, ok := ModifiedIntegrityImpactValueMap[mii]; ok {\n\t\t\treturn v\n\t\t}\n\t\treturn 0.0\n\t}\n}", "func (coll FeatureCollection) Value() (driver.Value, error) {\n\treturn coll.String(), nil\n}", "func (*InstUIToFP) isValue() {}", "func (o Iperf3SpecServerConfigurationPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (s *Int8Setting) Value() interface{} {\n\treturn *s.Int8Value\n}", "func (reference *Reference) GetValue() interface{} {\n\treturn reference.resolve().GetValue()\n}", "func (f *Factor) Value() string { return f.driver().name() }", "func (g *GaugeUint64) Value() uint64 {\n\treturn atomic.LoadUint64(&g.val)\n}", "func (s *Uint32Setting) Value() interface{} {\n\treturn *s.Uint32Value\n}", "func (p *NodeProcess) GetValue(resource, device string) (float64, error) {\n\tvalueMap := structs.Map(p)\n\tvalue, ok := valueMap[resource]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"%s not found, supporting: %v\", resource, p.GetTags())\n\t}\n\n\treturn value.(float64), nil\n}", "func (o StorageClusterSpecPlacementTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecPlacementTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (p *PhidgetCurrentInput) GetValue() (float64, error) {\n\tvar r C.double\n\tcerr := C.PhidgetCurrentInput_getCurrent(p.handle, &r)\n\tif cerr != C.EPHIDGET_OK {\n\t\treturn 0, p.phidgetError(cerr)\n\t}\n\treturn float64(r), nil\n}", "func (o QperfSpecServerConfigurationPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (o *RiskRulesListAllOfData) GetValue() string {\n\tif o == nil || IsNil(o.Value) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (b *BrightnessFuncSlice) GetFuncValue(stepNum int) (uint8, bool) {\n\tfuncVal, f := b.transFuncSlice.GetFuncValue(stepNum)\n\t// make sure there are functions defined\n\tok := true\n\tif f == nil {\n\t\tok = false\n\t}\n\treturn uint8(0xff * funcVal), ok\n}", "func (is *IfaceStat) GetValue(resource, device string) (float64, error) {\n\tvalueMap := structs.Map(is)\n\tvalue, ok := valueMap[resource]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"%s not found, supporting: %v\", resource, is.GetTags())\n\t}\n\n\treturn value.(float64), nil\n}", "func (o *VerifiableAddress) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (p *Param) GetValue() (float64, error) {\n\tvar ferr C.FMOD_RESULT\n\tvar value C.float\n\tbase.Thread(func() {\n\t\tferr = C.FMOD_EventParameter_GetValue(p.param, &value)\n\t})\n\treturn float64(value), base.ResultToError(ferr)\n}", "func (us *urlStatus) Value(key string) bool {\n\tus.mu.Lock()\n\t// Lock so only one goroutine at a time can access the map c.v.\n\tdefer us.mu.Unlock()\n\treturn us.v[key]\n}", "func (cfg *Config) Value(name string) string {\n\tv, _ := cfg.findLast(name)\n\treturn string(v)\n}", "func (p *Property) Value() int {\n\treturn p.value\n}", "func (o SysbenchSpecPodSchedulingTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func GetGaugeValue(metrics []byte, mtrName string) (float64, error) {\n\tvar parser expfmt.TextParser\n\tin := bytes.NewReader(metrics)\n\tmetricFamilies, err := parser.TextToMetricFamilies(in)\n\tif err != nil {\n\t\tlog.WithError(err).Errorln(\"error, reading text format failed\")\n\t\treturn -1, config.ErrKeyDecodingFile\n\t}\n\tfor _, mf := range metricFamilies {\n\t\tif mtrName == *mf.Name {\n\t\t\tif (*mf.Type).String() != strings.ToUpper(config.KeyMetricTypeGauge) {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"current_type\": (*mf.Type).String(),\n\t\t\t\t\t\"looking_for\": strings.ToUpper(config.KeyMetricTypeHistogram),\n\t\t\t\t}).Errorln(\"metric is not one of the spected type\")\n\t\t\t\treturn -1, config.ErrKeyInvalidType\n\t\t\t}\n\t\t\treturn *mf.Metric[0].Gauge.Value, nil\n\t\t}\n\t}\n\tlog.WithField(\"wanted_name\", mtrName).Errorln(\"metric name not found\")\n\treturn -1, config.ErrKeyNotFound\n}", "func (o BucketReplicationConfigRuleFilterTagPtrOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleFilterTag) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Value\n\t}).(pulumi.StringPtrOutput)\n}", "func (e *JVBMetricsCollector) getMetricValue(stats *JVBStatistics, fieldName string) float64 {\n\tr := reflect.ValueOf(stats)\n\tfieldVal := reflect.Indirect(r).FieldByName(fieldName)\n\tpromValue := 7.21\n\n\tfieldKind := fieldVal.Kind()\n\tswitch fieldKind {\n\tcase reflect.Int:\n\t\tpromValue = float64(fieldVal.Int())\n\tcase reflect.Float64:\n\t\tpromValue = float64(fieldVal.Float())\n\t}\n\n\treturn promValue\n}", "func (blk *Block) getVrfValue() []byte {\n\treturn blk.Info.VrfValue\n}", "func (stringEntry *String) GetValue() interface{} {\n\treturn stringEntry.trueValue\n}", "func (config *Config) GetValue(label string) string {\n\tvar value, _ = config.GetString(label)\n\treturn config.replaceHome(value)\n}", "func (self *FieldValue) GetValue() (interface{}, bool) {\n\tif self.StringValue != nil {\n\t\treturn *self.StringValue, true\n\t}\n\n\tif self.DoubleValue != nil {\n\t\tfv := *self.DoubleValue\n\t\tif math.IsNaN(fv) || math.IsInf(fv, 0) {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn fv, true\n\t}\n\n\tif self.Int64Value != nil {\n\t\treturn *self.Int64Value, true\n\t}\n\n\tif self.BoolValue != nil {\n\t\treturn *self.BoolValue, true\n\t}\n\n\t// TODO: should we do something here ?\n\treturn nil, true\n}", "func (b *Beacon) Value(layer types.LayerID) (uint32, error) {\n\tsl := safeLayer(layer, types.LayerID(b.confidenceParam))\n\n\t// check cache\n\tif val, exist := b.cache.Get(sl); exist {\n\t\treturn val.(uint32), nil\n\t}\n\n\t// note: multiple concurrent calls to ContextuallyValidBlock and calcValue can be made\n\t// consider adding a lock if concurrency-optimized is important\n\tv, err := b.patternProvider.ContextuallyValidBlock(sl)\n\tif err != nil {\n\t\tb.Log.With().Error(\"Could not get pattern ID\",\n\t\t\tlog.Err(err), layer, log.FieldNamed(\"sl_id\", sl))\n\t\treturn nilVal, errors.New(\"could not calc Beacon value\")\n\t}\n\n\t// notify if there are no contextually valid blocks\n\tif len(v) == 0 {\n\t\tb.Log.With().Warning(\"hare Beacon: zero contextually valid blocks (ignore if genesis first layers)\",\n\t\t\tlayer, log.FieldNamed(\"sl_id\", sl))\n\t}\n\n\t// calculate\n\tvalue := calcValue(v)\n\n\t// update\n\tb.cache.Add(sl, value)\n\n\treturn value, nil\n}", "func (p RProc) Value() Value { return mrbObjValue(unsafe.Pointer(p.p)) }", "func (c *ConfHolder) Value() interface{} {\n\treturn c.GameParameters\n}", "func (s *Smpval) Value() reflect.Value {\n\treturn s.val\n}", "func (v VEML6070) ReadValue(phenomenon string) (float64, error) {\n\tif phenomenon != \"uv\" {\n\t\treturn 0, fmt.Errorf(\"invalid phenomenon %s\", phenomenon)\n\t}\n\n\tuv, err := v.UV()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uv, nil\n}", "func (f *ExtensionField) Value() protoreflect.Value {\n\tif f.lazy != nil {\n\t\tif atomic.LoadUint32(&f.lazy.atomicOnce) == 0 {\n\t\t\tf.lazyInit()\n\t\t}\n\t\treturn f.lazy.value\n\t}\n\treturn f.value\n}", "func (o *AllocationVersion) GetValue() string {\n\tif o == nil || IsNil(o.Value) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (*InstSExt) isValue() {}", "func (o MetricTargetPatchOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricTargetPatch) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (f *Value) Get() interface{} {\n\t<-f.ready\n\treturn f.value\n}", "func (o MetricValueStatusOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricValueStatus) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (this FontFaceLoadStatus) Value() string {\n\tidx := int(this)\n\tif idx >= 0 && idx < len(fontFaceLoadStatusToWasmTable) {\n\t\treturn fontFaceLoadStatusToWasmTable[idx]\n\t}\n\tpanic(\"unknown input value\")\n}", "func (m *RegistryKeyState) GetValueData()(*string) {\n return m.valueData\n}", "func (v *tagValuer) Value(name string) (interface{}, bool) {\n\tif value, ok := v.tags[name]; ok {\n\t\tif value == nil {\n\t\t\treturn nil, true\n\t\t}\n\t\treturn *value, true\n\t}\n\treturn nil, false\n}", "func (b *BinarySearchNode) Value() int {\n\treturn b.value\n}" ]
[ "0.7641047", "0.67213154", "0.60203254", "0.5969953", "0.5907721", "0.5894237", "0.5693755", "0.5686337", "0.55916923", "0.5588278", "0.5571196", "0.5500819", "0.549452", "0.54863846", "0.5450651", "0.54302305", "0.53898174", "0.5385101", "0.5342542", "0.5263009", "0.525747", "0.5250626", "0.52477694", "0.5244975", "0.5239936", "0.5221072", "0.52098763", "0.52077585", "0.52005535", "0.5194524", "0.5188619", "0.51865137", "0.51840454", "0.51839304", "0.51825035", "0.51819706", "0.51726925", "0.5162429", "0.51567763", "0.515606", "0.51533115", "0.5147402", "0.51433283", "0.5133059", "0.5130527", "0.5124237", "0.5121494", "0.5120392", "0.5107161", "0.51065516", "0.51048726", "0.5104041", "0.50873107", "0.50832033", "0.5072216", "0.5070017", "0.5067526", "0.50647575", "0.50614995", "0.5046013", "0.50409865", "0.5039239", "0.5032903", "0.5031779", "0.50314564", "0.5023084", "0.5015716", "0.50116605", "0.5004905", "0.4999598", "0.4999033", "0.49959385", "0.49934402", "0.4974528", "0.49741393", "0.49727562", "0.49668652", "0.49622107", "0.49606976", "0.49585688", "0.49571738", "0.49556658", "0.49528068", "0.49496394", "0.4949104", "0.49477547", "0.49388945", "0.4936949", "0.49365428", "0.49359143", "0.49336657", "0.49326223", "0.49312934", "0.4925211", "0.4913836", "0.49112302", "0.4910653", "0.4908558", "0.490848", "0.49051714" ]
0.825966
0
GetFieldDeserializers the deserialization information for the current model
func (m *Win32LobAppRegistryDetection) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Win32LobAppDetection.GetFieldDeserializers() res["check32BitOn64System"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetCheck32BitOn64System(val) } return nil } res["detectionType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseWin32LobAppRegistryDetectionType) if err != nil { return err } if val != nil { m.SetDetectionType(val.(*Win32LobAppRegistryDetectionType)) } return nil } res["detectionValue"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDetectionValue(val) } return nil } res["keyPath"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetKeyPath(val) } return nil } res["operator"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseWin32LobAppDetectionOperator) if err != nil { return err } if val != nil { m.SetOperator(val.(*Win32LobAppDetectionOperator)) } return nil } res["valueName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetValueName(val) } return nil } return res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *AuthenticationMethod) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *IdentityProviderBase) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n return res\n}", "func (m *Artifact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *IdentityCustomUserFlowAttribute) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IdentityUserFlowAttribute.GetFieldDeserializers()\n return res\n}", "func (m *Store) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"defaultLanguageTag\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDefaultLanguageTag)\n res[\"groups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupFromDiscriminatorValue , m.SetGroups)\n res[\"languageTags\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetLanguageTags)\n res[\"sets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSetFromDiscriminatorValue , m.SetSets)\n return res\n}", "func (m *List) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseItem.GetFieldDeserializers()\n res[\"columns\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateColumnDefinitionFromDiscriminatorValue , m.SetColumns)\n res[\"contentTypes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContentTypeFromDiscriminatorValue , m.SetContentTypes)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"drive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive)\n res[\"items\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateListItemFromDiscriminatorValue , m.SetItems)\n res[\"list\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateListInfoFromDiscriminatorValue , m.SetList)\n res[\"operations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRichLongRunningOperationFromDiscriminatorValue , m.SetOperations)\n res[\"sharepointIds\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSharepointIdsFromDiscriminatorValue , m.SetSharepointIds)\n res[\"subscriptions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSubscriptionFromDiscriminatorValue , m.SetSubscriptions)\n res[\"system\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSystemFacetFromDiscriminatorValue , m.SetSystem)\n return res\n}", "func (m *NamedLocation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n return res\n}", "func (m *Schema) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"baseType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetBaseType)\n res[\"properties\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePropertyFromDiscriminatorValue , m.SetProperties)\n return res\n}", "func (m *RemoteAssistancePartner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"lastConnectionDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastConnectionDateTime)\n res[\"onboardingStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseRemoteAssistanceOnboardingStatus , m.SetOnboardingStatus)\n res[\"onboardingUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnboardingUrl)\n return res\n}", "func (m *RoleDefinition) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isBuiltIn\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsBuiltIn)\n res[\"roleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRoleAssignmentFromDiscriminatorValue , m.SetRoleAssignments)\n res[\"rolePermissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRolePermissionFromDiscriminatorValue , m.SetRolePermissions)\n return res\n}", "func (m *VppToken) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"appleId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAppleId)\n res[\"automaticallyUpdateApps\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAutomaticallyUpdateApps)\n res[\"countryOrRegion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCountryOrRegion)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"lastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastSyncDateTime)\n res[\"lastSyncStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenSyncStatus , m.SetLastSyncStatus)\n res[\"organizationName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOrganizationName)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenState , m.SetState)\n res[\"token\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetToken)\n res[\"vppTokenAccountType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseVppTokenAccountType , m.SetVppTokenAccountType)\n return res\n}", "func (m *AuditLogRoot) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"directoryAudits\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryAuditFromDiscriminatorValue , m.SetDirectoryAudits)\n res[\"provisioning\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProvisioningObjectSummaryFromDiscriminatorValue , m.SetProvisioning)\n res[\"signIns\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSignInFromDiscriminatorValue , m.SetSignIns)\n return res\n}", "func (m *ItemFacet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"allowedAudiences\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAllowedAudiences)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAllowedAudiences(val.(*AllowedAudiences))\n }\n return nil\n }\n res[\"createdBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentitySetFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedBy(val.(IdentitySetable))\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"inference\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateInferenceDataFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetInference(val.(InferenceDataable))\n }\n return nil\n }\n res[\"isSearchable\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsSearchable(val)\n }\n return nil\n }\n res[\"lastModifiedBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentitySetFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedBy(val.(IdentitySetable))\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"source\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePersonDataSourcesFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSource(val.(PersonDataSourcesable))\n }\n return nil\n }\n return res\n}", "func (m *User) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"aboutMe\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAboutMe)\n res[\"accountEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAccountEnabled)\n res[\"activities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateUserActivityFromDiscriminatorValue , m.SetActivities)\n res[\"ageGroup\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgeGroup)\n res[\"agreementAcceptances\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAgreementAcceptanceFromDiscriminatorValue , m.SetAgreementAcceptances)\n res[\"appRoleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleAssignmentFromDiscriminatorValue , m.SetAppRoleAssignments)\n res[\"assignedLicenses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLicenseFromDiscriminatorValue , m.SetAssignedLicenses)\n res[\"assignedPlans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedPlanFromDiscriminatorValue , m.SetAssignedPlans)\n res[\"authentication\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuthenticationFromDiscriminatorValue , m.SetAuthentication)\n res[\"authorizationInfo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuthorizationInfoFromDiscriminatorValue , m.SetAuthorizationInfo)\n res[\"birthday\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetBirthday)\n res[\"businessPhones\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetBusinessPhones)\n res[\"calendar\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCalendarFromDiscriminatorValue , m.SetCalendar)\n res[\"calendarGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateCalendarGroupFromDiscriminatorValue , m.SetCalendarGroups)\n res[\"calendars\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateCalendarFromDiscriminatorValue , m.SetCalendars)\n res[\"calendarView\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetCalendarView)\n res[\"chats\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatFromDiscriminatorValue , m.SetChats)\n res[\"city\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCity)\n res[\"companyName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCompanyName)\n res[\"consentProvidedForMinor\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConsentProvidedForMinor)\n res[\"contactFolders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContactFolderFromDiscriminatorValue , m.SetContactFolders)\n res[\"contacts\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateContactFromDiscriminatorValue , m.SetContacts)\n res[\"country\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCountry)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdObjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedObjects)\n res[\"creationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCreationType)\n res[\"department\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDepartment)\n res[\"deviceEnrollmentLimit\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDeviceEnrollmentLimit)\n res[\"deviceManagementTroubleshootingEvents\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDeviceManagementTroubleshootingEventFromDiscriminatorValue , m.SetDeviceManagementTroubleshootingEvents)\n res[\"directReports\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetDirectReports)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"drive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive)\n res[\"drives\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveFromDiscriminatorValue , m.SetDrives)\n res[\"employeeHireDate\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetEmployeeHireDate)\n res[\"employeeId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmployeeId)\n res[\"employeeOrgData\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEmployeeOrgDataFromDiscriminatorValue , m.SetEmployeeOrgData)\n res[\"employeeType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmployeeType)\n res[\"events\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetEvents)\n res[\"extensions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionFromDiscriminatorValue , m.SetExtensions)\n res[\"externalUserState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetExternalUserState)\n res[\"externalUserStateChangeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExternalUserStateChangeDateTime)\n res[\"faxNumber\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFaxNumber)\n res[\"followedSites\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSiteFromDiscriminatorValue , m.SetFollowedSites)\n res[\"givenName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetGivenName)\n res[\"hireDate\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetHireDate)\n res[\"identities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateObjectIdentityFromDiscriminatorValue , m.SetIdentities)\n res[\"imAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetImAddresses)\n res[\"inferenceClassification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateInferenceClassificationFromDiscriminatorValue , m.SetInferenceClassification)\n res[\"insights\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOfficeGraphInsightsFromDiscriminatorValue , m.SetInsights)\n res[\"interests\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetInterests)\n res[\"isResourceAccount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsResourceAccount)\n res[\"jobTitle\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetJobTitle)\n res[\"joinedTeams\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTeamFromDiscriminatorValue , m.SetJoinedTeams)\n res[\"lastPasswordChangeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastPasswordChangeDateTime)\n res[\"legalAgeGroupClassification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLegalAgeGroupClassification)\n res[\"licenseAssignmentStates\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateLicenseAssignmentStateFromDiscriminatorValue , m.SetLicenseAssignmentStates)\n res[\"licenseDetails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateLicenseDetailsFromDiscriminatorValue , m.SetLicenseDetails)\n res[\"mail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMail)\n res[\"mailboxSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMailboxSettingsFromDiscriminatorValue , m.SetMailboxSettings)\n res[\"mailFolders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMailFolderFromDiscriminatorValue , m.SetMailFolders)\n res[\"mailNickname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMailNickname)\n res[\"managedAppRegistrations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateManagedAppRegistrationFromDiscriminatorValue , m.SetManagedAppRegistrations)\n res[\"managedDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateManagedDeviceFromDiscriminatorValue , m.SetManagedDevices)\n res[\"manager\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetManager)\n res[\"memberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMemberOf)\n res[\"messages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMessageFromDiscriminatorValue , m.SetMessages)\n res[\"mobilePhone\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMobilePhone)\n res[\"mySite\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMySite)\n res[\"oauth2PermissionGrants\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOAuth2PermissionGrantFromDiscriminatorValue , m.SetOauth2PermissionGrants)\n res[\"officeLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOfficeLocation)\n res[\"onenote\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnenoteFromDiscriminatorValue , m.SetOnenote)\n res[\"onlineMeetings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnlineMeetingFromDiscriminatorValue , m.SetOnlineMeetings)\n res[\"onPremisesDistinguishedName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDistinguishedName)\n res[\"onPremisesDomainName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDomainName)\n res[\"onPremisesExtensionAttributes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnPremisesExtensionAttributesFromDiscriminatorValue , m.SetOnPremisesExtensionAttributes)\n res[\"onPremisesImmutableId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesImmutableId)\n res[\"onPremisesLastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetOnPremisesLastSyncDateTime)\n res[\"onPremisesProvisioningErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnPremisesProvisioningErrorFromDiscriminatorValue , m.SetOnPremisesProvisioningErrors)\n res[\"onPremisesSamAccountName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSamAccountName)\n res[\"onPremisesSecurityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSecurityIdentifier)\n res[\"onPremisesSyncEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOnPremisesSyncEnabled)\n res[\"onPremisesUserPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesUserPrincipalName)\n res[\"otherMails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetOtherMails)\n res[\"outlook\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOutlookUserFromDiscriminatorValue , m.SetOutlook)\n res[\"ownedDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwnedDevices)\n res[\"ownedObjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwnedObjects)\n res[\"passwordPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPasswordPolicies)\n res[\"passwordProfile\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePasswordProfileFromDiscriminatorValue , m.SetPasswordProfile)\n res[\"pastProjects\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetPastProjects)\n res[\"people\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePersonFromDiscriminatorValue , m.SetPeople)\n res[\"photo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateProfilePhotoFromDiscriminatorValue , m.SetPhoto)\n res[\"photos\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProfilePhotoFromDiscriminatorValue , m.SetPhotos)\n res[\"planner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePlannerUserFromDiscriminatorValue , m.SetPlanner)\n res[\"postalCode\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPostalCode)\n res[\"preferredDataLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredDataLocation)\n res[\"preferredLanguage\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredLanguage)\n res[\"preferredName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredName)\n res[\"presence\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePresenceFromDiscriminatorValue , m.SetPresence)\n res[\"provisionedPlans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProvisionedPlanFromDiscriminatorValue , m.SetProvisionedPlans)\n res[\"proxyAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetProxyAddresses)\n res[\"registeredDevices\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetRegisteredDevices)\n res[\"responsibilities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetResponsibilities)\n res[\"schools\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetSchools)\n res[\"scopedRoleMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateScopedRoleMembershipFromDiscriminatorValue , m.SetScopedRoleMemberOf)\n res[\"securityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSecurityIdentifier)\n res[\"settings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserSettingsFromDiscriminatorValue , m.SetSettings)\n res[\"showInAddressList\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetShowInAddressList)\n res[\"signInSessionsValidFromDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetSignInSessionsValidFromDateTime)\n res[\"skills\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetSkills)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetState)\n res[\"streetAddress\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetStreetAddress)\n res[\"surname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSurname)\n res[\"teamwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserTeamworkFromDiscriminatorValue , m.SetTeamwork)\n res[\"todo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateTodoFromDiscriminatorValue , m.SetTodo)\n res[\"transitiveMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMemberOf)\n res[\"usageLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUsageLocation)\n res[\"userPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserPrincipalName)\n res[\"userType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserType)\n return res\n}", "func (m *Application) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"addIns\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAddInFromDiscriminatorValue , m.SetAddIns)\n res[\"api\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateApiApplicationFromDiscriminatorValue , m.SetApi)\n res[\"appId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAppId)\n res[\"applicationTemplateId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetApplicationTemplateId)\n res[\"appRoles\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleFromDiscriminatorValue , m.SetAppRoles)\n res[\"certification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCertificationFromDiscriminatorValue , m.SetCertification)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdOnBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedOnBehalfOf)\n res[\"defaultRedirectUri\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDefaultRedirectUri)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"disabledByMicrosoftStatus\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisabledByMicrosoftStatus)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"extensionProperties\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionPropertyFromDiscriminatorValue , m.SetExtensionProperties)\n res[\"federatedIdentityCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateFederatedIdentityCredentialFromDiscriminatorValue , m.SetFederatedIdentityCredentials)\n res[\"groupMembershipClaims\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetGroupMembershipClaims)\n res[\"homeRealmDiscoveryPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateHomeRealmDiscoveryPolicyFromDiscriminatorValue , m.SetHomeRealmDiscoveryPolicies)\n res[\"identifierUris\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetIdentifierUris)\n res[\"info\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateInformationalUrlFromDiscriminatorValue , m.SetInfo)\n res[\"isDeviceOnlyAuthSupported\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsDeviceOnlyAuthSupported)\n res[\"isFallbackPublicClient\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsFallbackPublicClient)\n res[\"keyCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateKeyCredentialFromDiscriminatorValue , m.SetKeyCredentials)\n res[\"logo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetByteArrayValue(m.SetLogo)\n res[\"notes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetNotes)\n res[\"oauth2RequirePostResponse\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOauth2RequirePostResponse)\n res[\"optionalClaims\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOptionalClaimsFromDiscriminatorValue , m.SetOptionalClaims)\n res[\"owners\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwners)\n res[\"parentalControlSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateParentalControlSettingsFromDiscriminatorValue , m.SetParentalControlSettings)\n res[\"passwordCredentials\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePasswordCredentialFromDiscriminatorValue , m.SetPasswordCredentials)\n res[\"publicClient\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePublicClientApplicationFromDiscriminatorValue , m.SetPublicClient)\n res[\"publisherDomain\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPublisherDomain)\n res[\"requiredResourceAccess\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateRequiredResourceAccessFromDiscriminatorValue , m.SetRequiredResourceAccess)\n res[\"samlMetadataUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSamlMetadataUrl)\n res[\"serviceManagementReference\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetServiceManagementReference)\n res[\"signInAudience\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSignInAudience)\n res[\"spa\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSpaApplicationFromDiscriminatorValue , m.SetSpa)\n res[\"tags\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetTags)\n res[\"tokenEncryptionKeyId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTokenEncryptionKeyId)\n res[\"tokenIssuancePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTokenIssuancePolicyFromDiscriminatorValue , m.SetTokenIssuancePolicies)\n res[\"tokenLifetimePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTokenLifetimePolicyFromDiscriminatorValue , m.SetTokenLifetimePolicies)\n res[\"verifiedPublisher\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateVerifiedPublisherFromDiscriminatorValue , m.SetVerifiedPublisher)\n res[\"web\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWebApplicationFromDiscriminatorValue , m.SetWeb)\n return res\n}", "func (m *Reports) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n return res\n}", "func (m *AttributeSet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"maxAttributesPerSet\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMaxAttributesPerSet(val)\n }\n return nil\n }\n return res\n}", "func (m *IosExpeditedCheckinConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AppleExpeditedCheckinConfigurationBase.GetFieldDeserializers()\n return res\n}", "func (m *LabelActionBase) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"name\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetName(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *Planner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"buckets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerBucketFromDiscriminatorValue , m.SetBuckets)\n res[\"plans\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerPlanFromDiscriminatorValue , m.SetPlans)\n res[\"tasks\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreatePlannerTaskFromDiscriminatorValue , m.SetTasks)\n return res\n}", "func (m *SocialIdentityProvider) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IdentityProviderBase.GetFieldDeserializers()\n res[\"clientId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClientId)\n res[\"clientSecret\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClientSecret)\n res[\"identityProviderType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetIdentityProviderType)\n return res\n}", "func (m *FileDataConnector) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.IndustryDataConnector.GetFieldDeserializers()\n return res\n}", "func (m *SubCategoryTemplate) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.FilePlanDescriptorTemplate.GetFieldDeserializers()\n return res\n}", "func (m *ChatMessage) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"attachments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageAttachmentFromDiscriminatorValue , m.SetAttachments)\n res[\"body\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateItemBodyFromDiscriminatorValue , m.SetBody)\n res[\"channelIdentity\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChannelIdentityFromDiscriminatorValue , m.SetChannelIdentity)\n res[\"chatId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetChatId)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"deletedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetDeletedDateTime)\n res[\"etag\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEtag)\n res[\"eventDetail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEventMessageDetailFromDiscriminatorValue , m.SetEventDetail)\n res[\"from\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChatMessageFromIdentitySetFromDiscriminatorValue , m.SetFrom)\n res[\"hostedContents\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageHostedContentFromDiscriminatorValue , m.SetHostedContents)\n res[\"importance\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseChatMessageImportance , m.SetImportance)\n res[\"lastEditedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastEditedDateTime)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"locale\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLocale)\n res[\"mentions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageMentionFromDiscriminatorValue , m.SetMentions)\n res[\"messageType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseChatMessageType , m.SetMessageType)\n res[\"policyViolation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateChatMessagePolicyViolationFromDiscriminatorValue , m.SetPolicyViolation)\n res[\"reactions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageReactionFromDiscriminatorValue , m.SetReactions)\n res[\"replies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateChatMessageFromDiscriminatorValue , m.SetReplies)\n res[\"replyToId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetReplyToId)\n res[\"subject\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSubject)\n res[\"summary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSummary)\n res[\"webUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetWebUrl)\n return res\n}", "func (m *Drive) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseItem.GetFieldDeserializers()\n res[\"bundles\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetBundles)\n res[\"driveType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDriveType)\n res[\"following\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetFollowing)\n res[\"items\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetItems)\n res[\"list\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateListFromDiscriminatorValue , m.SetList)\n res[\"owner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetOwner)\n res[\"quota\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateQuotaFromDiscriminatorValue , m.SetQuota)\n res[\"root\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveItemFromDiscriminatorValue , m.SetRoot)\n res[\"sharePointIds\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSharepointIdsFromDiscriminatorValue , m.SetSharePointIds)\n res[\"special\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveItemFromDiscriminatorValue , m.SetSpecial)\n res[\"system\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSystemFacetFromDiscriminatorValue , m.SetSystem)\n return res\n}", "func (m *AndroidLobApp) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.MobileLobApp.GetFieldDeserializers()\n res[\"minimumSupportedOperatingSystem\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateAndroidMinimumOperatingSystemFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMinimumSupportedOperatingSystem(val.(AndroidMinimumOperatingSystemable))\n }\n return nil\n }\n res[\"packageId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPackageId(val)\n }\n return nil\n }\n res[\"versionCode\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetVersionCode(val)\n }\n return nil\n }\n res[\"versionName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetVersionName(val)\n }\n return nil\n }\n return res\n}", "func (m *AgreementFile) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AgreementFileProperties.GetFieldDeserializers()\n res[\"localizations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAgreementFileLocalizationFromDiscriminatorValue , m.SetLocalizations)\n return res\n}", "func (m *ManagedAppPolicy) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"version\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetVersion)\n return res\n}", "func (m *Malware) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *EdgeHomeButtonHidden) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.EdgeHomeButtonConfiguration.GetFieldDeserializers()\n return res\n}", "func (m *Media) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"calleeDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceInfoFromDiscriminatorValue , m.SetCalleeDevice)\n res[\"calleeNetwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNetworkInfoFromDiscriminatorValue , m.SetCalleeNetwork)\n res[\"callerDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceInfoFromDiscriminatorValue , m.SetCallerDevice)\n res[\"callerNetwork\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNetworkInfoFromDiscriminatorValue , m.SetCallerNetwork)\n res[\"label\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLabel)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"streams\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMediaStreamFromDiscriminatorValue , m.SetStreams)\n return res\n}", "func (m *ServiceAnnouncement) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"healthOverviews\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceHealthFromDiscriminatorValue , m.SetHealthOverviews)\n res[\"issues\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceHealthIssueFromDiscriminatorValue , m.SetIssues)\n res[\"messages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateServiceUpdateMessageFromDiscriminatorValue , m.SetMessages)\n return res\n}", "func (m *DeviceAndAppManagementAssignmentFilter) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"assignmentFilterManagementType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAssignmentFilterManagementType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAssignmentFilterManagementType(val.(*AssignmentFilterManagementType))\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"payloads\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreatePayloadByFilterFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]PayloadByFilterable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(PayloadByFilterable)\n }\n }\n m.SetPayloads(res)\n }\n return nil\n }\n res[\"platform\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseDevicePlatformType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPlatform(val.(*DevicePlatformType))\n }\n return nil\n }\n res[\"roleScopeTags\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetRoleScopeTags(res)\n }\n return nil\n }\n res[\"rule\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRule(val)\n }\n return nil\n }\n return res\n}", "func (m *ConnectedOrganizationMembers) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SubjectSet.GetFieldDeserializers()\n res[\"connectedOrganizationId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConnectedOrganizationId)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n return res\n}", "func (m *ExternalConnection) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"configuration\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateConfigurationFromDiscriminatorValue , m.SetConfiguration)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"groups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExternalGroupFromDiscriminatorValue , m.SetGroups)\n res[\"items\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExternalItemFromDiscriminatorValue , m.SetItems)\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"operations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConnectionOperationFromDiscriminatorValue , m.SetOperations)\n res[\"schema\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSchemaFromDiscriminatorValue , m.SetSchema)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseConnectionState , m.SetState)\n return res\n}", "func (m *IdentityUserFlowAttributeAssignment) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isOptional\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsOptional)\n res[\"requiresVerification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetRequiresVerification)\n res[\"userAttribute\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentityUserFlowAttributeFromDiscriminatorValue , m.SetUserAttribute)\n res[\"userAttributeValues\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateUserAttributeValuesItemFromDiscriminatorValue , m.SetUserAttributeValues)\n res[\"userInputType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseIdentityUserFlowAttributeInputType , m.SetUserInputType)\n return res\n}", "func (m *AadUserConversationMember) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ConversationMember.GetFieldDeserializers()\n res[\"email\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEmail)\n res[\"tenantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTenantId)\n res[\"user\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateUserFromDiscriminatorValue , m.SetUser)\n res[\"userId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserId)\n return res\n}", "func (m *DirectoryAudit) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activityDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetActivityDateTime)\n res[\"activityDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetActivityDisplayName)\n res[\"additionalDetails\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateKeyValueFromDiscriminatorValue , m.SetAdditionalDetails)\n res[\"category\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCategory)\n res[\"correlationId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetCorrelationId)\n res[\"initiatedBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAuditActivityInitiatorFromDiscriminatorValue , m.SetInitiatedBy)\n res[\"loggedByService\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetLoggedByService)\n res[\"operationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOperationType)\n res[\"result\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseOperationResult , m.SetResult)\n res[\"resultReason\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResultReason)\n res[\"targetResources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateTargetResourceFromDiscriminatorValue , m.SetTargetResources)\n return res\n}", "func (m *KeyValue) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"key\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKey)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetValue)\n return res\n}", "func (m *ParentLabelDetails) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"color\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetColor(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"isActive\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsActive(val)\n }\n return nil\n }\n res[\"name\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetName(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"parent\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateParentLabelDetailsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetParent(val.(ParentLabelDetailsable))\n }\n return nil\n }\n res[\"sensitivity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSensitivity(val)\n }\n return nil\n }\n res[\"tooltip\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTooltip(val)\n }\n return nil\n }\n return res\n}", "func (m *IncomingContext) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"observedParticipantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetObservedParticipantId)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"onBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetOnBehalfOf)\n res[\"sourceParticipantId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSourceParticipantId)\n res[\"transferor\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetTransferor)\n return res\n}", "func (m *Group) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DirectoryObject.GetFieldDeserializers()\n res[\"acceptedSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetAcceptedSenders)\n res[\"allowExternalSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowExternalSenders)\n res[\"appRoleAssignments\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAppRoleAssignmentFromDiscriminatorValue , m.SetAppRoleAssignments)\n res[\"assignedLabels\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLabelFromDiscriminatorValue , m.SetAssignedLabels)\n res[\"assignedLicenses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAssignedLicenseFromDiscriminatorValue , m.SetAssignedLicenses)\n res[\"autoSubscribeNewMembers\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAutoSubscribeNewMembers)\n res[\"calendar\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateCalendarFromDiscriminatorValue , m.SetCalendar)\n res[\"calendarView\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetCalendarView)\n res[\"classification\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClassification)\n res[\"conversations\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConversationFromDiscriminatorValue , m.SetConversations)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"createdOnBehalfOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDirectoryObjectFromDiscriminatorValue , m.SetCreatedOnBehalfOf)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"drive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDriveFromDiscriminatorValue , m.SetDrive)\n res[\"drives\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDriveFromDiscriminatorValue , m.SetDrives)\n res[\"events\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEventFromDiscriminatorValue , m.SetEvents)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"extensions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateExtensionFromDiscriminatorValue , m.SetExtensions)\n res[\"groupLifecyclePolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupLifecyclePolicyFromDiscriminatorValue , m.SetGroupLifecyclePolicies)\n res[\"groupTypes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetGroupTypes)\n res[\"hasMembersWithLicenseErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasMembersWithLicenseErrors)\n res[\"hideFromAddressLists\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHideFromAddressLists)\n res[\"hideFromOutlookClients\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHideFromOutlookClients)\n res[\"isArchived\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsArchived)\n res[\"isAssignableToRole\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsAssignableToRole)\n res[\"isSubscribedByMail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsSubscribedByMail)\n res[\"licenseProcessingState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateLicenseProcessingStateFromDiscriminatorValue , m.SetLicenseProcessingState)\n res[\"mail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMail)\n res[\"mailEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetMailEnabled)\n res[\"mailNickname\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMailNickname)\n res[\"memberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMemberOf)\n res[\"members\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMembers)\n res[\"membershipRule\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMembershipRule)\n res[\"membershipRuleProcessingState\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMembershipRuleProcessingState)\n res[\"membersWithLicenseErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetMembersWithLicenseErrors)\n res[\"onenote\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateOnenoteFromDiscriminatorValue , m.SetOnenote)\n res[\"onPremisesDomainName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesDomainName)\n res[\"onPremisesLastSyncDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetOnPremisesLastSyncDateTime)\n res[\"onPremisesNetBiosName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesNetBiosName)\n res[\"onPremisesProvisioningErrors\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnPremisesProvisioningErrorFromDiscriminatorValue , m.SetOnPremisesProvisioningErrors)\n res[\"onPremisesSamAccountName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSamAccountName)\n res[\"onPremisesSecurityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOnPremisesSecurityIdentifier)\n res[\"onPremisesSyncEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetOnPremisesSyncEnabled)\n res[\"owners\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetOwners)\n res[\"permissionGrants\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateResourceSpecificPermissionGrantFromDiscriminatorValue , m.SetPermissionGrants)\n res[\"photo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateProfilePhotoFromDiscriminatorValue , m.SetPhoto)\n res[\"photos\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateProfilePhotoFromDiscriminatorValue , m.SetPhotos)\n res[\"planner\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePlannerGroupFromDiscriminatorValue , m.SetPlanner)\n res[\"preferredDataLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredDataLocation)\n res[\"preferredLanguage\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPreferredLanguage)\n res[\"proxyAddresses\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfPrimitiveValues(\"string\" , m.SetProxyAddresses)\n res[\"rejectedSenders\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetRejectedSenders)\n res[\"renewedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetRenewedDateTime)\n res[\"securityEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetSecurityEnabled)\n res[\"securityIdentifier\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSecurityIdentifier)\n res[\"settings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupSettingFromDiscriminatorValue , m.SetSettings)\n res[\"sites\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSiteFromDiscriminatorValue , m.SetSites)\n res[\"team\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateTeamFromDiscriminatorValue , m.SetTeam)\n res[\"theme\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetTheme)\n res[\"threads\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateConversationThreadFromDiscriminatorValue , m.SetThreads)\n res[\"transitiveMemberOf\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMemberOf)\n res[\"transitiveMembers\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDirectoryObjectFromDiscriminatorValue , m.SetTransitiveMembers)\n res[\"unseenCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetUnseenCount)\n res[\"visibility\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetVisibility)\n return res\n}", "func (m *IndustryDataRunActivity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIndustryDataActivityFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActivity(val.(IndustryDataActivityable))\n }\n return nil\n }\n res[\"blockingError\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreatePublicErrorFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBlockingError(val.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.PublicErrorable))\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseIndustryDataActivityStatus)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val.(*IndustryDataActivityStatus))\n }\n return nil\n }\n return res\n}", "func (m *WorkbookPivotTable) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"worksheet\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkbookWorksheetFromDiscriminatorValue , m.SetWorksheet)\n return res\n}", "func (m *MediaPrompt) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Prompt.GetFieldDeserializers()\n res[\"mediaInfo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMediaInfoFromDiscriminatorValue , m.SetMediaInfo)\n return res\n}", "func (m *EdiscoverySearch) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Search.GetFieldDeserializers()\n res[\"additionalSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDataSourceFromDiscriminatorValue , m.SetAdditionalSources)\n res[\"addToReviewSetOperation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEdiscoveryAddToReviewSetOperationFromDiscriminatorValue , m.SetAddToReviewSetOperation)\n res[\"custodianSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDataSourceFromDiscriminatorValue , m.SetCustodianSources)\n res[\"dataSourceScopes\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseDataSourceScopes , m.SetDataSourceScopes)\n res[\"lastEstimateStatisticsOperation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEdiscoveryEstimateOperationFromDiscriminatorValue , m.SetLastEstimateStatisticsOperation)\n res[\"noncustodialSources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEdiscoveryNoncustodialDataSourceFromDiscriminatorValue , m.SetNoncustodialSources)\n return res\n}", "func (m *Synchronization) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"jobs\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationJobFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationJobable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationJobable)\n }\n }\n m.SetJobs(res)\n }\n return nil\n }\n res[\"secrets\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationSecretKeyStringValuePairFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationSecretKeyStringValuePairable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationSecretKeyStringValuePairable)\n }\n }\n m.SetSecrets(res)\n }\n return nil\n }\n res[\"templates\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateSynchronizationTemplateFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]SynchronizationTemplateable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(SynchronizationTemplateable)\n }\n }\n m.SetTemplates(res)\n }\n return nil\n }\n return res\n}", "func (m *ThreatAssessmentResult) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"message\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetMessage)\n res[\"resultType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentResultType , m.SetResultType)\n return res\n}", "func (m *EdgeSearchEngineCustom) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.EdgeSearchEngineBase.GetFieldDeserializers()\n res[\"edgeSearchEngineOpenSearchXmlUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetEdgeSearchEngineOpenSearchXmlUrl)\n return res\n}", "func (m *BookingBusiness) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"address\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePhysicalAddressFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAddress(val.(PhysicalAddressable))\n }\n return nil\n }\n res[\"appointments\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingAppointmentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingAppointmentable)\n }\n }\n m.SetAppointments(res)\n }\n return nil\n }\n res[\"businessHours\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingWorkHoursFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingWorkHoursable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingWorkHoursable)\n }\n }\n m.SetBusinessHours(res)\n }\n return nil\n }\n res[\"businessType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBusinessType(val)\n }\n return nil\n }\n res[\"calendarView\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingAppointmentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingAppointmentable)\n }\n }\n m.SetCalendarView(res)\n }\n return nil\n }\n res[\"customers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingCustomerBaseFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingCustomerBaseable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingCustomerBaseable)\n }\n }\n m.SetCustomers(res)\n }\n return nil\n }\n res[\"customQuestions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingCustomQuestionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingCustomQuestionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingCustomQuestionable)\n }\n }\n m.SetCustomQuestions(res)\n }\n return nil\n }\n res[\"defaultCurrencyIso\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDefaultCurrencyIso(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"email\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetEmail(val)\n }\n return nil\n }\n res[\"isPublished\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsPublished(val)\n }\n return nil\n }\n res[\"languageTag\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLanguageTag(val)\n }\n return nil\n }\n res[\"phone\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPhone(val)\n }\n return nil\n }\n res[\"publicUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPublicUrl(val)\n }\n return nil\n }\n res[\"schedulingPolicy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateBookingSchedulingPolicyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSchedulingPolicy(val.(BookingSchedulingPolicyable))\n }\n return nil\n }\n res[\"services\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingServiceFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingServiceable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingServiceable)\n }\n }\n m.SetServices(res)\n }\n return nil\n }\n res[\"staffMembers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateBookingStaffMemberBaseFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]BookingStaffMemberBaseable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(BookingStaffMemberBaseable)\n }\n }\n m.SetStaffMembers(res)\n }\n return nil\n }\n res[\"webSiteUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetWebSiteUrl(val)\n }\n return nil\n }\n return res\n}", "func (m *FileAssessmentRequest) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ThreatAssessmentRequest.GetFieldDeserializers()\n res[\"contentData\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentData)\n res[\"fileName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFileName)\n return res\n}", "func (m *AuthenticationContext) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"detail\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseAuthenticationContextDetail)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDetail(val.(*AuthenticationContextDetail))\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *RelatedContact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"accessConsent\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAccessConsent(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"emailAddress\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetEmailAddress(val)\n }\n return nil\n }\n res[\"mobilePhone\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetMobilePhone(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"relationship\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseContactRelationship)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRelationship(val.(*ContactRelationship))\n }\n return nil\n }\n return res\n}", "func (m *MessageRule) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"actions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRuleActionsFromDiscriminatorValue , m.SetActions)\n res[\"conditions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRulePredicatesFromDiscriminatorValue , m.SetConditions)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"exceptions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMessageRulePredicatesFromDiscriminatorValue , m.SetExceptions)\n res[\"hasError\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasError)\n res[\"isEnabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsEnabled)\n res[\"isReadOnly\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsReadOnly)\n res[\"sequence\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetSequence)\n return res\n}", "func (m *WindowsInformationProtectionAppLearningSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"applicationName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetApplicationName)\n res[\"applicationType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseApplicationType , m.SetApplicationType)\n res[\"deviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDeviceCount)\n return res\n}", "func (m *ManagementTemplateStep) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"acceptedVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateManagementTemplateStepVersionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAcceptedVersion(val.(ManagementTemplateStepVersionable))\n }\n return nil\n }\n res[\"category\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseManagementCategory)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCategory(val.(*ManagementCategory))\n }\n return nil\n }\n res[\"createdByUserId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedByUserId(val)\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"lastActionByUserId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastActionByUserId(val)\n }\n return nil\n }\n res[\"lastActionDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastActionDateTime(val)\n }\n return nil\n }\n res[\"managementTemplate\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateManagementTemplateFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetManagementTemplate(val.(ManagementTemplateable))\n }\n return nil\n }\n res[\"portalLink\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateActionUrlFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPortalLink(val.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.ActionUrlable))\n }\n return nil\n }\n res[\"priority\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriority(val)\n }\n return nil\n }\n res[\"versions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateManagementTemplateStepVersionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ManagementTemplateStepVersionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ManagementTemplateStepVersionable)\n }\n }\n m.SetVersions(res)\n }\n return nil\n }\n return res\n}", "func (m *ApplicationCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateApplicationFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *OutlookUser) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"masterCategories\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOutlookCategoryFromDiscriminatorValue , m.SetMasterCategories)\n return res\n}", "func (m *PrintConnector) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"appVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppVersion(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"fullyQualifiedDomainName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetFullyQualifiedDomainName(val)\n }\n return nil\n }\n res[\"location\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreatePrinterLocationFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLocation(val.(PrinterLocationable))\n }\n return nil\n }\n res[\"operatingSystem\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOperatingSystem(val)\n }\n return nil\n }\n res[\"registeredDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRegisteredDateTime(val)\n }\n return nil\n }\n return res\n}", "func (m *ManagedDeviceOverview) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"deviceExchangeAccessStateSummary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceExchangeAccessStateSummaryFromDiscriminatorValue , m.SetDeviceExchangeAccessStateSummary)\n res[\"deviceOperatingSystemSummary\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateDeviceOperatingSystemSummaryFromDiscriminatorValue , m.SetDeviceOperatingSystemSummary)\n res[\"dualEnrolledDeviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDualEnrolledDeviceCount)\n res[\"enrolledDeviceCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetEnrolledDeviceCount)\n res[\"mdmEnrolledCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMdmEnrolledCount)\n return res\n}", "func (m *AttachmentItem) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"attachmentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAttachmentType , m.SetAttachmentType)\n res[\"contentId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentId)\n res[\"contentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetContentType)\n res[\"isInline\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsInline)\n res[\"name\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetName)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"size\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt64Value(m.SetSize)\n return res\n}", "func (m *TargetManager) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SubjectSet.GetFieldDeserializers()\n res[\"managerLevel\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetManagerLevel)\n return res\n}", "func (m *TeamworkConversationIdentity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Identity.GetFieldDeserializers()\n res[\"conversationIdentityType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseTeamworkConversationIdentityType , m.SetConversationIdentityType)\n return res\n}", "func (m *SchemaExtension) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"owner\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOwner(val)\n }\n return nil\n }\n res[\"properties\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateExtensionSchemaPropertyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ExtensionSchemaPropertyable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ExtensionSchemaPropertyable)\n }\n }\n m.SetProperties(res)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val)\n }\n return nil\n }\n res[\"targetTypes\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetTargetTypes(res)\n }\n return nil\n }\n return res\n}", "func (m *AndroidCustomConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DeviceConfiguration.GetFieldDeserializers()\n res[\"omaSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOmaSettingFromDiscriminatorValue , m.SetOmaSettings)\n return res\n}", "func (m *AccessReviewSet) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"definitions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessReviewScheduleDefinitionFromDiscriminatorValue , m.SetDefinitions)\n res[\"historyDefinitions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessReviewHistoryDefinitionFromDiscriminatorValue , m.SetHistoryDefinitions)\n return res\n}", "func (m *AuthenticationListener) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"priority\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriority(val)\n }\n return nil\n }\n res[\"sourceFilter\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateAuthenticationSourceFilterFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSourceFilter(val.(AuthenticationSourceFilterable))\n }\n return nil\n }\n return res\n}", "func (m *Vulnerability) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"activeExploitsObserved\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActiveExploitsObserved(val)\n }\n return nil\n }\n res[\"articles\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateArticleFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Articleable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Articleable)\n }\n }\n m.SetArticles(res)\n }\n return nil\n }\n res[\"commonWeaknessEnumerationIds\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetCommonWeaknessEnumerationIds(res)\n }\n return nil\n }\n res[\"components\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateVulnerabilityComponentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]VulnerabilityComponentable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(VulnerabilityComponentable)\n }\n }\n m.SetComponents(res)\n }\n return nil\n }\n res[\"createdDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCreatedDateTime(val)\n }\n return nil\n }\n res[\"cvss2Summary\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCvssSummaryFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCvss2Summary(val.(CvssSummaryable))\n }\n return nil\n }\n res[\"cvss3Summary\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCvssSummaryFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCvss3Summary(val.(CvssSummaryable))\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateFormattedContentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val.(FormattedContentable))\n }\n return nil\n }\n res[\"exploits\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateHyperlinkFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Hyperlinkable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Hyperlinkable)\n }\n }\n m.SetExploits(res)\n }\n return nil\n }\n res[\"exploitsAvailable\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetExploitsAvailable(val)\n }\n return nil\n }\n res[\"hasChatter\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetHasChatter(val)\n }\n return nil\n }\n res[\"lastModifiedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetLastModifiedDateTime(val)\n }\n return nil\n }\n res[\"priorityScore\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPriorityScore(val)\n }\n return nil\n }\n res[\"publishedDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPublishedDateTime(val)\n }\n return nil\n }\n res[\"references\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateHyperlinkFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Hyperlinkable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Hyperlinkable)\n }\n }\n m.SetReferences(res)\n }\n return nil\n }\n res[\"remediation\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateFormattedContentFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetRemediation(val.(FormattedContentable))\n }\n return nil\n }\n res[\"severity\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseVulnerabilitySeverity)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSeverity(val.(*VulnerabilitySeverity))\n }\n return nil\n }\n return res\n}", "func (m *AccessPackageCatalog) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"accessPackages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetAccessPackages)\n res[\"catalogType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAccessPackageCatalogType , m.SetCatalogType)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"isExternallyVisible\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsExternallyVisible)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAccessPackageCatalogState , m.SetState)\n return res\n}", "func (m *UserSettings) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"contributionToContentDiscoveryAsOrganizationDisabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetContributionToContentDiscoveryAsOrganizationDisabled)\n res[\"contributionToContentDiscoveryDisabled\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetContributionToContentDiscoveryDisabled)\n res[\"shiftPreferences\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateShiftPreferencesFromDiscriminatorValue , m.SetShiftPreferences)\n return res\n}", "func (m *DiscoveredSensitiveType) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"classificationAttributes\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateClassificationAttributeFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]ClassificationAttributeable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(ClassificationAttributeable)\n }\n }\n m.SetClassificationAttributes(res)\n }\n return nil\n }\n res[\"confidence\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetConfidence(val)\n }\n return nil\n }\n res[\"count\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt32Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCount(val)\n }\n return nil\n }\n res[\"id\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetUUIDValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetId(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *SectionGroup) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.OnenoteEntityHierarchyModel.GetFieldDeserializers()\n res[\"parentNotebook\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateNotebookFromDiscriminatorValue , m.SetParentNotebook)\n res[\"parentSectionGroup\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateSectionGroupFromDiscriminatorValue , m.SetParentSectionGroup)\n res[\"sectionGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateSectionGroupFromDiscriminatorValue , m.SetSectionGroups)\n res[\"sectionGroupsUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSectionGroupsUrl)\n res[\"sections\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateOnenoteSectionFromDiscriminatorValue , m.SetSections)\n res[\"sectionsUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetSectionsUrl)\n return res\n}", "func (m *DomainCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateDomainFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *BookingNamedEntity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n return res\n}", "func (m *CreatePostRequestBody) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"certificateSigningRequest\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreatePrintCertificateSigningRequestFromDiscriminatorValue , m.SetCertificateSigningRequest)\n res[\"connectorId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetConnectorId)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"hasPhysicalDevice\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetHasPhysicalDevice)\n res[\"manufacturer\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetManufacturer)\n res[\"model\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetModel)\n res[\"physicalDeviceId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetPhysicalDeviceId)\n return res\n}", "func (m *ApplicationSignInDetailedSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"aggregatedEventDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAggregatedEventDateTime(val)\n }\n return nil\n }\n res[\"appDisplayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppDisplayName(val)\n }\n return nil\n }\n res[\"appId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetAppId(val)\n }\n return nil\n }\n res[\"signInCount\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetInt64Value()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSignInCount(val)\n }\n return nil\n }\n res[\"status\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateSignInStatusFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStatus(val.(SignInStatusable))\n }\n return nil\n }\n return res\n}", "func (m *MicrosoftAuthenticatorAuthenticationMethodConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.AuthenticationMethodConfiguration.GetFieldDeserializers()\n res[\"featureSettings\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateMicrosoftAuthenticatorFeatureSettingsFromDiscriminatorValue , m.SetFeatureSettings)\n res[\"includeTargets\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMicrosoftAuthenticatorAuthenticationMethodTargetFromDiscriminatorValue , m.SetIncludeTargets)\n return res\n}", "func (m *ExternalActivity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"performedBy\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateIdentityFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPerformedBy(val.(Identityable))\n }\n return nil\n }\n res[\"startDateTime\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetTimeValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetStartDateTime(val)\n }\n return nil\n }\n res[\"type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseExternalActivityType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTypeEscaped(val.(*ExternalActivityType))\n }\n return nil\n }\n return res\n}", "func (m *WorkbookOperation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"error\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkbookOperationErrorFromDiscriminatorValue , m.SetError)\n res[\"resourceLocation\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResourceLocation)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWorkbookOperationStatus , m.SetStatus)\n return res\n}", "func (m *DeviceCategory) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n return res\n}", "func (m *AccessPackage) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"accessPackagesIncompatibleWith\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetAccessPackagesIncompatibleWith)\n res[\"assignmentPolicies\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageAssignmentPolicyFromDiscriminatorValue , m.SetAssignmentPolicies)\n res[\"catalog\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateAccessPackageCatalogFromDiscriminatorValue , m.SetCatalog)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"description\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDescription)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"incompatibleAccessPackages\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue , m.SetIncompatibleAccessPackages)\n res[\"incompatibleGroups\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateGroupFromDiscriminatorValue , m.SetIncompatibleGroups)\n res[\"isHidden\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsHidden)\n res[\"modifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetModifiedDateTime)\n return res\n}", "func (m *MessageSecurityStateCollectionResponse) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.BaseCollectionPaginationCountResponse.GetFieldDeserializers()\n res[\"value\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateMessageSecurityStateFromDiscriminatorValue , m.SetValue)\n return res\n}", "func (m *RecurrencePattern) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"dayOfMonth\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetDayOfMonth)\n res[\"daysOfWeek\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfEnumValues(ParseDayOfWeek , m.SetDaysOfWeek)\n res[\"firstDayOfWeek\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseDayOfWeek , m.SetFirstDayOfWeek)\n res[\"index\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWeekIndex , m.SetIndex)\n res[\"interval\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetInterval)\n res[\"month\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMonth)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseRecurrencePatternType , m.SetType)\n return res\n}", "func (m *DeviceManagementSettingXmlConstraint) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.DeviceManagementConstraint.GetFieldDeserializers()\n return res\n}", "func (m *TeamworkApplicationIdentity) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Identity.GetFieldDeserializers()\n res[\"applicationIdentityType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseTeamworkApplicationIdentityType , m.SetApplicationIdentityType)\n return res\n}", "func (m *AgreementAcceptance) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"agreementFileId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgreementFileId)\n res[\"agreementId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAgreementId)\n res[\"deviceDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceDisplayName)\n res[\"deviceId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceId)\n res[\"deviceOSType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceOSType)\n res[\"deviceOSVersion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDeviceOSVersion)\n res[\"expirationDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetExpirationDateTime)\n res[\"recordedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetRecordedDateTime)\n res[\"state\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseAgreementAcceptanceState , m.SetState)\n res[\"userDisplayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserDisplayName)\n res[\"userEmail\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserEmail)\n res[\"userId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserId)\n res[\"userPrincipalName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUserPrincipalName)\n return res\n}", "func (m *TeamSummary) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"guestsCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetGuestsCount)\n res[\"membersCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetMembersCount)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"ownersCount\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetOwnersCount)\n return res\n}", "func (m *EducationAssignment) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"addedStudentAction\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAddedStudentAction , m.SetAddedStudentAction)\n res[\"addToCalendarAction\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAddToCalendarOptions , m.SetAddToCalendarAction)\n res[\"allowLateSubmissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowLateSubmissions)\n res[\"allowStudentsToAddResourcesToSubmission\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetAllowStudentsToAddResourcesToSubmission)\n res[\"assignDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetAssignDateTime)\n res[\"assignedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetAssignedDateTime)\n res[\"assignTo\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationAssignmentRecipientFromDiscriminatorValue , m.SetAssignTo)\n res[\"categories\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationCategoryFromDiscriminatorValue , m.SetCategories)\n res[\"classId\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetClassId)\n res[\"closeDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCloseDateTime)\n res[\"createdBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetCreatedBy)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"dueDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetDueDateTime)\n res[\"feedbackResourcesFolderUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetFeedbackResourcesFolderUrl)\n res[\"grading\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationAssignmentGradeTypeFromDiscriminatorValue , m.SetGrading)\n res[\"instructions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationItemBodyFromDiscriminatorValue , m.SetInstructions)\n res[\"lastModifiedBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetLastModifiedBy)\n res[\"lastModifiedDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetLastModifiedDateTime)\n res[\"notificationChannelUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetNotificationChannelUrl)\n res[\"resources\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationAssignmentResourceFromDiscriminatorValue , m.SetResources)\n res[\"resourcesFolderUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetResourcesFolderUrl)\n res[\"rubric\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateEducationRubricFromDiscriminatorValue , m.SetRubric)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseEducationAssignmentStatus , m.SetStatus)\n res[\"submissions\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateEducationSubmissionFromDiscriminatorValue , m.SetSubmissions)\n res[\"webUrl\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetWebUrl)\n return res\n}", "func (m *OnlineMeetingInfo) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"conferenceId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetConferenceId(val)\n }\n return nil\n }\n res[\"joinUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetJoinUrl(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"phones\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreatePhoneFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]Phoneable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(Phoneable)\n }\n }\n m.SetPhones(res)\n }\n return nil\n }\n res[\"quickDial\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetQuickDial(val)\n }\n return nil\n }\n res[\"tollFreeNumbers\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfPrimitiveValues(\"string\")\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]string, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = *(v.(*string))\n }\n }\n m.SetTollFreeNumbers(res)\n }\n return nil\n }\n res[\"tollNumber\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetTollNumber(val)\n }\n return nil\n }\n return res\n}", "func (m *ThreatAssessmentRequest) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"category\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatCategory , m.SetCategory)\n res[\"contentType\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentContentType , m.SetContentType)\n res[\"createdBy\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateIdentitySetFromDiscriminatorValue , m.SetCreatedBy)\n res[\"createdDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetCreatedDateTime)\n res[\"expectedAssessment\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatExpectedAssessment , m.SetExpectedAssessment)\n res[\"requestSource\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentRequestSource , m.SetRequestSource)\n res[\"results\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetCollectionOfObjectValues(CreateThreatAssessmentResultFromDiscriminatorValue , m.SetResults)\n res[\"status\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseThreatAssessmentStatus , m.SetStatus)\n return res\n}", "func (m *SharePostRequestBody) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"endDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetEndDateTime)\n res[\"notifyTeam\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetNotifyTeam)\n res[\"startDateTime\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetStartDateTime)\n return res\n}", "func (m *ZebraFotaArtifact) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"boardSupportPackageVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetBoardSupportPackageVersion(val)\n }\n return nil\n }\n res[\"description\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDescription(val)\n }\n return nil\n }\n res[\"deviceModel\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDeviceModel(val)\n }\n return nil\n }\n res[\"osVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOsVersion(val)\n }\n return nil\n }\n res[\"patchVersion\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPatchVersion(val)\n }\n return nil\n }\n res[\"releaseNotesUrl\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetReleaseNotesUrl(val)\n }\n return nil\n }\n return res\n}", "func (m *Setting) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"displayName\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetDisplayName(val)\n }\n return nil\n }\n res[\"jsonValue\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetJsonValue(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n res[\"overwriteAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOverwriteAllowed(val)\n }\n return nil\n }\n res[\"settingId\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSettingId(val)\n }\n return nil\n }\n res[\"valueType\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseManagementParameterValueType)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetValueType(val.(*ManagementParameterValueType))\n }\n return nil\n }\n return res\n}", "func (m *ActionResultPart) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"error\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreatePublicErrorFromDiscriminatorValue , m.SetError)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *EventMessageDetail) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *SearchBucket) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"aggregationFilterToken\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetAggregationFilterToken)\n res[\"count\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetCount)\n res[\"key\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetKey)\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n return res\n}", "func (m *InternalDomainFederation) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.SamlOrWsFedProvider.GetFieldDeserializers()\n res[\"activeSignInUri\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetActiveSignInUri(val)\n }\n return nil\n }\n res[\"federatedIdpMfaBehavior\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParseFederatedIdpMfaBehavior)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetFederatedIdpMfaBehavior(val.(*FederatedIdpMfaBehavior))\n }\n return nil\n }\n res[\"isSignedAuthenticationRequestRequired\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsSignedAuthenticationRequestRequired(val)\n }\n return nil\n }\n res[\"nextSigningCertificate\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetNextSigningCertificate(val)\n }\n return nil\n }\n res[\"promptLoginBehavior\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetEnumValue(ParsePromptLoginBehavior)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetPromptLoginBehavior(val.(*PromptLoginBehavior))\n }\n return nil\n }\n res[\"signingCertificateUpdateStatus\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateSigningCertificateUpdateStatusFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSigningCertificateUpdateStatus(val.(SigningCertificateUpdateStatusable))\n }\n return nil\n }\n res[\"signOutUri\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetSignOutUri(val)\n }\n return nil\n }\n return res\n}", "func (m *VirtualEndpoint) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.Entity.GetFieldDeserializers()\n res[\"auditEvents\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcAuditEventFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcAuditEventable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcAuditEventable)\n }\n }\n m.SetAuditEvents(res)\n }\n return nil\n }\n res[\"bulkActions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcBulkActionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcBulkActionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcBulkActionable)\n }\n }\n m.SetBulkActions(res)\n }\n return nil\n }\n res[\"cloudPCs\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPCFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPCable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPCable)\n }\n }\n m.SetCloudPCs(res)\n }\n return nil\n }\n res[\"crossCloudGovernmentOrganizationMapping\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcCrossCloudGovernmentOrganizationMappingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetCrossCloudGovernmentOrganizationMapping(val.(CloudPcCrossCloudGovernmentOrganizationMappingable))\n }\n return nil\n }\n res[\"deviceImages\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcDeviceImageFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcDeviceImageable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcDeviceImageable)\n }\n }\n m.SetDeviceImages(res)\n }\n return nil\n }\n res[\"externalPartnerSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcExternalPartnerSettingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcExternalPartnerSettingable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcExternalPartnerSettingable)\n }\n }\n m.SetExternalPartnerSettings(res)\n }\n return nil\n }\n res[\"frontLineServicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcFrontLineServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcFrontLineServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcFrontLineServicePlanable)\n }\n }\n m.SetFrontLineServicePlans(res)\n }\n return nil\n }\n res[\"galleryImages\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcGalleryImageFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcGalleryImageable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcGalleryImageable)\n }\n }\n m.SetGalleryImages(res)\n }\n return nil\n }\n res[\"onPremisesConnections\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcOnPremisesConnectionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcOnPremisesConnectionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcOnPremisesConnectionable)\n }\n }\n m.SetOnPremisesConnections(res)\n }\n return nil\n }\n res[\"organizationSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcOrganizationSettingsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOrganizationSettings(val.(CloudPcOrganizationSettingsable))\n }\n return nil\n }\n res[\"provisioningPolicies\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcProvisioningPolicyFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcProvisioningPolicyable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcProvisioningPolicyable)\n }\n }\n m.SetProvisioningPolicies(res)\n }\n return nil\n }\n res[\"reports\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetObjectValue(CreateCloudPcReportsFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n m.SetReports(val.(CloudPcReportsable))\n }\n return nil\n }\n res[\"servicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcServicePlanable)\n }\n }\n m.SetServicePlans(res)\n }\n return nil\n }\n res[\"sharedUseServicePlans\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSharedUseServicePlanFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSharedUseServicePlanable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSharedUseServicePlanable)\n }\n }\n m.SetSharedUseServicePlans(res)\n }\n return nil\n }\n res[\"snapshots\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSnapshotFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSnapshotable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSnapshotable)\n }\n }\n m.SetSnapshots(res)\n }\n return nil\n }\n res[\"supportedRegions\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcSupportedRegionFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcSupportedRegionable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcSupportedRegionable)\n }\n }\n m.SetSupportedRegions(res)\n }\n return nil\n }\n res[\"userSettings\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetCollectionOfObjectValues(CreateCloudPcUserSettingFromDiscriminatorValue)\n if err != nil {\n return err\n }\n if val != nil {\n res := make([]CloudPcUserSettingable, len(val))\n for i, v := range val {\n if v != nil {\n res[i] = v.(CloudPcUserSettingable)\n }\n }\n m.SetUserSettings(res)\n }\n return nil\n }\n return res\n}", "func (m *RetentionLabelSettings) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"isContentUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsContentUpdateAllowed(val)\n }\n return nil\n }\n res[\"isDeleteAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsDeleteAllowed(val)\n }\n return nil\n }\n res[\"isLabelUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsLabelUpdateAllowed(val)\n }\n return nil\n }\n res[\"isMetadataUpdateAllowed\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsMetadataUpdateAllowed(val)\n }\n return nil\n }\n res[\"isRecordLocked\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetBoolValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetIsRecordLocked(val)\n }\n return nil\n }\n res[\"@odata.type\"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {\n val, err := n.GetStringValue()\n if err != nil {\n return err\n }\n if val != nil {\n m.SetOdataType(val)\n }\n return nil\n }\n return res\n}", "func (m *WorkforceIntegration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := m.ChangeTrackedEntity.GetFieldDeserializers()\n res[\"apiVersion\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetInt32Value(m.SetApiVersion)\n res[\"displayName\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetDisplayName)\n res[\"encryption\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetObjectValue(CreateWorkforceIntegrationEncryptionFromDiscriminatorValue , m.SetEncryption)\n res[\"isActive\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetBoolValue(m.SetIsActive)\n res[\"supportedEntities\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseWorkforceIntegrationSupportedEntities , m.SetSupportedEntities)\n res[\"url\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetUrl)\n return res\n}", "func (m *ResponseStatus) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {\n res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))\n res[\"@odata.type\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetStringValue(m.SetOdataType)\n res[\"response\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetEnumValue(ParseResponseType , m.SetResponse)\n res[\"time\"] = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.SetTimeValue(m.SetTime)\n return res\n}" ]
[ "0.71389484", "0.7128844", "0.70900005", "0.70069104", "0.7001896", "0.6972073", "0.6967879", "0.69341457", "0.6871311", "0.6712054", "0.6700039", "0.66957355", "0.66894317", "0.6688032", "0.6666724", "0.6651305", "0.66157794", "0.66102874", "0.6606821", "0.66024405", "0.6599896", "0.6598879", "0.65818304", "0.6577992", "0.6575462", "0.6571221", "0.6558583", "0.65570176", "0.655391", "0.65457654", "0.65452987", "0.654436", "0.6539618", "0.65335596", "0.6532791", "0.6529466", "0.65237796", "0.65210813", "0.65191525", "0.65166837", "0.65152216", "0.6511653", "0.6504438", "0.6485666", "0.6484648", "0.6481014", "0.6478389", "0.6477256", "0.64721036", "0.64683986", "0.6457381", "0.64548993", "0.64546514", "0.6453945", "0.6450939", "0.6440395", "0.64390045", "0.64305645", "0.64280385", "0.6422919", "0.6421019", "0.6419494", "0.6418019", "0.6411983", "0.6411156", "0.64096516", "0.64069825", "0.64064634", "0.64045924", "0.64000195", "0.63960165", "0.6395823", "0.6389498", "0.63867176", "0.63860023", "0.638458", "0.6379445", "0.6375804", "0.63719904", "0.636767", "0.6365444", "0.6363826", "0.63613665", "0.63555324", "0.6348026", "0.6339148", "0.63390654", "0.6336292", "0.63357437", "0.63329977", "0.63315904", "0.6328458", "0.632036", "0.6319762", "0.62957895", "0.62894315", "0.62844497", "0.62839735", "0.62711537", "0.6271046", "0.627067" ]
0.0
-1
GetKeyPath gets the keyPath property value. The registry key path to detect Win32 Line of Business (LoB) app
func (m *Win32LobAppRegistryDetection) GetKeyPath()(*string) { val, err := m.GetBackingStore().Get("keyPath") if err != nil { panic(err) } if val != nil { return val.(*string) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) GetKeyPath()(*string) {\n return m.keyPath\n}", "func (m *Win32LobAppRegistryRule) SetKeyPath(value *string)() {\n m.keyPath = value\n}", "func (m *Win32LobAppRegistryDetection) SetKeyPath(value *string)() {\n err := m.GetBackingStore().Set(\"keyPath\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppFileSystemDetection) GetPath()(*string) {\n val, err := m.GetBackingStore().Get(\"path\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func getKeyPath(name string) string {\n\treturn configDir + \"/hil-vpn-\" + name + \".key\"\n}", "func (di *directoryInfo) getPathKey(path string) (string, error) {\n\tif di.regexp == nil {\n\t\treturn \"\", errors.New(\"regexp is not set.\")\n\t}\n\n\tmatches := di.regexp.FindStringSubmatch(path)\n\tif matches != nil {\n\t\treturn matches[di.Config.MatchNum], nil\n\t} else {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"key not found. path: %s\", path))\n\t}\n}", "func (rc RC) Path(key string) (string, bool) {\n\tv, ok := rc[key]\n\tif !ok {\n\t\treturn \"\", false\n\t} else if t := strings.TrimPrefix(v, \"~\"); t != v && (t == \"\" || t[0] == '/') {\n\t\treturn os.Getenv(\"HOME\") + t, true\n\t}\n\treturn v, true\n}", "func (pp *ProcessProfile) GetPathKeyValue(cookie keyvalue.Cookie) *keyvalue.KeyValue {\n\tpathB := [kernel.PathMax]byte{}\n\tcopy(pathB[:], pp.BinaryPath)\n\treturn &keyvalue.KeyValue{\n\t\tKey: &keyvalue.BinaryPathKey{\n\t\t\tCookie: cookie,\n\t\t\tPath: pathB,\n\t\t},\n\t\tValue: &keyvalue.CookieValue{\n\t\t\tCookie: pp.binaryPathID,\n\t\t},\n\t}\n}", "func (km *KeyManager) GetPathKey(path string, i int) (*bip32.Key, error) {\n\tkey, ok := km.getKey(path)\n\tif ok {\n\t\treturn key, nil\n\t}\n\n\tif path == \"m\" {\n\t\treturn km.getMasterKey()\n\t}\n\n\tderivationPath, err := ParseDerivationPath(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparentPath := derivationPath[:i] \t\n\tparent, err := km.GetPathKey(parentPath.toString(), i-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err = parent.NewChildKey(derivationPath[i])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkm.setKey(path, key)\n\treturn key, nil\n}", "func GetKeysPath() string {\n\tlocation := os.Getenv(\"SSH_KEYS_LOCATION\")\n\tif !strings.HasSuffix(location, fmt.Sprintf(\"%c\", os.PathSeparator)) {\n\t\tlocation += fmt.Sprintf(\"%c\", os.PathSeparator)\n\t}\n\treturn location\n}", "func (self *recordSet) KeyPath(key int64) (string, map[string]string) {\n var path = fmt.Sprintf(\"R%020d\", key)\n\tvar items = self.Decompose(path)\n path = fmt.Sprintf(\"%s.json\", path)\n return filepath.Join(self.RecordsPath(), path), items\n}", "func (c *DiskCache) KeyPath(ctx context.Context, repo *gitalypb.Repository, req proto.Message) (string, error) {\n\treturn c.keyer.keyPath(ctx, repo, req)\n}", "func (a tlsCredentials) getKeyMountPath() string {\n\tsecret := monitoringv1.SecretOrConfigMap{Secret: &a.keySecret}\n\treturn a.tlsPathForSelector(secret, \"key\")\n}", "func (h Hashicorp) GetPath() string {\n\treturn h.FilePath\n}", "func GetKey(buf *bytes.Buffer, path []*gpb.PathElem) (string, map[string]string) {\n\tlabels := make(map[string]string)\n\n\tfor _, elem := range path {\n\t\tif len(elem.Name) > 0 {\n\t\t\tbuf.WriteRune('/')\n\t\t\tbuf.WriteString(elem.Name)\n\t\t}\n\n\t\tfor key, value := range elem.Key {\n\t\t\tif _, ok := labels[key]; ok {\n\t\t\t\tlabels[buf.String()+\"/\"+key] = value\n\t\t\t} else {\n\t\t\t\tlabels[key] = value\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf.ReadRune()\n\n\treturn buf.String(), labels\n}", "func (d *Fs) getPath(key string) (fPath string) {\n\tfPath = d.basePath\n\trunes := []rune(key)\n\tif len(key) > 4 {\n\t\tfPath = filepath.Join(fPath, string(runes[0:2]), string(runes[2:4]))\n\t}\n\treturn\n}", "func getOSDependantKey(path string, isDir bool) string {\n\tsep := \"/\"\n\n\t// for windows make sure to print in 'windows' specific style.\n\tif runtime.GOOS == \"windows\" {\n\t\tpath = strings.Replace(path, \"/\", \"\\\\\", -1)\n\t\tsep = \"\\\\\"\n\t}\n\n\tif isDir && !strings.HasSuffix(path, sep) {\n\t\treturn fmt.Sprintf(\"%s%s\", path, sep)\n\t}\n\treturn path\n}", "func PSPath(path string) string {\n\tpsPath := path\n\tfor i, j := range map[string]string{\n\t\t`HKEY_CURRENT_USER\\`: `HKCU:`,\n\t\t`HKEY_LOCAL_MACHINE\\`: `HKLM:`,\n\t} {\n\t\tif strings.HasPrefix(path, i) {\n\t\t\tpsPath = j + path[len(i):]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn psPath\n}", "func PathForKey(raw string) paths.Unencrypted {\n\treturn paths.NewUnencrypted(strings.TrimSuffix(raw, \"/\"))\n}", "func (k *K8S) Path() string {\n\treturn k.name + \"-root-master-key\"\n}", "func (f *FileStore) getPathByKey(key string) string {\n\treturn filepath.Join(f.directoryPath, key)\n}", "func (f *FileStore) getPathByKey(key string) string {\n\treturn filepath.Join(f.directoryPath, key)\n}", "func (c *Conf) GetDomainKey(path string) []string {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\tdomainKey, err := c.root.getDomainKey(path)\n\tif err != nil {\n\t\treturn []string{}\n\t}\n\treturn domainKey\n}", "func (m *RegistryKeyState) GetKey()(*string) {\n return m.key\n}", "func TestKeyToPath(t *testing.T) {\n\ttestKey(t, \"\", \"/\")\n\ttestKey(t, \"/\", \"/\")\n\ttestKey(t, \"///\", \"/\")\n\ttestKey(t, \"hello/world/\", \"hello/world\")\n\ttestKey(t, \"///hello////world/../\", \"/hello\")\n}", "func (k *Keys) PBEKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\treturn path.Join(k.dir, PBEKeysetPath)\n}", "func (o *Gojwt) GetPubKeyPath()(string){\n return o.pubKeyPath\n}", "func (k *Key) path() (string, error) {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get current user\")\n\t}\n\treturn path.Join(usr.HomeDir, *identity), nil\n}", "func (p *RandomizedTempPaths) GetPath(key string) (string, error) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tif val, ok := p.paths[key]; ok {\n\t\treturn val, nil\n\t}\n\tuniqueId, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trepoPath := filepath.Join(p.root, uniqueId.String())\n\tp.paths[key] = repoPath\n\treturn repoPath, nil\n}", "func PathToKey(path string) (string) {\n\treturn base64.StdEncoding.EncodeToString([]byte(path))\n}", "func (i *Instance) Path() (string, error) {\n\tref, _, _, err := i.GetAsAny(WmiPathKey)\n\treturn ref.(string), err\n}", "func KeyToPath(key string) (string) {\n\tpath, err := base64.StdEncoding.DecodeString(key)\n\tif err != nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn string(path)\n\t}\n}", "func (me *Image) Path() string {\n\treturn me.key.path\n}", "func GetCfgPath(c domain.CLIContext) string {\n\treturn c.String(cfgPathKey)\n}", "func (b *BaseBuild) Path(keys ...string) ([]string, error) {\n\tpaths := make([]string, len(keys))\n\tfor i, key := range keys {\n\t\tif path, found := b.Paths[key]; found {\n\t\t\tpaths[i] = path\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"no path for %q\", key)\n\t\t}\n\t}\n\treturn paths, nil\n}", "func (c *Config) KeyStorePath() string {\n\tkeystorePath := pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\treturn filepath.Join(keystorePath, \"keystore\")\n}", "func (c *Crypto) PrivateKeyPath() string {\n\treturn c.privateKeyPath\n}", "func (u *UFlat) GetPathForByteKey(key []byte) (path string, err error) {\n\tif key == nil {\n\t\terr = NilKey\n\t} else {\n\t\tstrKey := hex.EncodeToString(key)\n\t\tpath, err = u.GetPathForHexKey(strKey)\n\t}\n\treturn\n}", "func (a *PhonebookAccess1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func KBFSBinPath(runMode libkb.RunMode, binPath string) (string, error) {\n\treturn kbfsBinPathDefault(runMode, binPath)\n}", "func GetByPath(path string, mp map[string]any) (val any, ok bool) {\n\tif val, ok := mp[path]; ok {\n\t\treturn val, true\n\t}\n\n\t// no sub key\n\tif len(mp) == 0 || strings.IndexByte(path, '.') < 1 {\n\t\treturn nil, false\n\t}\n\n\t// has sub key. eg. \"top.sub\"\n\tkeys := strings.Split(path, \".\")\n\treturn GetByPathKeys(mp, keys)\n}", "func (c *Crypto) PublicKeyPath() string {\n\treturn c.publicKeyPath\n}", "func kpath(key, keytail string) string {\n\tl, t := len(key), len(keytail)\n\treturn key[:l-t]\n}", "func wslConfigGetKernelPath() (string, error) {\n\tcfg, err := wslConfigLoad()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn cfg.Section(wsl2Section).Key(wsl2KernelKey).String(), nil\n}", "func (s *K8s) Path() string {\n\treturn s.moduleDir\n}", "func (metadata EventMetadata) GetPath() (string, error) {\n\tpath, err := os.Readlink(\n\t\tfilepath.Join(\n\t\t\tProcFsFdInfo,\n\t\t\tstrconv.FormatUint(\n\t\t\t\tuint64(metadata.Fd),\n\t\t\t\t10,\n\t\t\t),\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"fanotify: %w\", err)\n\t}\n\n\treturn path, nil\n}", "func GetPath(mounter volume.Mounter) (string, error) {\n\tpath := mounter.GetPath()\n\tif path == \"\" {\n\t\treturn \"\", fmt.Errorf(\"path is empty %s\", reflect.TypeOf(mounter).String())\n\t}\n\treturn path, nil\n}", "func (f *File) Path() string {\n\treturn \"/\" + f.key\n}", "func (e *EtcdClientCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdClientKeyFileName) }", "func getPath(bucket, key string) string {\n\tfileName := fmt.Sprintf(\"%s.value\", key)\n\treturn fmt.Sprintf(\"%s/key/%s\", bucket, fileName)\n}", "func (u *UFlat) GetPathForHexKey(key string) (path string, err error) {\n\tif key == \"\" {\n\t\terr = EmptyKey\n\t} else {\n\t\tpath = filepath.Join(u.path, key)\n\t}\n\treturn\n}", "func GetHDKeyByPath(hdKey *hdkeychain.ExtendedKey, chain, num uint32) (*hdkeychain.ExtendedKey, error) {\r\n\r\n\t// Derive the child key from the chain path\r\n\tchildKeyChain, err := GetHDKeyChild(hdKey, chain)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// Get the child key from the num path\r\n\treturn GetHDKeyChild(childKeyChain, num)\r\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookieOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConsistentHashLoadBalancerSettingsHttpCookie) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (c *CaHostKeyCert) GetPath() string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_key_cert/%s\", c.Reference)\n}", "func (prodController *ProducerController) GetPath() string {\n\treturn producerPath\n}", "func (zk *ZookeeperMaster) GetPath() string {\n\treturn zk.selfPath\n}", "func (o *SamlConfigurationProperties) GetPath() SamlConfigurationPropertyItemsArray {\n\tif o == nil || o.Path == nil {\n\t\tvar ret SamlConfigurationPropertyItemsArray\n\t\treturn ret\n\t}\n\treturn *o.Path\n}", "func (r InboundRequest) PathString(key string) (string, bool) {\n s, err := r.PathParams.String(key)\n return s, err == nil\n}", "func (e *EtcdCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdKeyFileName) }", "func GetSubscribeKeyPath(subscribeType string) string {\n\tvar subscribeKeyPath string\n\tif subscribeType == SerAvailabilityNotificationSubscription {\n\t\tsubscribeKeyPath = AvailAppSubKeyPath\n\t} else {\n\t\tsubscribeKeyPath = EndAppSubKeyPath\n\t}\n\treturn subscribeKeyPath\n}", "func (conf blah) Path() string {\n\treturn configPath\n}", "func (s *Service) getPathAndKey(\n\tctx context.Context,\n\treq *pb.PullPathRequest,\n\tbuck *tdb.Bucket,\n\tpth path.Path,\n) (path.Resolved, []byte, error) {\n\tfileKey, err := buck.GetFileEncryptionKeyForPath(req.Path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar filePath path.Resolved\n\tif buck.IsPrivate() {\n\t\tbuckPath, err := util.NewResolvedPath(buck.Path)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tnp, isDir, r, err := s.getNodesToPath(ctx, buckPath, req.Path, buck.GetLinkEncryptionKey())\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif r != \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"could not resolve path: %s\", pth)\n\t\t}\n\t\tif isDir {\n\t\t\treturn nil, nil, fmt.Errorf(\"node is a directory\")\n\t\t}\n\t\tfn := np[len(np)-1]\n\t\tfilePath = path.IpfsPath(fn.new.Cid())\n\t} else {\n\t\tfilePath, err = s.IPFSClient.ResolvePath(ctx, pth)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn filePath, fileKey, nil\n}", "func DeterminePath(configPath string, keyPath string) string {\n\tif !IsDir(configPath) {\n\t\tconfigPath = filepath.Dir(configPath)\n\t}\n\tsep := string(filepath.Separator)\n\tabs, _ := filepath.Abs(keyPath)\n\trel := strings.TrimRight(keyPath, sep)\n\tif abs != rel || !strings.Contains(keyPath, sep) {\n\t\t// The path was relative\n\t\treturn filepath.Join(configPath, keyPath)\n\t}\n\treturn abs\n}", "func (ss *StateService) GetKegByPath(path string) (keg.IKeg, error) {\n\tkeg, exist := ss.kegByPath[path]\n\tif !exist {\n\t\treturn nil, errors.New(\"Keg not found\")\n\t}\n\treturn keg, nil\n}", "func (o ConsistentHashLoadBalancerSettingsHttpCookiePtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConsistentHashLoadBalancerSettingsHttpCookie) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (d *Device) GetPath() string {\n\treturn d.path\n}", "func K8sPKIPath(p string) string {\n\treturn filepath.Join(k8sPKIPath, p)\n}", "func (b *BgpRouteMap) GetPath() string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/route_map/%s\", b.Reference)\n}", "func (s *switchPortAllocations) Path() string {\n\treturn s.path\n}", "func GetPrivateKeyByPath(hdKey *hdkeychain.ExtendedKey, chain, num uint32) (*bsvec.PrivateKey, error) {\r\n\r\n\t// Get the child key from the num & chain\r\n\tchildKeyNum, err := GetHDKeyByPath(hdKey, chain, num)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// Get the private key\r\n\treturn childKeyNum.ECPrivKey()\r\n}", "func (app *App) GetDataPath() string {\n\tpath, err := app.SettingsService.GetString(\"general.dataPath\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn path\n}", "func (b *BrBuilder) GetSymbolPath(hash, name string) string {\n\treturn filepath.Join(b.StorePath, name, hash, name)\n}", "func (o FluxConfigurationKustomizationOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FluxConfigurationKustomization) *string { return v.Path }).(pulumi.StringPtrOutput)\n}", "func (config *SQLConfiguration) GetPath() string {\n\tvar path, defaultFile, customFile string\n\tpath = \"database/\"\n\tdefaultFile = path + \"default.json\"\n\tcustomFile = path + \"custom.json\"\n\tif _, err := os.Open(\"conf/\" + customFile); err == nil {\n\t\treturn customFile\n\t}\n\treturn defaultFile\n}", "func (o *CustconfDynamicCacheRule) GetPathFilter() string {\n\tif o == nil || o.PathFilter == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PathFilter\n}", "func (sps SecurityProfileSpec) GetProfilePathsKeyValues() ([]*keyvalue.KeyValue, error) {\n\trep := []*keyvalue.KeyValue{}\n\tfor _, pp := range sps.ProcessProfiles {\n\t\trep = append(rep, pp.GetPathKeyValue(sps.securityProfileID))\n\t}\n\treturn rep, nil\n}", "func (b *BtcWallet) deriveKeyByBIP32Path(path []uint32) (*btcec.PrivateKey,\n\terror) {\n\n\t// Make sure we get a full path with exactly 5 elements. A path is\n\t// either custom purpose one with 4 dynamic and one static elements:\n\t// m/1017'/coinType'/keyFamily'/0/index\n\t// Or a default BIP49/89 one with 5 elements:\n\t// m/purpose'/coinType'/account'/change/index\n\tconst expectedDerivationPathDepth = 5\n\tif len(path) != expectedDerivationPathDepth {\n\t\treturn nil, fmt.Errorf(\"invalid BIP32 derivation path, \"+\n\t\t\t\"expected path length %d, instead was %d\",\n\t\t\texpectedDerivationPathDepth, len(path))\n\t}\n\n\t// Assert that the first three parts of the path are actually hardened\n\t// to avoid under-flowing the uint32 type.\n\tif err := assertHardened(path[0], path[1], path[2]); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid BIP32 derivation path, \"+\n\t\t\t\"expected first three elements to be hardened: %w\", err)\n\t}\n\n\tpurpose := path[0] - hdkeychain.HardenedKeyStart\n\tcoinType := path[1] - hdkeychain.HardenedKeyStart\n\taccount := path[2] - hdkeychain.HardenedKeyStart\n\tchange, index := path[3], path[4]\n\n\t// Is this a custom lnd internal purpose key?\n\tswitch purpose {\n\tcase keychain.BIP0043Purpose:\n\t\t// Make sure it's for the same coin type as our wallet's\n\t\t// keychain scope.\n\t\tif coinType != b.chainKeyScope.Coin {\n\t\t\treturn nil, fmt.Errorf(\"invalid BIP32 derivation \"+\n\t\t\t\t\"path, expected coin type %d, instead was %d\",\n\t\t\t\tb.chainKeyScope.Coin, coinType)\n\t\t}\n\n\t\treturn b.deriveKeyByLocator(keychain.KeyLocator{\n\t\t\tFamily: keychain.KeyFamily(account),\n\t\t\tIndex: index,\n\t\t})\n\n\t// Is it a standard, BIP defined purpose that the wallet understands?\n\tcase waddrmgr.KeyScopeBIP0044.Purpose,\n\t\twaddrmgr.KeyScopeBIP0049Plus.Purpose,\n\t\twaddrmgr.KeyScopeBIP0084.Purpose,\n\t\twaddrmgr.KeyScopeBIP0086.Purpose:\n\n\t\t// We're going to continue below the switch statement to avoid\n\t\t// unnecessary indentation for this default case.\n\n\t// Currently, there is no way to import any other key scopes than the\n\t// one custom purpose or three standard ones into lnd's wallet. So we\n\t// shouldn't accept any other scopes to sign for.\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid BIP32 derivation path, \"+\n\t\t\t\"unknown purpose %d\", purpose)\n\t}\n\n\t// Okay, we made sure it's a BIP49/84 key, so we need to derive it now.\n\t// Interestingly, the btcwallet never actually uses a coin type other\n\t// than 0 for those keys, so we need to make sure this behavior is\n\t// replicated here.\n\tif coinType != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid BIP32 derivation path, coin \" +\n\t\t\t\"type must be 0 for BIP49/84 btcwallet keys\")\n\t}\n\n\t// We only expect to be asked to sign with key scopes that we know\n\t// about. So if the scope doesn't exist, we don't create it.\n\tscope := waddrmgr.KeyScope{\n\t\tPurpose: purpose,\n\t\tCoin: coinType,\n\t}\n\tscopedMgr, err := b.wallet.Manager.FetchScopedKeyManager(scope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching manager for scope %v: \"+\n\t\t\t\"%w\", scope, err)\n\t}\n\n\t// Let's see if we can hit the private key cache.\n\tkeyPath := waddrmgr.DerivationPath{\n\t\tInternalAccount: account,\n\t\tAccount: account,\n\t\tBranch: change,\n\t\tIndex: index,\n\t}\n\tprivKey, err := scopedMgr.DeriveFromKeyPathCache(keyPath)\n\tif err == nil {\n\t\treturn privKey, nil\n\t}\n\n\t// The key wasn't in the cache, let's fully derive it now.\n\terr = walletdb.View(b.db, func(tx walletdb.ReadTx) error {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\n\t\taddr, err := scopedMgr.DeriveFromKeyPath(addrmgrNs, keyPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error deriving private key: %w\", err)\n\t\t}\n\n\t\tprivKey, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error deriving key from path %#v: %w\",\n\t\t\tkeyPath, err)\n\t}\n\n\treturn privKey, nil\n}", "func (app *Application) Path() dbus.ObjectPath {\n\treturn app.config.ObjectPath\n}", "func (ds *Datastore) path(key datastore.Key) string {\n\treturn strings.TrimLeft(ds.Path+key.String(), \"/\")\n\t// return strings.TrimLeft(filepath.Join(ds.Path, key.String()), \"/\")\n}", "func pathToKey(jsonPath string) (string, error) {\n\treg, err := regexp.Compile(\"[^-._a-zA-Z0-9]+\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reg.ReplaceAllString(jsonPath, \"\"), nil\n}", "func (prodController *ProducersController) GetPath() string {\n\treturn producersPath\n}", "func (r *SysNet) getPath() (string, error) {\n\tvar procPath string\n\n\tswitch r.Path {\n\tcase sysNetPathCore:\n\t\tprocPath = path.Join(path.Join(sysNetPath, sysNetPathCore), r.Property)\n\t\tbreak\n\tcase sysNetPathIPv4:\n\n\t\tif r.Link != \"\" {\n\t\t\tprocPath = path.Join(path.Join(path.Join(path.Join(sysNetPath, sysNetPathIPv4), \"conf\"), r.Link), r.Property)\n\t\t} else {\n\t\t\tprocPath = path.Join(path.Join(sysNetPath, sysNetPathIPv4), r.Property)\n\t\t}\n\t\tbreak\n\tcase sysNetPathIPv6:\n\n\t\tif r.Link != \"\" {\n\t\t\tprocPath = path.Join(path.Join(path.Join(path.Join(sysNetPath, sysNetPathIPv6), \"conf\"), r.Link), r.Property)\n\t\t} else {\n\t\t\tprocPath = path.Join(path.Join(sysNetPath, sysNetPathIPv6), r.Property)\n\t\t}\n\t\tbreak\n\tdefault:\n\t\treturn \"\", errors.New(\"Path not found\")\n\t}\n\n\treturn procPath, nil\n}", "func (a *AdminPolicyStatus1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func (apnian Apnian) AuthKeyPath() string {\n\trel := fmt.Sprintf(\"keys/%s\", apnian.P8KeyName)\n\treturn fmt.Sprintf(\"%s/%s\", apnian.Configurer.Root, rel)\n}", "func (c *cache) path(key string) string {\n\t// Prepend an intermediate directory of a couple of chars to make it a bit more explorable\n\treturn path.Join(c.root, string([]byte{key[0], key[1]}), key)\n}", "func (c *SFTPServer) PrivateKeyPath() string {\n\treturn path.Join(c.BasePath, \".sftp/id_ed25519\")\n}", "func (b *BgpSystem) GetPath() string { return fmt.Sprintf(\"/api/objects/bgp/system/%s\", b.Reference) }", "func (o *Gojwt) SetPubKeyPath(path string)(){\n o.pubKeyPath = path\n}", "func GetPathOutput(sensors []*config.Sensor) map[string]string {\n\tvar pathOutput = make(map[string]string)\n\n\tfor _, sensor := range sensors {\n\t\tif strings.HasSuffix(sensor.Path, \"/\") {\n\t\t\tpathOutput[sensor.Path] = sensor.Output\n\t\t} else {\n\t\t\tpathOutput[fmt.Sprintf(\"%s/\", sensor.Path)] = sensor.Output\n\t\t}\n\t}\n\n\treturn pathOutput\n}", "func (o *Gojwt) GetPrivKeyPath()(string){\n return o.privKeyPath\n}", "func (k *Kluster) Path() string {\n\treturn k.path\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsReadinessProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Payment) GetPath() []string {\n\tif m != nil {\n\t\treturn m.Path\n\t}\n\treturn nil\n}", "func (m *Payment) GetPath() []string {\n\tif m != nil {\n\t\treturn m.Path\n\t}\n\treturn nil\n}", "func (m *Payment) GetPath() []string {\n\tif m != nil {\n\t\treturn m.Path\n\t}\n\treturn nil\n}", "func (m *GroupPolicyDefinition) GetCategoryPath()(*string) {\n val, err := m.GetBackingStore().Get(\"categoryPath\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *Global) GetCfgPath() string {\n\tif o == nil || o.CfgPath == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.CfgPath\n}", "func (c *GlobalConfig) GetPidPath() string {\n\treturn c.PidFilePath\n}", "func (r Ref) GetPath() string {\n\tvar path = \"\"\n\tstart := strings.Index(string(r), \"//\")\n\tif start >= 0 {\n\t\tpath = string(r)[(start + len(\"//\")):]\n\t\tend := strings.Index(path, \":\")\n\t\tif end >= 0 {\n\t\t\tpath = path[:end]\n\t\t}\n\t}\n\n\treturn path\n}", "func getPath() string {\n\treturn os.Getenv(pathEnvVar)\n}" ]
[ "0.78984046", "0.67674714", "0.6547843", "0.6513192", "0.6465143", "0.62664264", "0.60375607", "0.603131", "0.59816104", "0.59493417", "0.5889502", "0.5860767", "0.58368987", "0.5812933", "0.5775046", "0.57547045", "0.57531434", "0.57431287", "0.5739169", "0.57093596", "0.56278104", "0.56278104", "0.5570013", "0.5568522", "0.55499816", "0.5529412", "0.5527948", "0.5522328", "0.55136794", "0.55055296", "0.54955167", "0.5487193", "0.5479561", "0.54704195", "0.54596645", "0.5413519", "0.5385568", "0.5335786", "0.53041506", "0.5287591", "0.527594", "0.52753407", "0.5261195", "0.52511996", "0.5244147", "0.5215736", "0.52101326", "0.518493", "0.51827013", "0.5181311", "0.5165272", "0.5159152", "0.5152338", "0.51359457", "0.51353806", "0.51332283", "0.51092756", "0.51086533", "0.51048136", "0.5103024", "0.51012015", "0.5099765", "0.5087313", "0.508076", "0.5077041", "0.5065371", "0.5064181", "0.5061887", "0.5061181", "0.5061131", "0.5057782", "0.5047926", "0.50444835", "0.5036719", "0.503117", "0.5022828", "0.5022187", "0.5015568", "0.5006467", "0.4994993", "0.4994712", "0.49783108", "0.4973334", "0.49681818", "0.49652082", "0.49610403", "0.49589774", "0.49522164", "0.49514964", "0.49436638", "0.49435332", "0.49429289", "0.49424082", "0.49424082", "0.49424082", "0.4939667", "0.4938633", "0.49342299", "0.49341163", "0.4931377" ]
0.78582966
1
GetOperator gets the operator property value. Contains properties for detection operator.
func (m *Win32LobAppRegistryDetection) GetOperator()(*Win32LobAppDetectionOperator) { val, err := m.GetBackingStore().Get("operator") if err != nil { panic(err) } if val != nil { return val.(*Win32LobAppDetectionOperator) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f Filter) GetOperator() string {\n\treturn f.operator\n}", "func (m *Win32LobAppRegistryRule) GetOperator()(*Win32LobAppRuleOperator) {\n return m.operator\n}", "func GetOperator(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *OperatorState, opts ...pulumi.ResourceOption) (*Operator, error) {\n\tvar resource Operator\n\terr := ctx.ReadResource(\"kubernetes:deploy.hybridapp.io/v1alpha1:Operator\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *Win32LobAppFileSystemDetection) GetOperator()(*Win32LobAppDetectionOperator) {\n val, err := m.GetBackingStore().Get(\"operator\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppDetectionOperator)\n }\n return nil\n}", "func (OperatorFactory) GetOperator(operation Operation) Operator {\n\tswitch operation {\n\tcase Sum:\n\t\treturn Summator{}\n\tcase Subtraction:\n\t\treturn Subtractor{}\n\tcase Multiplication:\n\t\treturn Multiplicator{}\n\tcase Division:\n\t\treturn Divisor{}\n\tdefault:\n\t\treturn NotImplemented{}\n\t}\n}", "func (p *Port) Operator() *Operator {\n\treturn p.operator\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o MachineInstanceSpecClassSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MachineInstanceSpecClassSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (p Problem) Operator() rune {\n\treturn p.operator\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o KubernetesClusterSpecClassSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v KubernetesClusterSpecClassSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o *AddOn) GetOperatorName() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&4096 != 0\n\tif ok {\n\t\tvalue = o.operatorName\n\t}\n\treturn\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FunctionEventTriggerEventFilterOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FunctionEventTriggerEventFilter) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (c *FakeExampleOperators) Get(name string, options v1.GetOptions) (result *v1alpha1.ExampleOperator, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewGetAction(exampleoperatorsResource, c.ns, name), &v1alpha1.ExampleOperator{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.ExampleOperator), err\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingTolerationsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingTolerations) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SchedulingNodeAffinityResponseOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SchedulingNodeAffinityResponse) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o StorageClusterSpecNodesSelectorLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecNodesSelectorLabelSelectorMatchExpressions) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (r *Requirement) Operator() selection.Operator {\n\treturn r.operator\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (factory *Factory) GetOperatorImage() string {\n\treturn prependRegistry(factory.options.registry, factory.options.operatorImage)\n}", "func (o ArgoCDExportSpecStoragePvcSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ArgoCDExportSpecStoragePvcSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (p *Lexer) Operator() (string, bool) {\n\n\tvar buf []byte\n\n\tfor {\n\t\tc, _ := p.Byte()\n\t\tif !isOperatorChar(c) {\n\t\t\tbreak\n\t\t}\n\t\tbuf = append(buf, c)\n\t}\n\n\tp.UnreadByte()\n\treturn string(buf), len(buf) > 0\n}", "func (o DrillSpecPodConfigPodSchedulingTolerationsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingTolerations) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingTolerationsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingTolerations) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func Operator() error {\n\tif err := sh.RunV(\"mage\", \"-d\", \"operator\", \"all\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetOperatorType() OperatorType {\n\t// Assuming that if Gopkg.toml exists then this is a Go operator\n\t_, err := os.Stat(gopkgToml)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn OperatorTypeAnsible\n\t}\n\treturn OperatorTypeGo\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingTolerationsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingTolerations) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (w *Where) GetOp() string {\n\tif w.Op == \"\" {\n\t\treturn \"=\"\n\t}\n\treturn w.Op\n}" ]
[ "0.80829227", "0.7646545", "0.7586884", "0.7536287", "0.74493635", "0.72114533", "0.71136105", "0.711027", "0.71038866", "0.7087019", "0.7086355", "0.7079433", "0.7075816", "0.7069984", "0.70697856", "0.7065881", "0.70624244", "0.7060574", "0.7048873", "0.70485675", "0.7043922", "0.7039419", "0.70375115", "0.70374525", "0.70328355", "0.70176107", "0.7006038", "0.7003932", "0.700192", "0.70011914", "0.69963783", "0.6983373", "0.69832116", "0.6978216", "0.69755155", "0.6973878", "0.69725025", "0.696612", "0.6964744", "0.6964277", "0.6960669", "0.6955812", "0.69547963", "0.6950078", "0.6949599", "0.6949462", "0.69406646", "0.6940203", "0.6922604", "0.69199115", "0.6915758", "0.6914833", "0.69110763", "0.6908991", "0.6906514", "0.6904724", "0.6903985", "0.68990606", "0.6894225", "0.6891896", "0.6889567", "0.6874863", "0.6872072", "0.6871663", "0.6864557", "0.68629456", "0.68525934", "0.68465674", "0.68419045", "0.6836122", "0.6834363", "0.6829926", "0.68261176", "0.6823787", "0.6813584", "0.68089324", "0.68016094", "0.67917174", "0.6789328", "0.67809623", "0.67790294", "0.67689437", "0.6757078", "0.6753222", "0.6748965", "0.6746891", "0.6741305", "0.6737545", "0.67375374", "0.6736447", "0.6734098", "0.67300946", "0.6687791", "0.66804445", "0.6679834", "0.6669281", "0.6648457", "0.6647858", "0.66263604", "0.66263527" ]
0.7549911
3
GetValueName gets the valueName property value. The registry value name
func (m *Win32LobAppRegistryDetection) GetValueName()(*string) { val, err := m.GetBackingStore().Get("valueName") if err != nil { panic(err) } if val != nil { return val.(*string) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) GetValueName()(*string) {\n return m.valueName\n}", "func (m *RegistryKeyState) GetValueName()(*string) {\n return m.valueName\n}", "func (p ByName) ValueName() string { return p.valueName }", "func (m *Win32LobAppRegistryRule) SetValueName(value *string)() {\n m.valueName = value\n}", "func (s *Identity) GetValue(name string) *Identity {\n\tfor _, v := range s.Values {\n\t\tif v.Name == name {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func (getEnvPropertyValueFn) Name() string {\n\treturn \"getEnvPropertyValue\"\n}", "func (m *RegistryKeyState) SetValueName(value *string)() {\n m.valueName = value\n}", "func (g *GaugeRegressHandler) GetName() string {\n\treturn g.name\n}", "func (r *Record) Get(name string) (Value, bool) {\n\tvalue, ok := r.nameValueMap[name]\n\treturn value, ok\n}", "func getResourceNameByValue(value interface{}) string {\n\t// assume it's ResourceNamer -- get resource name\n\tif inter, ok := value.(admin.ResourceNamer); value != nil && ok {\n\t\treturn inter.ResourceName()\n\t}\n\n\t// last resort: raw struct name\n\treturn reflect.Indirect(reflect.ValueOf(value)).Type().String()\n}", "func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() {\n err := m.GetBackingStore().Set(\"valueName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (t *Target) GetValue(name string) string {\n\treturn t.labels.Get(name)\n}", "func (reg *Registry) GetName() string {\n\treturn reg.apiRegistry.GetName()\n}", "func (m *DeviceManagementConfigurationSettingDefinition) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (s *Section) GetValue(name string) (string, bool) {\n\tfor _, e := range s.Entries {\n\t\tif e.Key == name {\n\t\t\treturn e.Value, true\n\t\t}\n\t}\n\treturn \"\", false\n}", "func (m *PolicyRule) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (e *EnumDescriptor) GetNamedValue(name string) *EnumValueDescriptor {\n\tfor _, v := range e.GetValues() {\n\t\tif v.GetName() == name {\n\t\t\treturn v\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *CalendarGroup) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *RegistryKeyState) GetOldValueName()(*string) {\n return m.oldValueName\n}", "func (m *DeviceManagementConfigurationPolicy) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (r *Resultset) GetValueByName(row int, name string) (interface{}, error) {\n\tcolumn, err := r.NameIndex(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.GetValue(row, column)\n}", "func getNameRegEntry(t *testing.T, client client.RPCClient, name string) *core_types.NameRegEntry {\n\tentry, err := edbcli.GetName(client, name)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn entry\n}", "func (c *Config) GetValue(section, name string) string {\n\tc.ReadList()\n\tconf := c.ReadList()\n\tfor _, v := range conf {\n\t\tfor key, value := range v {\n\t\t\tif key == section {\n\t\t\t\treturn value[name]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"no value\"\n}", "func GetValue(name string) (value interface{}, exists bool) {\n\tif log.RootLogger().TraceEnabled() {\n\t\tlog.RootLogger().Tracef(\"Getting App Value '%s': %v\", name)\n\t}\n\treturn appData.GetValue(name)\n}", "func (request *DomainRegisterRequest) GetName() *string {\n\treturn request.GetStringProperty(\"Name\")\n}", "func (v Value) Name() (string, error) {\n\tif v.typ != Name {\n\t\treturn \"\", v.newError(\"%s is not an object name\", v.Raw())\n\t}\n\treturn v.str, nil\n}", "func ValueName(vName string) OptFunc {\n\treturn func(p *ByName) error {\n\t\tif vName == \"\" {\n\t\t\treturn errors.New(\"some non-empty value name must be given\")\n\t\t}\n\t\tp.valueName = vName\n\n\t\treturn nil\n\t}\n}", "func GetVal(k string) string {\n\treturn Get(k).Val\n}", "func (m *ParentLabelDetails) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *WorkbookNamedItem) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *V0037JobProperties) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (o *EnvironmentVariablePair1) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func Value(ctx *bm.Context, name string) (value string, ok bool) {\n\tvalue, ok = ctx.Keys[name].(string)\n\treturn\n}", "func (m *LabelActionBase) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (t *SentryTaggedScalar) GetName() string {\n\treturn t.Name\n}", "func FlagsGetValueByName(flagsClass *FlagsClass, name string) *FlagsValue {\n\tc_flags_class := (*C.GFlagsClass)(C.NULL)\n\tif flagsClass != nil {\n\t\tc_flags_class = (*C.GFlagsClass)(flagsClass.ToC())\n\t}\n\n\tc_name := C.CString(name)\n\tdefer C.free(unsafe.Pointer(c_name))\n\n\tretC := C.g_flags_get_value_by_name(c_flags_class, c_name)\n\tretGo := FlagsValueNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (cfg *Config) Value(name string) string {\n\tv, _ := cfg.findLast(name)\n\treturn string(v)\n}", "func (envUC EnvUsecase) GetName(e domain.Env, pName string, gPrefix *string) string {\n\tif e.Name != nil {\n\t\treturn *e.Name\n\t}\n\treturn strings.ToUpper(fmt.Sprintf(\"%s%s\", envUC.GetPrefix(e, gPrefix), pName))\n}", "func (o *SecurityMonitoringRuleCase) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (t *TemplateNumberParam) GetName() string { return t.Name }", "func (o *ResourceProperties) GetName() *string {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.Name\n\n}", "func (o *AddOn) GetName() (value string, ok bool) {\n\tok = o != nil && o.bitmap_&2048 != 0\n\tif ok {\n\t\tvalue = o.name\n\t}\n\treturn\n}", "func (o *MonitorSearchResult) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func GetValue(req *http.Request, key string) string {\n\tvars.RLock()\n\tvalue := vars.v[req][key]\n\tvars.RUnlock()\n\treturn value\n}", "func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromSecretKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (o *WebhooksIntegrationCustomVariableResponse) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn o.Name\n}", "func (o *Object) Get(name string) Value {\n\treturn o.self.getStr(unistring.NewFromString(name), nil)\n}", "func (o *CustomFilterChartSeriesDimensionConfig) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (m *KeyValue) GetValue()(*string) {\n return m.value\n}", "func (t EventType) GetName() string {\n\treturn C.GoString((*C.char)(C.gst_event_type_get_name(C.GstEventType(t))))\n}", "func (arg1 *UConverter) GetName(arg2 *UErrorCode) string", "func (p stringProperty) Name() string {\n\treturn p.name\n}", "func (t *TemplateEnumParam) GetName() string { return t.Name }", "func (r *reflex) valueByName(value reflect.Value, name string) any {\n\tif fieldValue := value.FieldByName(name); !fieldValue.IsNil() {\n\t\treturn fieldValue.Elem().Interface()\n\t}\n\treturn nil\n}", "func (scanner *Scanner) GetName() string {\n\treturn scanner.config.Name\n}", "func (o *BackupUnitProperties) GetName() *string {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.Name\n\n}", "func (config *Config) GetValue(label string) string {\n\tvar value, _ = config.GetString(label)\n\treturn config.replaceHome(value)\n}", "func (e *EnumEntry) GetName() string { return e.Name }", "func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (s MpuSensor) GetName() string {\n\treturn \"Ac-Mg-Gy\"\n}", "func (c *CustomCondition) GetName() string {\n\treturn c.name\n}", "func (o RegistryTaskTimerTriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskTimerTrigger) string { return v.Name }).(pulumi.StringOutput)\n}", "func (rp *ResourceProperty) Name() string {\n\treturn rp.PropertyName\n}", "func (e *EMeter) GetName() string {\n\treturn \"properties\"\n}", "func (o IndexingConfigurationThingGroupIndexingConfigurationCustomFieldOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IndexingConfigurationThingGroupIndexingConfigurationCustomField) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func getFieldValue(e reflect.Value, name string) interface{} {\n\tswitch e.Kind() {\n\tcase reflect.Ptr:\n\t\telem := e.Elem()\n\t\treturn getFieldValue(elem, name)\n\tcase reflect.Struct:\n\t\tf := e.FieldByName(strings.Title(name))\n\t\tif f.IsValid() {\n\t\t\treturn f.Interface()\n\t\t}\n\tcase reflect.Map:\n\t\tm, _ := e.Interface().(map[string]interface{})\n\t\treturn m[name]\n\t}\n\treturn nil\n}", "func (m *DeviceCompliancePolicySettingStateSummary) GetSettingName()(*string) {\n val, err := m.GetBackingStore().Get(\"settingName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (mon *Monitor) GetName() string {\n\treturn C.GoString(C.glfwGetMonitorName(mon.internalPtr))\n}", "func (o *LabelProperties) GetValue() *string {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.Value\n\n}", "func (t *Link) GetNameString(index int) (v string) {\n\treturn *t.name[index].stringName\n\n}", "func (s *Service) GetName(ctx context.Context) (string, error) {\n\treturn s.getStringProperty(ctx, shillconst.ServicePropertyName)\n}", "func (o *SiteAllOfNameResolutionGcpResolvers) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (p *Property) GetName() string {\n\treturn \"properties\"\n}", "func (d DocLanguageHelper) GetPropertyName(p *schema.Property) (string, error) {\n\treturn PyName(p.Name), nil\n}", "func (m *AgedAccountsPayable) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func ( b *binIoRoundtripTestBuilder ) getVal( nm string ) interface{} {\n if val, ok := b.nmCheck[ nm ]; ok { return val }\n panic( libErrorf( \"valMap[ %q ]: no value\", nm ) )\n}", "func (m *Device) GetName() (val string, set bool) {\n\tif m.Name == nil {\n\t\treturn\n\t}\n\n\treturn *m.Name, true\n}", "func (c *Configuration) Get(name string) (string, error) {\n\tv, ok := c.data[name].(string)\n\tif !ok {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"no existe el campo %s o no se puede convertir en string\", name))\n\t}\n\n\treturn v, nil\n}", "func (o VirtualDatabaseSpecEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (recv *ParamSpec) GetName() string {\n\tretC := C.g_param_spec_get_name((*C.GParamSpec)(recv.native))\n\tretGo := C.GoString(retC)\n\n\treturn retGo\n}", "func (o IndexingConfigurationThingIndexingConfigurationCustomFieldOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IndexingConfigurationThingIndexingConfigurationCustomField) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (d *V8interceptor) GetByname(name string, object *V8value, retval **V8value, exception *string) int32 {\n\tname_ := C.cef_string_userfree_alloc()\n\tsetCEFStr(name, name_)\n\tdefer func() {\n\t\tC.cef_string_userfree_free(name_)\n\t}()\n\tretval_ := (*retval).toNative()\n\texception_ := C.cef_string_userfree_alloc()\n\tsetCEFStr(*exception, exception_)\n\tdefer func() {\n\t\t*exception = cefstrToString(exception_)\n\t\tC.cef_string_userfree_free(exception_)\n\t}()\n\treturn int32(C.gocef_v8interceptor_get_byname(d.toNative(), (*C.cef_string_t)(name_), object.toNative(), &retval_, (*C.cef_string_t)(exception_), d.get_byname))\n}", "func (p *Plugin) GetVariable(name string) (value string) {\n\tsymVal, err := p.plug.Lookup(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tvaluepointer, ok := symVal.(*string)\n\tif !ok {\n\t\tlog.Fatal(\"Could not cast value of variable \", name)\n\t}\n\n\treturn *valuepointer\n}", "func (o *ResourceEntry) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (o VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRefOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuildEnvValueFromConfigMapKeyRef) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func GetName(node *yaml.RNode, path string) string {\n\treturn GetStringField(node, path, \"metadata\", \"name\")\n}", "func (instance *cache) GetName() string {\n\treturn instance.name.Load().(string)\n}", "func EnumGetValueByName(enumClass *EnumClass, name string) *EnumValue {\n\tc_enum_class := (*C.GEnumClass)(C.NULL)\n\tif enumClass != nil {\n\t\tc_enum_class = (*C.GEnumClass)(enumClass.ToC())\n\t}\n\n\tc_name := C.CString(name)\n\tdefer C.free(unsafe.Pointer(c_name))\n\n\tretC := C.g_enum_get_value_by_name(c_enum_class, c_name)\n\tretGo := EnumValueNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (s *StickerSet) GetName() (value string) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Name\n}", "func (t *TemplateTypeParam) GetName() string { return t.Name }", "func (o *LogsPipelineProcessor) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (monitor *Monitor) GetName() string {\n\treturn C.GoString(C.glfwGetMonitorName(monitor.c()))\n}", "func (c *SQLConfigMapSpec) GetName() string {\n\tsuffix := fmt.Sprintf(\"sql-%s\", c.Database)\n\treturn util.PrefixConfigmap(c.qserv, suffix)\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (m *Option) GetName() (val string, set bool) {\n\tif m.Name == nil {\n\t\treturn\n\t}\n\n\treturn *m.Name, true\n}", "func (o *StorageSasExpander) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (r *RegInterface) Get(name string) string {\n\treturn r.replaceMethod[name]\n}", "func (e *Entry) GetName() string {\n\tif len(e.NameRaw) > 0 {\n\t\treturn string(e.NameRaw)\n\t}\n\treturn e.Name\n}", "func GetValue(termName, language string) string {\n\tif language != \"\" { // If a language is defined\n\t\tlanguage = Sanitize(language) // Ensure it is sanitized\n\t} else { // If a language is not defined\n\t\tlanguage = Config.DefaultLanguage // Set to Default Language\n\t}\n\n\tSetTerm(termName) // Automatically set the term if it doesn't exist already\n\tvalue, exists := Config.Terms[termName][language] // Get the language value of this term in Terms\n\n\tif !exists { // If the language key/val does not exist\n\t\tvalue = \"Term \" + termName + \" is not translated into \" + language\n\t}\n\n\treturn value\n}", "func (c ValueColumn) Name() string {\n\treturn c.name\n}" ]
[ "0.7900741", "0.7671747", "0.66240984", "0.65626806", "0.6345081", "0.6202632", "0.6187288", "0.61499274", "0.61246884", "0.60892904", "0.60507566", "0.6003135", "0.5918145", "0.59086007", "0.5907154", "0.58331186", "0.5813495", "0.5791507", "0.5772751", "0.57622325", "0.57222074", "0.56745285", "0.5646473", "0.56377906", "0.5626308", "0.5624486", "0.5616972", "0.5598688", "0.5565005", "0.5564055", "0.5550715", "0.55389667", "0.5535364", "0.55264777", "0.5525827", "0.551551", "0.5511688", "0.55087906", "0.5506487", "0.5495946", "0.5490156", "0.5475244", "0.54714525", "0.5471156", "0.5467479", "0.544705", "0.5436483", "0.5436216", "0.5430546", "0.54293627", "0.5425344", "0.5423672", "0.542109", "0.5420379", "0.5404093", "0.5402765", "0.53972274", "0.5394024", "0.5385353", "0.5382504", "0.53757226", "0.53649837", "0.5360284", "0.53600514", "0.53542954", "0.5341417", "0.5341312", "0.5336787", "0.53359354", "0.5335007", "0.5331375", "0.53246075", "0.5323238", "0.531472", "0.5312121", "0.53087044", "0.5305936", "0.5292573", "0.52920157", "0.5283611", "0.52731967", "0.52599454", "0.5257669", "0.5251867", "0.5250746", "0.5246921", "0.5238325", "0.52360183", "0.5234469", "0.5223772", "0.5217276", "0.52171165", "0.52163464", "0.5209738", "0.52069634", "0.5206328", "0.5198807", "0.5197145", "0.5196287", "0.51942843" ]
0.7951308
0
Serialize serializes information the current object
func (m *Win32LobAppRegistryDetection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Win32LobAppDetection.Serialize(writer) if err != nil { return err } { err = writer.WriteBoolValue("check32BitOn64System", m.GetCheck32BitOn64System()) if err != nil { return err } } if m.GetDetectionType() != nil { cast := (*m.GetDetectionType()).String() err = writer.WriteStringValue("detectionType", &cast) if err != nil { return err } } { err = writer.WriteStringValue("detectionValue", m.GetDetectionValue()) if err != nil { return err } } { err = writer.WriteStringValue("keyPath", m.GetKeyPath()) if err != nil { return err } } if m.GetOperator() != nil { cast := (*m.GetOperator()).String() err = writer.WriteStringValue("operator", &cast) if err != nil { return err } } { err = writer.WriteStringValue("valueName", m.GetValueName()) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p Registered) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"ID\": p.ID,\n\t\t\"Date\": p.Date,\n\t\t\"Riders\": p.Riders,\n\t\t\"RidersID\": p.RidersID,\n\t\t\"Events\": p.Events,\n\t\t\"EventsID\": p.EventsID,\n\t\t\"StartNumber\": p.StartNumber,\n\t}\n}", "func (m *IncomingContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"observedParticipantId\", m.GetObservedParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"onBehalfOf\", m.GetOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"sourceParticipantId\", m.GetSourceParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"transferor\", m.GetTransferor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *LabelActionBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"name\", m.GetName())\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.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *Uniform) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"uniform selection\"\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (m *ParentLabelDetails) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"color\", m.GetColor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"id\", m.GetId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteBoolValue(\"isActive\", m.GetIsActive())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"name\", m.GetName())\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(\"parent\", m.GetParent())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"sensitivity\", m.GetSensitivity())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tooltip\", m.GetTooltip())\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 Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (s *State) Serialize() []byte {\n\treturn s.serializer.Serialize(s.structure())\n}", "func (r *SbProxy) Serialize() rotator.Object {\n\tr.RLock()\n\tdefer r.RUnlock()\n\treturn r.serialize()\n}", "func (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (this *Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(this)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (e *SetTempoEvent) Serialize() []byte {\n\tbs := []byte{}\n\tbs = append(bs, constant.Meta, constant.SetTempo)\n\tbs = append(bs, 0x03)\n\tbs = append(bs, byte(e.tempo>>16))\n\tbs = append(bs, byte((0xff00&e.tempo)>>8))\n\tbs = append(bs, byte(e.tempo&0xff))\n\n\treturn bs\n}", "func (b *AnnealingEpsilonGreedy) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"annealing epsilon greedy\"\n\tdata[\"epsilon\"] = b.Epsilon()\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (e *Entity) Serialize(w io.Writer) error {\n\terr := e.PrimaryKey.Serialize(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, ident := range e.Identities {\n\t\terr = ident.UserId.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = ident.SelfSignature.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, sig := range ident.Signatures {\n\t\t\terr = sig.Serialize(w)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, subkey := range e.Subkeys {\n\t\terr = subkey.PublicKey.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = subkey.Sig.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f *feature) Serialize() string {\n\tstream, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(stream)\n}", "func (m *BookingNamedEntity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *EpsilonGreedy) Serialize() interface{} {\n\tdata := make(map[string]interface{})\n\tdata[\"strategy\"] = \"epsilon greedy\"\n\tdata[\"epsilon\"] = b.Epsilon\n\tdata[\"counts\"] = b.counts\n\tdata[\"values\"] = b.values\n\treturn data\n}", "func (m *IdentityProviderBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (n Name) Serialize() []byte {\n\tnameData := make([]byte, 0, len(n)+5)\n\tfor _, label := range n.getLabels() {\n\t\tnameData = append(nameData, encodeLabel(label)...)\n\t}\n\t//terminate labels\n\tnameData = append(nameData, byte(0))\n\n\treturn nameData\n}", "func (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (JSONPresenter) Serialize(object interface{}) []byte {\n\tserial, err := json.Marshal(object)\n\n\tif err != nil {\n\t\tlog.Printf(\"failed to serialize: \\\"%s\\\"\", err)\n\t}\n\n\treturn serial\n}", "func (m *NamedLocation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"modifiedDateTime\", m.GetModifiedDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *BundleIdent) Serialize(buffer []byte) []byte {\n\tbuffer = serializeString(b.App, buffer)\n\tbuffer = b.User.Serialize(buffer)\n\tbuffer = serializeString(b.Name, buffer)\n\tbuffer = serializeString(b.Incarnation, buffer)\n\treturn buffer\n}", "func (m *ExternalConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"configuration\", m.GetConfiguration())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", 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.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schema\", m.GetSchema())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *EventMessageDetail) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\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 (out *TransactionOutput) Serialize(bw *io.BinaryWriter) {\n\tbw.WriteLE(out.AssetId)\n\tbw.WriteLE(out.Value)\n\tbw.WriteLE(out.ScriptHash)\n}", "func (in *Store) Serialize() ([]byte, error) {\n\treturn proto.Marshal(in.ToProto())\n}", "func (ds *DepositToStake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(ds.Proto()))\n}", "func Serialize(v interface{}) ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tif err := gob.NewEncoder(buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (writer *Writer) Serialize(v interface{}) {\n\tif v == nil {\n\t\twriter.WriteNil()\n\t} else {\n\t\tv := reflect.ValueOf(v)\n\t\tvalueEncoders[v.Kind()](writer, v)\n\t}\n}", "func (sh *ServerPropertiesHandle) Serialized() string {\n\tsh.Serialize(sh.serverProperties)\n\treturn sh.String()\n}", "func (sigInfo *TxSignature) Serialize() []byte {\n\tecSig := sigInfo.Signature.Serialize()\n\tecSig = append(ecSig, byte(int(sigInfo.HashType)))\n\treturn ecSig\n}", "func (o *A_2) Serialize(\r\n\tbyteOrder binary.ByteOrder,\r\n\tstream io.Writer,\r\n) error {\r\n\t//TODO: implement\r\n\t/*\r\n\t\tif err := o.cursor.Serialize(byteOrder, stream); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\t\tif err := o.limit.Serialize(byteOrder, stream); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t*/\r\n\treturn fmt.Errorf(\"not yet implemented\")\r\n}", "func (f *PushNotice) Serialize(buffer []byte) []byte {\n\tbuffer[0] = byte(f.Flags)\n\tcopy(buffer[1:], f.Data)\n\treturn buffer\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tthis.s(root)\n\treturn \"[\" + strings.Join(this.data, \",\") + \"]\"\n}", "func (acc *Account) Serialize() ([]byte, error) {\n\treturn json.Marshal(acc)\n}", "func (m *saMap) serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (m *ServicePlanInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"appliesTo\", m.GetAppliesTo())\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(\"provisioningStatus\", m.GetProvisioningStatus())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"servicePlanId\", m.GetServicePlanId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"servicePlanName\", m.GetServicePlanName())\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 (f *CloseNotice) Serialize(buffer []byte) []byte {\n\treturn buffer\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (l *Layer) Serialize() ([]byte, error) {\n\treturn json.Marshal(l)\n}", "func (n *Norm) Serialize() ([]byte, error) {\n\tweightsData, err := json.Marshal(n.Weights)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmagsData, err := json.Marshal(n.Mags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn serializer.SerializeAny(\n\t\tserializer.Bytes(weightsData),\n\t\tserializer.Bytes(magsData),\n\t\tn.Creator,\n\t)\n}", "func (team *Team) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"id\": team.ID,\n\t\t\"name\": team.Name,\n\t\t\"description\": team.Description,\n\t\t\"level\": team.Level,\n\t\t\"code\": team.Code,\n\t\t\"city_id\": team.CityID,\n\t\t\"ward_id\": team.WardID,\n\t\t\"district_id\": team.DistrictID,\n\t\t\"since\": team.Since,\n\t\t\"address\": team.Address,\n\t\t\"web\": team.Web,\n\t\t\"facebook_id\": team.FacebookID,\n\t\t\"cover\": team.Cover,\n\t\t\"lng\": team.Lng,\n\t\t\"lat\": team.Lat,\n\t\t\"user\": team.User.Serialize(),\n\t}\n}", "func (s *StoredChannel) serialize() ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tencoder := gob.NewEncoder(buffer)\n\terr := encoder.Encode(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (m *ExternalActivity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"performedBy\", m.GetPerformedBy())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"startDateTime\", m.GetStartDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetTypeEscaped() != nil {\n cast := (*m.GetTypeEscaped()).String()\n err = writer.WriteStringValue(\"type\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *UserSimulationEventInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"browser\", m.GetBrowser())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteTimeValue(\"eventDateTime\", m.GetEventDateTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventName\", m.GetEventName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"ipAddress\", m.GetIpAddress())\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(\"osPlatformDeviceDetails\", m.GetOsPlatformDeviceDetails())\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 (m *OnlineMeetingInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"conferenceId\", m.GetConferenceId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"joinUrl\", m.GetJoinUrl())\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 if m.GetPhones() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPhones()))\n for i, v := range m.GetPhones() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"phones\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"quickDial\", m.GetQuickDial())\n if err != nil {\n return err\n }\n }\n if m.GetTollFreeNumbers() != nil {\n err := writer.WriteCollectionOfStringValues(\"tollFreeNumbers\", m.GetTollFreeNumbers())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tollNumber\", m.GetTollNumber())\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 (m *PrintConnector) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"appVersion\", m.GetAppVersion())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"fullyQualifiedDomainName\", m.GetFullyQualifiedDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"location\", m.GetLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"operatingSystem\", m.GetOperatingSystem())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"registeredDateTime\", m.GetRegisteredDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (self X) Serialise(enc *gob.Encoder) error {\n\treturn enc.Encode(self)\n}", "func (d *DeviceInfo) Serialize() (string, error) {\n\tb, err := json.Marshal(d)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\treturn dfsSerial(root, \"\")\n}", "func (m *List) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetColumns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetColumns())\n err = writer.WriteCollectionOfObjectValues(\"columns\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentTypes() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContentTypes())\n err = writer.WriteCollectionOfObjectValues(\"contentTypes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\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 if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\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.GetSubscriptions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSubscriptions())\n err = writer.WriteCollectionOfObjectValues(\"subscriptions\", 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 (c *CheckboxBase) Serialize(e page.Encoder) {\n\tc.ControlBase.Serialize(e)\n\n\tif err := e.Encode(c.checked); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := e.Encode(c.LabelMode); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := e.Encode(c.labelAttributes); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (p statisticsActionProps) serialize() actionlog.Meta {\n\tvar (\n\t\tm = make(actionlog.Meta)\n\t)\n\n\treturn m\n}", "func (st Account) Serialize() ([]byte, error) {\n\treturn proto.Marshal(st.ToProto())\n}", "func (st Account) Serialize() ([]byte, error) {\n\treturn proto.Marshal(st.ToProto())\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func (m *KeyValue) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"key\", m.GetKey())\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(\"value\", m.GetValue())\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 (m *User) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"aboutMe\", m.GetAboutMe())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"accountEnabled\", m.GetAccountEnabled())\n if err != nil {\n return err\n }\n }\n if m.GetActivities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetActivities())\n err = writer.WriteCollectionOfObjectValues(\"activities\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"ageGroup\", m.GetAgeGroup())\n if err != nil {\n return err\n }\n }\n if m.GetAgreementAcceptances() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAgreementAcceptances())\n err = writer.WriteCollectionOfObjectValues(\"agreementAcceptances\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAppRoleAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoleAssignments())\n err = writer.WriteCollectionOfObjectValues(\"appRoleAssignments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedLicenses() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLicenses())\n err = writer.WriteCollectionOfObjectValues(\"assignedLicenses\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedPlans())\n err = writer.WriteCollectionOfObjectValues(\"assignedPlans\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authentication\", m.GetAuthentication())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authorizationInfo\", m.GetAuthorizationInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"birthday\", m.GetBirthday())\n if err != nil {\n return err\n }\n }\n if m.GetBusinessPhones() != nil {\n err = writer.WriteCollectionOfStringValues(\"businessPhones\", m.GetBusinessPhones())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"calendar\", m.GetCalendar())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarGroups())\n err = writer.WriteCollectionOfObjectValues(\"calendarGroups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendars() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendars())\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarView())\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetChats() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetChats())\n err = writer.WriteCollectionOfObjectValues(\"chats\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"city\", m.GetCity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"companyName\", m.GetCompanyName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"consentProvidedForMinor\", m.GetConsentProvidedForMinor())\n if err != nil {\n return err\n }\n }\n if m.GetContactFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContactFolders())\n err = writer.WriteCollectionOfObjectValues(\"contactFolders\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContacts() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContacts())\n err = writer.WriteCollectionOfObjectValues(\"contacts\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"country\", m.GetCountry())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetCreatedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCreatedObjects())\n err = writer.WriteCollectionOfObjectValues(\"createdObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"creationType\", m.GetCreationType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"department\", m.GetDepartment())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"deviceEnrollmentLimit\", m.GetDeviceEnrollmentLimit())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceManagementTroubleshootingEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDeviceManagementTroubleshootingEvents())\n err = writer.WriteCollectionOfObjectValues(\"deviceManagementTroubleshootingEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDirectReports() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDirectReports())\n err = writer.WriteCollectionOfObjectValues(\"directReports\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetDrives() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDrives())\n err = writer.WriteCollectionOfObjectValues(\"drives\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"employeeHireDate\", m.GetEmployeeHireDate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeId\", m.GetEmployeeId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"employeeOrgData\", m.GetEmployeeOrgData())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeType\", m.GetEmployeeType())\n if err != nil {\n return err\n }\n }\n if m.GetEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetEvents())\n err = writer.WriteCollectionOfObjectValues(\"events\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExtensions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensions())\n err = writer.WriteCollectionOfObjectValues(\"extensions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"externalUserState\", m.GetExternalUserState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"externalUserStateChangeDateTime\", m.GetExternalUserStateChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"faxNumber\", m.GetFaxNumber())\n if err != nil {\n return err\n }\n }\n if m.GetFollowedSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowedSites())\n err = writer.WriteCollectionOfObjectValues(\"followedSites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"givenName\", m.GetGivenName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"hireDate\", m.GetHireDate())\n if err != nil {\n return err\n }\n }\n if m.GetIdentities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIdentities())\n err = writer.WriteCollectionOfObjectValues(\"identities\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"imAddresses\", m.GetImAddresses())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"inferenceClassification\", m.GetInferenceClassification())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"insights\", m.GetInsights())\n if err != nil {\n return err\n }\n }\n if m.GetInterests() != nil {\n err = writer.WriteCollectionOfStringValues(\"interests\", m.GetInterests())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isResourceAccount\", m.GetIsResourceAccount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"jobTitle\", m.GetJobTitle())\n if err != nil {\n return err\n }\n }\n if m.GetJoinedTeams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetJoinedTeams())\n err = writer.WriteCollectionOfObjectValues(\"joinedTeams\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastPasswordChangeDateTime\", m.GetLastPasswordChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"legalAgeGroupClassification\", m.GetLegalAgeGroupClassification())\n if err != nil {\n return err\n }\n }\n if m.GetLicenseAssignmentStates() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseAssignmentStates())\n err = writer.WriteCollectionOfObjectValues(\"licenseAssignmentStates\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseDetails() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseDetails())\n err = writer.WriteCollectionOfObjectValues(\"licenseDetails\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mail\", m.GetMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"mailboxSettings\", m.GetMailboxSettings())\n if err != nil {\n return err\n }\n }\n if m.GetMailFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMailFolders())\n err = writer.WriteCollectionOfObjectValues(\"mailFolders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mailNickname\", m.GetMailNickname())\n if err != nil {\n return err\n }\n }\n if m.GetManagedAppRegistrations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedAppRegistrations())\n err = writer.WriteCollectionOfObjectValues(\"managedAppRegistrations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetManagedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedDevices())\n err = writer.WriteCollectionOfObjectValues(\"managedDevices\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"manager\", m.GetManager())\n if err != nil {\n return err\n }\n }\n if m.GetMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"memberOf\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessages() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMessages())\n err = writer.WriteCollectionOfObjectValues(\"messages\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mobilePhone\", m.GetMobilePhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mySite\", m.GetMySite())\n if err != nil {\n return err\n }\n }\n if m.GetOauth2PermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOauth2PermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"oauth2PermissionGrants\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"officeLocation\", m.GetOfficeLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onenote\", m.GetOnenote())\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnlineMeetings())\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDistinguishedName\", m.GetOnPremisesDistinguishedName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremisesExtensionAttributes\", m.GetOnPremisesExtensionAttributes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesImmutableId\", m.GetOnPremisesImmutableId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"onPremisesLastSyncDateTime\", m.GetOnPremisesLastSyncDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesProvisioningErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnPremisesProvisioningErrors())\n err = writer.WriteCollectionOfObjectValues(\"onPremisesProvisioningErrors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSamAccountName\", m.GetOnPremisesSamAccountName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSecurityIdentifier\", m.GetOnPremisesSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"onPremisesSyncEnabled\", m.GetOnPremisesSyncEnabled())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesUserPrincipalName\", m.GetOnPremisesUserPrincipalName())\n if err != nil {\n return err\n }\n }\n if m.GetOtherMails() != nil {\n err = writer.WriteCollectionOfStringValues(\"otherMails\", m.GetOtherMails())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"outlook\", m.GetOutlook())\n if err != nil {\n return err\n }\n }\n if m.GetOwnedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedDevices())\n err = writer.WriteCollectionOfObjectValues(\"ownedDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOwnedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedObjects())\n err = writer.WriteCollectionOfObjectValues(\"ownedObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"passwordPolicies\", m.GetPasswordPolicies())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"passwordProfile\", m.GetPasswordProfile())\n if err != nil {\n return err\n }\n }\n if m.GetPastProjects() != nil {\n err = writer.WriteCollectionOfStringValues(\"pastProjects\", m.GetPastProjects())\n if err != nil {\n return err\n }\n }\n if m.GetPeople() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPeople())\n err = writer.WriteCollectionOfObjectValues(\"people\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"photo\", m.GetPhoto())\n if err != nil {\n return err\n }\n }\n if m.GetPhotos() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPhotos())\n err = writer.WriteCollectionOfObjectValues(\"photos\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"planner\", m.GetPlanner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"postalCode\", m.GetPostalCode())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredDataLocation\", m.GetPreferredDataLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredLanguage\", m.GetPreferredLanguage())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredName\", m.GetPreferredName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"presence\", m.GetPresence())\n if err != nil {\n return err\n }\n }\n if m.GetProvisionedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProvisionedPlans())\n err = writer.WriteCollectionOfObjectValues(\"provisionedPlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRegisteredDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRegisteredDevices())\n err = writer.WriteCollectionOfObjectValues(\"registeredDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetResponsibilities() != nil {\n err = writer.WriteCollectionOfStringValues(\"responsibilities\", m.GetResponsibilities())\n if err != nil {\n return err\n }\n }\n if m.GetSchools() != nil {\n err = writer.WriteCollectionOfStringValues(\"schools\", m.GetSchools())\n if err != nil {\n return err\n }\n }\n if m.GetScopedRoleMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetScopedRoleMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"scopedRoleMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"securityIdentifier\", m.GetSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"settings\", m.GetSettings())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"showInAddressList\", m.GetShowInAddressList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"signInSessionsValidFromDateTime\", m.GetSignInSessionsValidFromDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetSkills() != nil {\n err = writer.WriteCollectionOfStringValues(\"skills\", m.GetSkills())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"state\", m.GetState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"streetAddress\", m.GetStreetAddress())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"surname\", m.GetSurname())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"teamwork\", m.GetTeamwork())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"todo\", m.GetTodo())\n if err != nil {\n return err\n }\n }\n if m.GetTransitiveMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"usageLocation\", m.GetUsageLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userType\", m.GetUserType())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mu *MuHash) Serialize() *SerializedMuHash {\n\tvar out SerializedMuHash\n\tmu.serializeInner(&out)\n\treturn &out\n}", "func (m *SolutionsRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetBusinessScenarios() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessScenarios()))\n for i, v := range m.GetBusinessScenarios() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"businessScenarios\", 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(\"virtualEvents\", m.GetVirtualEvents())\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 (bo *BlockObject) toJSON(t *thread) string {\n\treturn bo.toString()\n}", "func (m *Vulnerability) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteBoolValue(\"activeExploitsObserved\", m.GetActiveExploitsObserved())\n if err != nil {\n return err\n }\n }\n if m.GetArticles() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetArticles()))\n for i, v := range m.GetArticles() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"articles\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCommonWeaknessEnumerationIds() != nil {\n err = writer.WriteCollectionOfStringValues(\"commonWeaknessEnumerationIds\", m.GetCommonWeaknessEnumerationIds())\n if err != nil {\n return err\n }\n }\n if m.GetComponents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetComponents()))\n for i, v := range m.GetComponents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"components\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss2Summary\", m.GetCvss2Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss3Summary\", m.GetCvss3Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetExploits() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExploits()))\n for i, v := range m.GetExploits() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"exploits\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"exploitsAvailable\", m.GetExploitsAvailable())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasChatter\", m.GetHasChatter())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastModifiedDateTime\", m.GetLastModifiedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"priorityScore\", m.GetPriorityScore())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"publishedDateTime\", m.GetPublishedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetReferences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetReferences()))\n for i, v := range m.GetReferences() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"references\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"remediation\", m.GetRemediation())\n if err != nil {\n return err\n }\n }\n if m.GetSeverity() != nil {\n cast := (*m.GetSeverity()).String()\n err = writer.WriteStringValue(\"severity\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *AuthenticationContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetDetail() != nil {\n cast := (*m.GetDetail()).String()\n err := writer.WriteStringValue(\"detail\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"id\", m.GetId())\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.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *DiscoveredSensitiveType) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetClassificationAttributes() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetClassificationAttributes()))\n for i, v := range m.GetClassificationAttributes() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"classificationAttributes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"confidence\", m.GetConfidence())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"count\", m.GetCount())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteUUIDValue(\"id\", m.GetId())\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.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (e *RegisterRequest) Serialize() (string, error) {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (m *Set) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetChildren() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetChildren()))\n for i, v := range m.GetChildren() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"children\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetLocalizedNames() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetLocalizedNames()))\n for i, v := range m.GetLocalizedNames() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"localizedNames\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentGroup\", m.GetParentGroup())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProperties()))\n for i, v := range m.GetProperties() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetRelations() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetRelations()))\n for i, v := range m.GetRelations() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"relations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTerms() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTerms()))\n for i, v := range m.GetTerms() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"terms\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *InformationProtection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"bitlocker\", m.GetBitlocker())\n if err != nil {\n return err\n }\n }\n if m.GetDataLossPreventionPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDataLossPreventionPolicies()))\n for i, v := range m.GetDataLossPreventionPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dataLossPreventionPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"policy\", m.GetPolicy())\n if err != nil {\n return err\n }\n }\n if m.GetSensitivityLabels() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSensitivityLabels()))\n for i, v := range m.GetSensitivityLabels() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sensitivityLabels\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sensitivityPolicySettings\", m.GetSensitivityPolicySettings())\n if err != nil {\n return err\n }\n }\n if m.GetThreatAssessmentRequests() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetThreatAssessmentRequests()))\n for i, v := range m.GetThreatAssessmentRequests() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"threatAssessmentRequests\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b *binding) serialize() ([]byte, error) {\n\treturn json.Marshal(b)\n}", "func (m *VirtualEndpoint) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAuditEvents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuditEvents()))\n for i, v := range m.GetAuditEvents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"auditEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBulkActions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBulkActions()))\n for i, v := range m.GetBulkActions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"bulkActions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCloudPCs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCloudPCs()))\n for i, v := range m.GetCloudPCs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"cloudPCs\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"crossCloudGovernmentOrganizationMapping\", m.GetCrossCloudGovernmentOrganizationMapping())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeviceImages()))\n for i, v := range m.GetDeviceImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deviceImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExternalPartnerSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExternalPartnerSettings()))\n for i, v := range m.GetExternalPartnerSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"externalPartnerSettings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFrontLineServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFrontLineServicePlans()))\n for i, v := range m.GetFrontLineServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"frontLineServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGalleryImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetGalleryImages()))\n for i, v := range m.GetGalleryImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"galleryImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesConnections() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesConnections()))\n for i, v := range m.GetOnPremisesConnections() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesConnections\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"organizationSettings\", m.GetOrganizationSettings())\n if err != nil {\n return err\n }\n }\n if m.GetProvisioningPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProvisioningPolicies()))\n for i, v := range m.GetProvisioningPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"provisioningPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"reports\", m.GetReports())\n if err != nil {\n return err\n }\n }\n if m.GetServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePlans()))\n for i, v := range m.GetServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSharedUseServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSharedUseServicePlans()))\n for i, v := range m.GetSharedUseServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sharedUseServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSnapshots() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSnapshots()))\n for i, v := range m.GetSnapshots() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"snapshots\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSupportedRegions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSupportedRegions()))\n for i, v := range m.GetSupportedRegions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"supportedRegions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetUserSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserSettings()))\n for i, v := range m.GetUserSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userSettings\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (msg *MsgInv) Serialize(w io.Writer, pver uint32) error {\n\terr := writeCompactSize(w, pver, msg.InvCount())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, inv := range msg.Inventory {\n\t\terr := inv.Serialize(w, pver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *RemoteAssistancePartner) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastConnectionDateTime\", m.GetLastConnectionDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnboardingStatus() != nil {\n cast := (*m.GetOnboardingStatus()).String()\n err = writer.WriteStringValue(\"onboardingStatus\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onboardingUrl\", m.GetOnboardingUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *WorkbookOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"resourceLocation\", m.GetResourceLocation())\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *DeviceLocalCredentialInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCredentials() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCredentials()))\n for i, v := range m.GetCredentials() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"credentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceName\", m.GetDeviceName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastBackupDateTime\", m.GetLastBackupDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"refreshDateTime\", m.GetRefreshDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Synchronization) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetJobs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetJobs()))\n for i, v := range m.GetJobs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"jobs\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSecrets() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSecrets()))\n for i, v := range m.GetSecrets() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"secrets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTemplates() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTemplates()))\n for i, v := range m.GetTemplates() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"templates\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func serialize(toMarshal interface{}) *bytes.Buffer {\n\tjsonStr, _ := json.Marshal(toMarshal)\n\treturn bytes.NewBuffer(jsonStr)\n}", "func (i Int) Serialize() ([]byte, error) {\n\treturn []byte(strconv.Itoa(int(i))), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\ttmp := []string{}\n\ts(root, &tmp)\n\tthis.SerializeStr = strings.Join(tmp, \",\")\n\treturn this.SerializeStr\n}", "func (e *EntityNotFoundError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-001\",\n\t\t\"error\": \"EntityNotFoundError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (f *ProgressNotice) Serialize(buffer []byte) []byte {\n\tbinary.LittleEndian.PutUint64(buffer, f.Offset)\n\tbuffer = f.User.Serialize(buffer[8:])\n\treturn buffer\n}", "func (p ProductSize) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"id\": p.ID,\n\t\t\"product_id\": p.ProductID,\n\t\t\"sku\": p.Sku,\n\t\t\"size\": p.Size,\n\t\t\"created_at\": p.CreatedAt,\n\t\t\"created_by\": p.CreatedAt,\n\t\t\"updated_at\": p.CreatedAt,\n\t\t\"updated_by\": p.CreatedAt,\n\t\t\"deleted_at\": p.CreatedAt,\n\t\t\"deleted_by\": p.CreatedAt,\n\t}\n}", "func (user *User) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"username\": user.Username,\n\t\t\"id\": user.ID,\n\t\t\"uuid\": user.UUID,\n\t}\n}", "func (bm *BlockMeta) Serialize() ([]byte, error) {\n\tpb, err := bm.Proto()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Marshal(pb)\n}", "func (s *Session) Serialize() string {\n\tvar str string\n\n\tfor _, tv := range []*Table{s.Filter, s.Nat, s.Mangle} {\n\t\tstr += fmt.Sprintf(\"*%s\\n\", tv.name)\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tstr += fmt.Sprintf(\":%s %s [0:0]\\n\", cv.name, cv.policy)\n\t\t\t}\n\t\t}\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tif cv.rules != nil {\n\t\t\t\t\tfor _, rv := range cv.rules {\n\t\t\t\t\t\tstr += rv + \"\\n\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstr += fmt.Sprintf(\"COMMIT\\n\")\n\t}\n\n\treturn str\n}", "func (c *Circle) Serialize() interface{} {\n\tcx := int64(math.Round(c.center.x * configs.HashPrecision))\n\tcy := int64(math.Round(c.center.y * configs.HashPrecision))\n\tcr := int64(math.Round(c.r * configs.HashPrecision))\n\treturn (cx*configs.Prime+cy)*configs.Prime + cr\n}", "func Serialize(object interface{}) ([]byte, error) {\n\tserialized, err := json.Marshal(object)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn serialized, nil\n}", "func (m *SAMap) Serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (req *PutRequest) serialize(w proto.Writer, serialVersion int16) (err error) {\n\treturn req.serializeInternal(w, serialVersion, true)\n}", "func (m *ChannelIdentity) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"channelId\", m.GetChannelId())\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(\"teamId\", m.GetTeamId())\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 (m *PrinterCreateOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrintOperation.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"certificate\", m.GetCertificate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"printer\", m.GetPrinter())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *PrinterCreateOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrintOperation.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"certificate\", m.GetCertificate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"printer\", m.GetPrinter())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func Serialize(ctx context.Context, msgType omci.MessageType, request gopacket.SerializableLayer, tid uint16) ([]byte, error) {\n\tomciLayer := &omci.OMCI{\n\t\tTransactionID: tid,\n\t\tMessageType: msgType,\n\t}\n\treturn SerializeOmciLayer(ctx, omciLayer, request)\n}", "func (m *Schema) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"baseType\", m.GetBaseType())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProperties())\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func serialize(src interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(src); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (ts *TagSet) Serialization() []byte {\n\treturn ts.serialization\n}", "func (m *CloudPcConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"healthCheckStatus\", m.GetHealthCheckStatus())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastRefreshedDateTime\", m.GetLastRefreshedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tenantDisplayName\", m.GetTenantDisplayName())\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 return nil\n}", "func (m *BookingBusiness) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"address\", m.GetAddress())\n if err != nil {\n return err\n }\n }\n if m.GetAppointments() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppointments()))\n for i, v := range m.GetAppointments() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"appointments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBusinessHours() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessHours()))\n for i, v := range m.GetBusinessHours() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"businessHours\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"businessType\", m.GetBusinessType())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendarView()))\n for i, v := range m.GetCalendarView() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomers()))\n for i, v := range m.GetCustomers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customers\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomQuestions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomQuestions()))\n for i, v := range m.GetCustomQuestions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customQuestions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultCurrencyIso\", m.GetDefaultCurrencyIso())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"email\", m.GetEmail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"languageTag\", m.GetLanguageTag())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"phone\", m.GetPhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schedulingPolicy\", m.GetSchedulingPolicy())\n if err != nil {\n return err\n }\n }\n if m.GetServices() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServices()))\n for i, v := range m.GetServices() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"services\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetStaffMembers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetStaffMembers()))\n for i, v := range m.GetStaffMembers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"staffMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"webSiteUrl\", m.GetWebSiteUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *EmbeddedSIMActivationCode) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"integratedCircuitCardIdentifier\", m.GetIntegratedCircuitCardIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"matchingIdentifier\", m.GetMatchingIdentifier())\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(\"smdpPlusServerAddress\", m.GetSmdpPlusServerAddress())\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 (w *Writer) Serialize(v interface{}) *Writer {\n\tif v == nil {\n\t\tw.WriteNil()\n\t} else if rv, ok := v.(reflect.Value); ok {\n\t\tw.WriteValue(rv)\n\t} else {\n\t\tw.WriteValue(reflect.ValueOf(v))\n\t}\n\treturn w\n}", "func (record *SessionRecord) Serialize() ([]byte, error) {\n\trs := &protobuf.RecordStructure{}\n\trs.CurrentSession = record.sessionState.SS\n\tfor _, s := range record.PreviousStates {\n\t\trs.PreviousSessions = append(rs.PreviousSessions, s.SS)\n\t}\n\tb, err := proto.Marshal(rs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}" ]
[ "0.6572986", "0.6466613", "0.6435532", "0.63836247", "0.6377068", "0.63716114", "0.6346305", "0.62336147", "0.6171269", "0.6162533", "0.61441034", "0.6142544", "0.6116166", "0.610626", "0.6100351", "0.6082516", "0.6060808", "0.6053123", "0.6039119", "0.60381764", "0.60261023", "0.60039175", "0.59918606", "0.59914076", "0.5974712", "0.5974484", "0.5970634", "0.5952611", "0.5946486", "0.59450865", "0.5940796", "0.59394485", "0.59394366", "0.59377605", "0.5937568", "0.59360915", "0.5931097", "0.5929001", "0.59284574", "0.59035015", "0.59031016", "0.5895243", "0.58752036", "0.58727145", "0.5855991", "0.5854772", "0.585326", "0.58368224", "0.58364624", "0.58350384", "0.5834011", "0.5830749", "0.5812052", "0.58117825", "0.58088374", "0.58088374", "0.5801002", "0.5796614", "0.5796315", "0.5782493", "0.5774934", "0.57711565", "0.57711416", "0.5769109", "0.5768296", "0.57620305", "0.5749026", "0.5744891", "0.57402736", "0.57361037", "0.57326525", "0.5732051", "0.5727444", "0.57250386", "0.57224107", "0.5722387", "0.5717766", "0.57160777", "0.57041603", "0.56997585", "0.5698607", "0.56971216", "0.5697107", "0.5696918", "0.5695454", "0.5685647", "0.56853646", "0.56833076", "0.5671279", "0.56696004", "0.56696004", "0.56692386", "0.5667735", "0.56639826", "0.5662368", "0.5660281", "0.56548345", "0.5651103", "0.56429994", "0.5641443", "0.5641308" ]
0.0
-1
SetCheck32BitOn64System sets the check32BitOn64System property value. A value indicating whether this registry path is for checking 32bit app on 64bit system
func (m *Win32LobAppRegistryDetection) SetCheck32BitOn64System(value *bool)() { err := m.GetBackingStore().Set("check32BitOn64System", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) SetCheck32BitOn64System(value *bool)() {\n m.check32BitOn64System = value\n}", "func (m *Win32LobAppFileSystemDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryRule) GetCheck32BitOn64System()(*bool) {\n return m.check32BitOn64System\n}", "func (m *Win32LobAppRegistryDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (m *Win32LobAppFileSystemDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func Is64BitCPU() bool {\n\treturn strconv.IntSize == 64\n}", "func Xlstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_LSTAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"lstat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func Is64(t *Type) bool", "func PtraceSetRegsMips64le(pid int, regs *PtraceRegsMips64le) error {\r\n\treturn ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))\r\n}", "func TestSet64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestSetN(testN, hm)\n}", "func opUI64Bitshl(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) << ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (ba *BitArray) Add64(bits uint64) {\n\tba.AddVar(bits, 64)\n}", "func (h *ZipDirEntry) isZip64() bool {\n\treturn h.CompressedSize64 >= uint32max || h.UncompressedSize64 >= uint32max\n}", "func SysInt64(name string) int64 {\r\n\treturn converter.StrToInt64(SysString(name))\r\n}", "func PtraceGetRegsMips64le(pid int, regsout *PtraceRegsMips64le) error {\r\n\treturn ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))\r\n}", "func opUI64Bitand(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) & ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func Xfstat64(tls TLS, fildes int32, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_FSTAT64, uintptr(fildes), buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"fstat64(%v, %#x) %v %v\\n\", fildes, buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func Wow64RevertWow64FsRedirection(olValue uintptr) bool {\n\tret1 := syscall3(wow64RevertWow64FsRedirection, 1,\n\t\tolValue,\n\t\t0,\n\t\t0)\n\treturn ret1 != 0\n}", "func Xstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_STAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"stat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}", "func opI64Bitshl(expr *CXExpression, fp int) {\n\toutB0 := int64(ReadI64(fp, expr.Inputs[0]) << uint64(ReadI64(fp, expr.Inputs[1])))\n\tWriteI64(GetOffset_i64(fp, expr.Outputs[0]), outB0)\n}", "func Test386() error {\n\tenv := map[string]string{\"GOARCH\": \"386\", \"GOFLAGS\": testGoFlags()}\n\treturn runCmd(env, goexe, \"test\", \"./...\")\n}", "func mipsOpcode32bit(opc *mipsOpcode) bool {\n\treturn (opc.mask >> 16) != 0\n}", "func Mul64(x, y uint64) (hi, lo uint64) {\n\tconst mask32 = 1<<32 - 1\n\tx0 := x & mask32\n\tx1 := x >> 32\n\ty0 := y & mask32\n\ty1 := y >> 32\n\tw0 := x0 * y0\n\tt := x1*y0 + w0>>32\n\tw1 := t & mask32\n\tw2 := t >> 32\n\tw1 += x0 * y1\n\thi = x1*y1 + w2 + w1>>32\n\tlo = x * y\n\treturn\n}", "func BKDRHash64(str string) uint64 {\n\tlist := []byte(str)\n\tvar seed uint64 = 131 // 31 131 1313 13131 131313 etc..\n\tvar hash uint64 = 0\n\tfor i := 0; i < len(list); i++ {\n\t\thash = hash*seed + uint64(list[i])\n\t}\n\treturn (hash & 0x7FFFFFFFFFFFFFFF)\n}", "func CmpXchg64(v *int64, oldval int64, newval int64) bool {\n\trv := C.__atomic_compare_exchange_8(v, &oldval, newval, 0, C.__ATOMIC_SEQ_CST, C.__ATOMIC_SEQ_CST)\n\treturn rv\n}", "func count64(bitMask []uint64) (result uint64) {\n\n\tfor i := 0; i < len(bitMask); i++ {\n\t\tresult += uint64(bits.OnesCount64(bitMask[i]))\n\t}\n\treturn\n}", "func opI64Bitand(expr *CXExpression, fp int) {\n\toutB0 := ReadI64(fp, expr.Inputs[0]) & ReadI64(fp, expr.Inputs[1])\n\tWriteI64(GetOffset_i64(fp, expr.Outputs[0]), outB0)\n}", "func (b *Bus) Write64(addr mirv.Address, v uint64) error {\n\tblk := b.p\n\tif !blk.contains(addr) {\n\t\tblk = b.find(addr)\n\t}\n\treturn blk.m.Write64(addr-blk.s, v)\n}", "func SetBvInt64Value(model ModelT, t TermT, val int64) int32 {\n\treturn int32(C.yices_model_set_bv_int64(ymodel(model), C.term_t(t), C.int64_t(val)))\n}", "func SetInt64Value(model ModelT, t TermT, val int64) int32 {\n\treturn int32(C.yices_model_set_int64(ymodel(model), C.term_t(t), C.int64_t(val)))\n}", "func PropValNum64(reply *xproto.GetPropertyReply, err error) (int64, error) {\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif reply.Format != 32 {\n\t\treturn 0, fmt.Errorf(\"PropValNum: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\treturn int64(xgb.Get32(reply.Value)), nil\n}", "func (s *State) Write64(h uint64) (err error) {\n\ts.clen += 8\n\ts.tail = append(s.tail, byte(h>>56), byte(h>>48), byte(h>>40), byte(h>>32), byte(h>>24), byte(h>>16), byte(h>>8), byte(h))\n\treturn nil\n}", "func (b *Bus) Read64(addr mirv.Address) (uint64, error) {\n\tblk := b.p\n\tif !blk.contains(addr) {\n\t\tblk = b.find(addr)\n\t}\n\treturn blk.m.Read64(addr - blk.s)\n}", "func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)", "func shift64RightJamming(a uint64, count int16) uint64 {\n\tif count == 0 {\n\t\treturn a\n\t} else if count < 64 {\n\t\treturn a>>count | x1((a<<((-count)&63)) != 0)\n\t} else if a != 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func TestInt64(tst *testing.T) {\n\n\t// Test bool\n\ti, err := StringToInt64(\"187480198367637651\")\n\tbrtesting.AssertEqual(tst, err, nil, \"StringToInt64 failed\")\n\tbrtesting.AssertEqual(tst, i, int64(187480198367637651), \"StringToInt64 failed\")\n\ti, err = StringToInt64(\"go-bedrock\")\n\tbrtesting.AssertNotEqual(tst, err, nil, \"StringToInt64 failed\")\n}", "func CheckLSB(num int) {\n\tif num&1 == 1 {\n\t\tfmt.Printf(\"\\nLSB of %d is set (1)\", num)\n\t} else {\n\t\tfmt.Printf(\"\\nLSB of %d is unset (0)\", num)\n\t}\n}", "func (this *MachO_MachoFlags) DyldLink() (v bool, err error) {\n\tif (this._f_dyldLink) {\n\t\treturn this.dyldLink, nil\n\t}\n\tthis.dyldLink = bool((this.Value & 4) != 0)\n\tthis._f_dyldLink = true\n\treturn this.dyldLink, nil\n}", "func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)", "func MSB64(x uint64) uint64", "func (n *node64s) Match(key uint64, bits int) (*node64, bool) {\n\tif n == nil {\n\t\treturn nil, false\n\t}\n\n\tif bits < 0 {\n\t\tbits = 0\n\t} else if bits > key64BitSize {\n\t\tbits = key64BitSize\n\t}\n\n\tr := n.match(key, uint8(bits))\n\tif r == nil {\n\t\treturn nil, false\n\t}\n\n\treturn r.value, true\n}", "func GetSystemRegistryQuota(pdwQuotaAllowed *DWORD, pdwQuotaUsed *DWORD) bool {\n\tret1 := syscall3(getSystemRegistryQuota, 2,\n\t\tuintptr(unsafe.Pointer(pdwQuotaAllowed)),\n\t\tuintptr(unsafe.Pointer(pdwQuotaUsed)),\n\t\t0)\n\treturn ret1 != 0\n}", "func (v *Value) SetUInt64(val uint64) {\n\tC.g_value_set_uint64(v.Native(), C.guint64(val))\n}", "func hash64(key, mask uint64) uint64 {\n\tkey = (^key + (key << 21)) & mask\n\tkey = key ^ key>>24\n\tkey = ((key + (key << 3)) + (key << 8)) & mask\n\tkey = key ^ key>>14\n\tkey = ((key + (key << 2)) + (key << 4)) & mask\n\tkey = key ^ key>>28\n\tkey = (key + (key << 31)) & mask\n\treturn key\n}", "func Fixed64Pack(value uint64, out []byte) ([]byte, uint32) {\n\n\tout, _ = Fixed32Pack(uint32(value), out)\n\tout, _ = Fixed32Pack(uint32(value>>32), out)\n\n\treturn out, 8\n}", "func TestGetInt64Var(t *testing.T) {\n\tfor _, tt := range getInt64VarFlagTests {\n\t\tt.Run(tt.valueIn, func(t *testing.T) {\n\t\t\tos.Clearenv()\n\n\t\t\tif err := os.Setenv(variableName, tt.valueIn); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tv, err := GetInt64Var(variableName, tt.fallback)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tif v != tt.valueOut {\n\t\t\t\tt.Errorf(\"Variable %s not equal to value '%v'\", variableName, tt.valueOut)\n\t\t\t}\n\t\t})\n\t}\n}", "func CLZ64(in int64) int32 {\n\tin_upper := int32(in >> 32)\n\tif in_upper == 0 {\n\t\treturn 32 + CLZ32(int32(in))\n\t} else {\n\t\t/* Search in the upper 32 bits */\n\t\treturn CLZ32(in_upper)\n\t}\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) CheckLibraryRights(opts *bind.CallOpts, lib common.Address, access_type uint8) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"checkLibraryRights\", lib, access_type)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func LoadInt64(addr *int64) (val int64)", "func ValidateDNS64Fields(c *Config) error {\n\tif c.DNS64.AllowIPv6Use {\n\t\tc.DNS64.AllowAAAAUse = true\n\t}\n\treturn nil\n}", "func BlsmskU64(a uint64) uint64 {\n\tpanic(\"not implemented\")\n}", "func Len64(x uint64) (n int) {\n\tif x >= 1<<32 {\n\t\tx >>= 32\n\t\tn = 32\n\t}\n\tif x >= 1<<16 {\n\t\tx >>= 16\n\t\tn += 16\n\t}\n\tif x >= 1<<8 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\treturn n + int(len8tab[x])\n}", "func Len64(x uint64) (n int) {\n\tif x >= 1<<32 {\n\t\tx >>= 32\n\t\tn = 32\n\t}\n\tif x >= 1<<16 {\n\t\tx >>= 16\n\t\tn += 16\n\t}\n\tif x >= 1<<8 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\treturn n + int(len8tab[x])\n}", "func (r *QuayRegistryReconciler) checkBuildManagerAvailable(\n\tqctx *quaycontext.QuayRegistryContext, bundle *corev1.Secret,\n) error {\n\tvar config map[string]interface{}\n\tif err := yaml.Unmarshal(bundle.Data[\"config.yaml\"], &config); err != nil {\n\t\treturn err\n\t}\n\n\tif buildManagerHostname, ok := config[\"BUILDMAN_HOSTNAME\"]; ok {\n\t\tqctx.BuildManagerHostname = buildManagerHostname.(string)\n\t}\n\n\treturn nil\n}", "func UseLongAsUint32Pair() {\r\n\tlongAsString = false\r\n}", "func (out *OutBuffer) WriteUint64LE(v uint64) bool {\n\tcontainer := out.GetContainer()\n\tif len(container) < 8 {\n\t\treturn false\n\t}\n\n\tbinary.LittleEndian.PutUint64(out.GetContainer(), v)\n\tout.pos += 8\n\treturn true\n}", "func RegisterInt64(key string, def int64, description string) onion.Int {\n\tsetDescription(key, description)\n\treturn o.RegisterInt64(key, def)\n}", "func ValIsInt64(model ModelT, val *YvalT) int32 {\n\treturn int32(C.yices_val_is_int64(ymodel(model), (*C.yval_t)(val)))\n}", "func eb64(bits uint64, hi uint8, lo uint8) uint64 {\n\tm := uint64(((1 << (hi - lo)) - 1) << lo)\n\treturn (bits & m) >> lo\n}", "func (r *AMD64Registers) Get(n int) (uint64, error) {\n\treg := x86asm.Reg(n)\n\tconst (\n\t\tmask8 = 0x000f\n\t\tmask16 = 0x00ff\n\t\tmask32 = 0xffff\n\t)\n\n\tswitch reg {\n\t// 8-bit\n\tcase x86asm.AL:\n\t\treturn r.rax & mask8, nil\n\tcase x86asm.CL:\n\t\treturn r.rcx & mask8, nil\n\tcase x86asm.DL:\n\t\treturn r.rdx & mask8, nil\n\tcase x86asm.BL:\n\t\treturn r.rbx & mask8, nil\n\tcase x86asm.AH:\n\t\treturn (r.rax >> 8) & mask8, nil\n\tcase x86asm.CH:\n\t\treturn (r.rcx >> 8) & mask8, nil\n\tcase x86asm.DH:\n\t\treturn (r.rdx >> 8) & mask8, nil\n\tcase x86asm.BH:\n\t\treturn (r.rbx >> 8) & mask8, nil\n\tcase x86asm.SPB:\n\t\treturn r.rsp & mask8, nil\n\tcase x86asm.BPB:\n\t\treturn r.rbp & mask8, nil\n\tcase x86asm.SIB:\n\t\treturn r.rsi & mask8, nil\n\tcase x86asm.DIB:\n\t\treturn r.rdi & mask8, nil\n\tcase x86asm.R8B:\n\t\treturn r.r8 & mask8, nil\n\tcase x86asm.R9B:\n\t\treturn r.r9 & mask8, nil\n\tcase x86asm.R10B:\n\t\treturn r.r10 & mask8, nil\n\tcase x86asm.R11B:\n\t\treturn r.r11 & mask8, nil\n\tcase x86asm.R12B:\n\t\treturn r.r12 & mask8, nil\n\tcase x86asm.R13B:\n\t\treturn r.r13 & mask8, nil\n\tcase x86asm.R14B:\n\t\treturn r.r14 & mask8, nil\n\tcase x86asm.R15B:\n\t\treturn r.r15 & mask8, nil\n\n\t// 16-bit\n\tcase x86asm.AX:\n\t\treturn r.rax & mask16, nil\n\tcase x86asm.CX:\n\t\treturn r.rcx & mask16, nil\n\tcase x86asm.DX:\n\t\treturn r.rdx & mask16, nil\n\tcase x86asm.BX:\n\t\treturn r.rbx & mask16, nil\n\tcase x86asm.SP:\n\t\treturn r.rsp & mask16, nil\n\tcase x86asm.BP:\n\t\treturn r.rbp & mask16, nil\n\tcase x86asm.SI:\n\t\treturn r.rsi & mask16, nil\n\tcase x86asm.DI:\n\t\treturn r.rdi & mask16, nil\n\tcase x86asm.R8W:\n\t\treturn r.r8 & mask16, nil\n\tcase x86asm.R9W:\n\t\treturn r.r9 & mask16, nil\n\tcase x86asm.R10W:\n\t\treturn r.r10 & mask16, nil\n\tcase x86asm.R11W:\n\t\treturn r.r11 & mask16, nil\n\tcase x86asm.R12W:\n\t\treturn r.r12 & mask16, nil\n\tcase x86asm.R13W:\n\t\treturn r.r13 & mask16, nil\n\tcase x86asm.R14W:\n\t\treturn r.r14 & mask16, nil\n\tcase x86asm.R15W:\n\t\treturn r.r15 & mask16, nil\n\n\t// 32-bit\n\tcase x86asm.EAX:\n\t\treturn r.rax & mask32, nil\n\tcase x86asm.ECX:\n\t\treturn r.rcx & mask32, nil\n\tcase x86asm.EDX:\n\t\treturn r.rdx & mask32, nil\n\tcase x86asm.EBX:\n\t\treturn r.rbx & mask32, nil\n\tcase x86asm.ESP:\n\t\treturn r.rsp & mask32, nil\n\tcase x86asm.EBP:\n\t\treturn r.rbp & mask32, nil\n\tcase x86asm.ESI:\n\t\treturn r.rsi & mask32, nil\n\tcase x86asm.EDI:\n\t\treturn r.rdi & mask32, nil\n\tcase x86asm.R8L:\n\t\treturn r.r8 & mask32, nil\n\tcase x86asm.R9L:\n\t\treturn r.r9 & mask32, nil\n\tcase x86asm.R10L:\n\t\treturn r.r10 & mask32, nil\n\tcase x86asm.R11L:\n\t\treturn r.r11 & mask32, nil\n\tcase x86asm.R12L:\n\t\treturn r.r12 & mask32, nil\n\tcase x86asm.R13L:\n\t\treturn r.r13 & mask32, nil\n\tcase x86asm.R14L:\n\t\treturn r.r14 & mask32, nil\n\tcase x86asm.R15L:\n\t\treturn r.r15 & mask32, nil\n\n\t// 64-bit\n\tcase x86asm.RAX:\n\t\treturn r.rax, nil\n\tcase x86asm.RCX:\n\t\treturn r.rcx, nil\n\tcase x86asm.RDX:\n\t\treturn r.rdx, nil\n\tcase x86asm.RBX:\n\t\treturn r.rbx, nil\n\tcase x86asm.RSP:\n\t\treturn r.rsp, nil\n\tcase x86asm.RBP:\n\t\treturn r.rbp, nil\n\tcase x86asm.RSI:\n\t\treturn r.rsi, nil\n\tcase x86asm.RDI:\n\t\treturn r.rdi, nil\n\tcase x86asm.R8:\n\t\treturn r.r8, nil\n\tcase x86asm.R9:\n\t\treturn r.r9, nil\n\tcase x86asm.R10:\n\t\treturn r.r10, nil\n\tcase x86asm.R11:\n\t\treturn r.r11, nil\n\tcase x86asm.R12:\n\t\treturn r.r12, nil\n\tcase x86asm.R13:\n\t\treturn r.r13, nil\n\tcase x86asm.R14:\n\t\treturn r.r14, nil\n\tcase x86asm.R15:\n\t\treturn r.r15, nil\n\t}\n\n\treturn 0, proc.ErrUnknownRegister\n}", "func TestUnaligned64(t *testing.T) {\n\t// Unaligned 64-bit atomics on 32-bit systems are\n\t// a continual source of pain. Test that on 32-bit systems they crash\n\t// instead of failing silently.\n\n\tswitch runtime.GOARCH {\n\tdefault:\n\t\tif unsafe.Sizeof(int(0)) != 4 {\n\t\t\tt.Skip(\"test only runs on 32-bit systems\")\n\t\t}\n\tcase \"amd64p32\":\n\t\t// amd64p32 can handle unaligned atomics.\n\t\tt.Skipf(\"test not needed on %v\", runtime.GOARCH)\n\t}\n\n\tx := make([]uint32, 4)\n\tu := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) | 4) // force alignment to 4\n\n\tup64 := (*uint64)(u) // misaligned\n\tp64 := (*int64)(u) // misaligned\n\n\tshouldPanic(t, \"Load64\", func() { satomic.LoadUint64(up64) })\n\tshouldPanic(t, \"Loadint64\", func() { satomic.LoadInt64(p64) })\n\tshouldPanic(t, \"Store64\", func() { satomic.StoreUint64(up64, 0) })\n}", "func isARM64Instance(instanceType string) bool {\n\tr := regexp.MustCompile(\"(a1|.\\\\dgd?)\\\\.(medium|\\\\d*x?large|metal)\")\n\tif r.MatchString(instanceType) {\n\t\treturn true\n\t}\n\treturn false\n}", "func TestCount64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestCountN(testN, hm)\n}", "func JDK_jang_lang_Double_longBitsToDouble(bits Long) Double {\n\tvalue := math.Float64frombits(uint64(bits)) // todo\n\treturn Double(value)\n}", "func main() {\n\ttest32()\n\ttest64()\n}", "func BenchmarkHasSet64(b *testing.B) {\n\thasInit(b)\n\tfor n := 0; n < b.N; n++ {\n\t\thasIntSet64Data.Has(1000)\n\t}\n}", "func GetInt64Value(model ModelT, t TermT, val *int64) int32 {\n\treturn int32(C.yices_get_int64_value(ymodel(model), C.term_t(t), (*C.int64_t)(val)))\n}", "func GetInt64(key string) int64 {\n\ts, contains := getFromMode(key)\n\tif !contains {\n\t\ts, contains = getFromGlobal(key)\n\t}\n\tif contains {\n\t\ti, err := strconv.ParseInt(s, 10, 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"GetInt64 error:\", err)\n\t\t\treturn 0\n\t\t}\n\t\treturn i\n\t}\n\tfmt.Println(\"values of\", key, \"is not set!\")\n\treturn 0\n}", "func uint64Little(b []byte) uint64 {\n\tif len(b) < 8 {\n\t\tpanic(fmt.Sprintf(\"input smaller than eight bytes - got %d\", len(b)))\n\t}\n\treturn binary.LittleEndian.Uint64(b)\n}", "func SetBvUint64Value(model ModelT, t TermT, val uint64) int32 {\n\treturn int32(C.yices_model_set_bv_uint64(ymodel(model), C.term_t(t), C.uint64_t(val)))\n}", "func (m *MacOSMinimumOperatingSystem) GetV1012()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_12\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func TestGet64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestGetN(testN, hm)\n}", "func SetScreenSizeChecked(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(true, false)\n\tc.NewRequest(setScreenSizeRequest(c, Window, Width, Height, MmWidth, MmHeight), cookie)\n\treturn SetScreenSizeCookie{cookie}\n}", "func (r *QuayRegistryReconciler) checkBuildManagerAvailable(ctx *quaycontext.QuayRegistryContext, quay *v1.QuayRegistry, configBundle map[string][]byte) (*quaycontext.QuayRegistryContext, *v1.QuayRegistry, error) {\n\tvar config map[string]interface{}\n\tif err := yaml.Unmarshal(configBundle[\"config.yaml\"], &config); err != nil {\n\t\treturn ctx, quay, err\n\t}\n\n\tif buildManagerHostname, ok := config[\"BUILDMAN_HOSTNAME\"]; ok {\n\t\tctx.BuildManagerHostname = buildManagerHostname.(string)\n\t}\n\n\treturn ctx, quay, nil\n}", "func configureForOS(path string) error {\n\t// The key name is the localized path for the Diablo II directory.\n\tkeyName := fmt.Sprintf(\"%s\\\\%s\", localizePath(path), \"Game.exe\")\n\n\t// Open the compatibility key directory.\n\tcompatibilityKey, err := registry.OpenKey(registry.CURRENT_USER,\n\t\t`Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers`,\n\t\tregistry.QUERY_VALUE|registry.SET_VALUE,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set Windows XP Service Pack 2 compatibility mode.\n\tif err := compatibilityKey.SetStringValue(keyName, \"~ WINXPSP2\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Close the registry when we're done.\n\tif err := compatibilityKey.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Float64From32Bits(f float64) float64 {\n\tif f < 0 {\n\t\treturn 0\n\t}\n\treturn f\n}", "func ConvertInt64Set(values ...interface{}) (Int64Set, bool) {\n\tset := make(Int64Set)\n\n\tfor _, i := range values {\n\t\tswitch i.(type) {\n\t\tcase int:\n\t\t\tset[int64(i.(int))] = struct{}{}\n\t\tcase int8:\n\t\t\tset[int64(i.(int8))] = struct{}{}\n\t\tcase int16:\n\t\t\tset[int64(i.(int16))] = struct{}{}\n\t\tcase int32:\n\t\t\tset[int64(i.(int32))] = struct{}{}\n\t\tcase int64:\n\t\t\tset[int64(i.(int64))] = struct{}{}\n\t\tcase uint:\n\t\t\tset[int64(i.(uint))] = struct{}{}\n\t\tcase uint8:\n\t\t\tset[int64(i.(uint8))] = struct{}{}\n\t\tcase uint16:\n\t\t\tset[int64(i.(uint16))] = struct{}{}\n\t\tcase uint32:\n\t\t\tset[int64(i.(uint32))] = struct{}{}\n\t\tcase uint64:\n\t\t\tset[int64(i.(uint64))] = struct{}{}\n\t\tcase float32:\n\t\t\tset[int64(i.(float32))] = struct{}{}\n\t\tcase float64:\n\t\t\tset[int64(i.(float64))] = struct{}{}\n\t\t}\n\t}\n\n\treturn set, len(set) == len(values)\n}", "func TestShiftLess64(t *testing.T) {\n v := New([]uint8{\n 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0,\n 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1,\n 1, 0, 0, 1, 1, 0, 1, 0,\n })\n resLeft1 := New([]uint8{\n 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0,\n 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1,\n 1, 0, 0, 1, 1, 0, 1, 0, 0,\n })\n resRight1 := New([]uint8{\n 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0,\n 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1,\n 1, 0, 0, 1, 1, 0, 1,\n })\n resLeft21 := New([]uint8{\n 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1,\n 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n })\n resRight21 := New([]uint8{\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0,\n 0, 1, 1,\n })\n resZero := New(40)\n res := v.ShiftLeft(0)\n if !res.Equal(v) {\n t.Errorf(\"vector testing: %v.ShiftLeft(0) is incorrect, is %v, but expected %v\",\n v, res, v)\n }\n res = v.ShiftLeft(1)\n if !res.Equal(resLeft1) {\n t.Errorf(\"vector testing: %v.ShiftLeft(1) is incorrect, is %v, but expected %v\",\n v, res, resLeft1)\n }\n res = v.ShiftLeft(21)\n if !res.Equal(resLeft21) {\n t.Errorf(\"vector testing: %v.ShiftLeft(21) is incorrect, is %v, but expected %v\",\n v, res, resLeft21)\n }\n res = v.ShiftLeft(40)\n if !res.Equal(resZero) {\n t.Errorf(\"vector testing: %v.ShiftLeft(40) is incorrect, is %v, but expected %v\",\n v, res, resZero)\n }\n\n res = v.ShiftRight(0)\n if !res.Equal(v) {\n t.Errorf(\"vector testing: %v.ShiftRight(0) is incorrect, is %v, but expected %v\",\n v, res, v)\n }\n res = v.ShiftRight(1)\n if !res.Equal(resRight1) {\n t.Errorf(\"vector testing: %v.ShiftRight(1) is incorrect, is %v, but expected %v\",\n v, res, resRight1)\n }\n res = v.ShiftRight(21)\n if !res.Equal(resRight21) {\n t.Errorf(\"vector testing: %v.ShiftRight(21) is incorrect, is %v, but expected %v\",\n v, res, resRight21)\n }\n res = v.ShiftRight(40)\n if !res.Equal(resZero) {\n t.Errorf(\"vector testing: %v.ShiftRight(40) is incorrect, is %v, but expected %v\",\n v, res, resZero)\n }\n}", "func (m *Win32LobAppRegistryDetection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Win32LobAppDetection.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteBoolValue(\"check32BitOn64System\", m.GetCheck32BitOn64System())\n if err != nil {\n return err\n }\n }\n if m.GetDetectionType() != nil {\n cast := (*m.GetDetectionType()).String()\n err = writer.WriteStringValue(\"detectionType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"detectionValue\", m.GetDetectionValue())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"keyPath\", m.GetKeyPath())\n if err != nil {\n return err\n }\n }\n if m.GetOperator() != nil {\n cast := (*m.GetOperator()).String()\n err = writer.WriteStringValue(\"operator\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"valueName\", m.GetValueName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func opUI64Eq(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) == ReadUI64(fp, expr.Inputs[1])\n\tWriteBool(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (cac CPUArchCeck) Check() (warnings, errorList []error) {\n\tresult, err := cac.CombinedOutput(\"getconf LONG_BIT\")\n\tif err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn\n\t}\n\tarch, err := strconv.Atoi(strings.TrimSpace(string(result)))\n\tif err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn\n\t}\n\n\tif arch != cac.Arch {\n\t\terrorList = append(errorList, errors.Errorf(\"only support CPU arch %d, but current is %d\", cac.Arch, arch))\n\t}\n\treturn warnings, errorList\n}", "func (me *Bitstream) PutWithBitCountLittleUint64(v uint64, n uint32) error {\n\treturn me.PutBitsUnsignedLittle(uint64(v), n)\n}", "func (l *Link) SetInt64(w int64) *Link {\n\treturn (*Link)((*big.Int)(l).SetInt64(w))\n}", "func getTickCount64() int64 {\n\tret, _, _ := procGetTickCount64.Call()\n\treturn int64(ret)\n}", "func TestCheckBinaryExprBoolRhlBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `true >> true`, env,\n\t\t`invalid operation: true >> true (shift count type bool, must be unsigned integer)`,\n\t)\n\n}", "func (m *MacOSMinimumOperatingSystem) GetV110()(*bool) {\n val, err := m.GetBackingStore().Get(\"v11_0\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func Uint64(list []uint64, value uint64) bool {\n\tfor _, item := range list {\n\t\tif item == value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Pow64(x int64, y int) int64 {\n\tif y == 0 {\n\t\treturn 1\n\t}\n\n\tresult := x\n\tfor n := 1; n < y; n++ {\n\t\tresult = result * x\n\t}\n\treturn result\n}", "func (child MagicU32) MagicBit() bool {\n\treturn (child & (1 << 31)) > 0\n}", "func (this *DynMap) GetInt64(key string) (int64, bool) {\n\ttmp, ok := this.Get(key)\n\tif !ok {\n\t\treturn -1, ok\n\t}\n\tval, err := ToInt64(tmp)\n\tif err == nil {\n\t\treturn val, true\n\t}\n\treturn -1, false\n}", "func (r *Record) SetInt64Field(d *Db, number uint16, data int64) error {\n\tif C.wg_set_int_field(d.db, r.rec, C.wg_int(number), C.wg_int(data)) != 0 {\n\t\treturn WDBError(\"Could not set field\")\n\t}\n\treturn nil\n}", "func opUI64Bitshr(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) >> ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func shift64ExtraRightJamming(a0, a1 uint64, count int16) (z0, z1 uint64) {\n\tif count == 0 {\n\t\tz1 = a1\n\t\tz0 = a0\n\t} else if count < 64 {\n\t\tz1 = (a0 << ((-count) & 63)) | x1(a1 != 0)\n\t\tz0 = a0 >> count\n\t} else {\n\t\tif count == 64 {\n\t\t\tz1 = a0 | x1(a1 != 0)\n\t\t} else if (a0 | a1) != 0 {\n\t\t\tz1 = 1\n\t\t}\n\t\tz0 = 0\n\t}\n\treturn\n}", "func TestUnaligned64(t *testing.T) {\n\t// Unaligned 64-bit atomics on 32-bit systems are\n\t// a continual source of pain. Test that on 32-bit systems they crash\n\t// instead of failing silently.\n\n\tif unsafe.Sizeof(int(0)) != 4 {\n\t\tt.Skip(\"test only runs on 32-bit systems\")\n\t}\n\n\tx := make([]uint32, 4)\n\tu := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) | 4) // force alignment to 4\n\n\tup64 := (*uint64)(u) // misaligned\n\tp64 := (*int64)(u) // misaligned\n\n\tshouldPanic(t, \"Load64\", func() { atomic.Load64(up64) })\n\tshouldPanic(t, \"Loadint64\", func() { atomic.Loadint64(p64) })\n\tshouldPanic(t, \"Store64\", func() { atomic.Store64(up64, 0) })\n\tshouldPanic(t, \"Xadd64\", func() { atomic.Xadd64(up64, 1) })\n\tshouldPanic(t, \"Xchg64\", func() { atomic.Xchg64(up64, 1) })\n\tshouldPanic(t, \"Cas64\", func() { atomic.Cas64(up64, 1, 2) })\n}", "func opBitwiseConstants64() []uint64 {\n\tvar result []uint64\n\tvar bitmask uint64\n\tvar size, length, e, rotation uint8\n\tfor size = 2; size <= 64; size *= 2 {\n\t\tfor length = 1; length < size; length++ {\n\t\t\tbitmask = 0xffffffffffffffff >> (64 - length)\n\t\t\tfor e = size; e < 64; e *= 2 {\n\t\t\t\tbitmask |= bitmask << e\n\t\t\t}\n\t\t\tfor rotation = 0; rotation < size; rotation++ {\n\t\t\t\tresult = append(result, bitmask)\n\t\t\t\tbitmask = (bitmask >> 1) | (bitmask << 63)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func Hash64WithSeeds(s []byte, seed0, seed1 uint64) uint64 {\n\treturn hash64Len16(Hash64(s)-seed0, seed1)\n}", "func (m *MacOSMinimumOperatingSystem) SetV110(value *bool)() {\n err := m.GetBackingStore().Set(\"v11_0\", value)\n if err != nil {\n panic(err)\n }\n}", "func opUI64Bitxor(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) ^ ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (m *MacOSMinimumOperatingSystem) SetV1012(value *bool)() {\n err := m.GetBackingStore().Set(\"v10_12\", value)\n if err != nil {\n panic(err)\n }\n}", "func (me *BitStream) ReadBitsLong(n int) uint32 {\n\ttmp := me.ShowBitsLong(n)\n\tme.Index += n\n\treturn tmp\n}" ]
[ "0.80912334", "0.7938606", "0.74322027", "0.7383997", "0.7221693", "0.5194884", "0.48725256", "0.46642232", "0.46489272", "0.44782275", "0.4423561", "0.43780947", "0.43608654", "0.4353791", "0.4339238", "0.432639", "0.426746", "0.4247548", "0.42021963", "0.41816446", "0.41808194", "0.41375047", "0.41232875", "0.4108926", "0.41049856", "0.41034183", "0.40960926", "0.40737107", "0.40691838", "0.40649176", "0.40565065", "0.40530735", "0.4039687", "0.4032187", "0.40306818", "0.40249383", "0.4023963", "0.3999065", "0.39862967", "0.39774087", "0.3942591", "0.3919007", "0.39146462", "0.3904088", "0.38941035", "0.38940644", "0.38898313", "0.3882403", "0.38787922", "0.387429", "0.387198", "0.38712585", "0.38712585", "0.38648593", "0.38284865", "0.38212293", "0.38111192", "0.38057092", "0.38024867", "0.380201", "0.37997952", "0.37943187", "0.37934023", "0.3782622", "0.37815145", "0.37675366", "0.37589008", "0.37579033", "0.37535468", "0.3753166", "0.37484133", "0.37448955", "0.37432933", "0.37415144", "0.37309077", "0.37188768", "0.37175", "0.37172365", "0.3714999", "0.3712113", "0.37099475", "0.37092972", "0.370018", "0.36988097", "0.36975998", "0.36855936", "0.36829892", "0.36811873", "0.36792955", "0.3675858", "0.36707652", "0.36707443", "0.36705795", "0.3666216", "0.3665354", "0.36634228", "0.3661254", "0.36592615", "0.3658389", "0.3655859" ]
0.81353074
0
SetDetectionType sets the detectionType property value. Contains all supported registry data detection type.
func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() { err := m.GetBackingStore().Set("detectionType", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ServicePrincipalRiskDetection) SetDetectionTimingType(value *RiskDetectionTimingType)() {\n err := m.GetBackingStore().Set(\"detectionTimingType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}", "func (myOperatingSystemType *OperatingSystemType) SetType(val string) {\n\tmyOperatingSystemType.Typevar = val\n}", "func (m *IPInRangeCompareOperation) SetType(val string) {\n\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (n *Node) SetType(t provider.ResourceType) {\n\tn.nodeType = &t\n}", "func (m *DeviceComplianceScriptDeviceState) SetDetectionState(value *RunState)() {\n err := m.GetBackingStore().Set(\"detectionState\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryRule) SetOperationType(value *Win32LobAppRegistryRuleOperationType)() {\n m.operationType = value\n}", "func (m *FileEvidence) SetDetectionStatus(value *DetectionStatus)() {\n err := m.GetBackingStore().Set(\"detectionStatus\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) SetRuleType(value *DeviceManagementApplicabilityRuleType)() {\n err := m.GetBackingStore().Set(\"ruleType\", value)\n if err != nil {\n panic(err)\n }\n}", "func DetectType(typ api.CQLinterType, project api.Project) bool {\n\tlinter, ok := ByType[typ]\n\treturn ok && DetectLinter(linter, project)\n}", "func (o *SyntheticsBrowserTest) SetType(v SyntheticsBrowserTestType) {\n\to.Type = v\n}", "func (n *node) SetType(t string) {\n\tn.nodeType = t\n}", "func (i *CreationInfo) SetType(str string) {\n\tC.alt_IResource_CreationInfo_SetType(i.altInfoPtr, C.CString(str))\n\ti.Type = str\n}", "func (m *Win32LobAppFileSystemDetection) GetDetectionType()(*Win32LobAppFileSystemDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppFileSystemDetectionType)\n }\n return nil\n}", "func (iface *Interface) SetType(ifType string) {\n\tiface.lock.Lock()\n\tdefer iface.lock.Unlock()\n\n\tiface.Type = toIfType(ifType)\n}", "func (options *CreateLoadBalancerMonitorOptions) SetType(typeVar string) *CreateLoadBalancerMonitorOptions {\n\toptions.Type = core.StringPtr(typeVar)\n\treturn options\n}", "func (s UserSet) SetType(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Type\", \"type\"), value)\n}", "func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *SyntheticsGlobalVariableParseTestOptions) SetType(v SyntheticsGlobalVariableParseTestOptionsType) {\n\to.Type = v\n}", "func (d UserData) SetType(value string) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Type\", \"type\"), value)\n\treturn d\n}", "func (o *LocalDatabaseProvider) SetType(v string) {\n\to.Type = v\n}", "func (m *Drive) SetDriveType(value *string)() {\n m.driveType = value\n}", "func (o *MonitorSearchResult) SetType(v MonitorType) {\n\to.Type = &v\n}", "func (field *Field) SetType() {\n\t// field.Type = field.StructField.Name\n}", "func (m *WebsiteSLAWidgetData) SetType(val string) {\n\n}", "func (m *notification) SetProviderType(val string) {\n\tm.providerTypeField = val\n}", "func (options *EditLoadBalancerMonitorOptions) SetType(typeVar string) *EditLoadBalancerMonitorOptions {\n\toptions.Type = core.StringPtr(typeVar)\n\treturn options\n}", "func (sc *ServiceConfiguration) SetType(serviceType *Provider) {\n\tsc.ServiceType = serviceType\n}", "func (s *ResolutionTechniques) SetResolutionType(v string) *ResolutionTechniques {\n\ts.ResolutionType = &v\n\treturn s\n}", "func (o *SyntheticMonitorUpdate) SetType(v string) {\n\to.Type = v\n}", "func (mdl *Model) SetType(typ std.ModelType) error {\n\tif len(mdl.data) > 0 {\n\t\treturn errors.New(ReadOnlyProperty, \"model is not empty, type cannot be modified\")\n\t}\n\tmdl.typ = typ\n\treturn nil\n}", "func (s *Portal) SetRendererType(v string) *Portal {\n\ts.RendererType = &v\n\treturn s\n}", "func (_options *ReplaceIntegrationOptions) SetType(typeVar string) *ReplaceIntegrationOptions {\n\t_options.Type = core.StringPtr(typeVar)\n\treturn _options\n}", "func (m *sdt) SetType(val string) {\n\n}", "func (m *UnifiedRoleManagementPolicyNotificationRule) SetNotificationType(value *string)() {\n m.notificationType = value\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetType(typeVar string) {\n\to.Type = typeVar\n}", "func (m *EqOp) SetType(val string) {\n}", "func (nmd *NetMethodDispatch) RegisterType(key reflect.Type, f NetMethodFun) {\n\tnmd.sync.Lock()\n\tdefer nmd.sync.Unlock()\n\tnmd.m[key] = f\n}", "func (k *Keyboard) SetType(typ KeyboardType) {\n\tk.enabled = true\n\tk.typ = typ\n}", "func (in *ActionLocationIndexInput) SetHypervisorType(value string) *ActionLocationIndexInput {\n\tin.HypervisorType = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"HypervisorType\"] = nil\n\treturn in\n}", "func (o *Ga4ghChemotherapy) SetType(v string) {\n\to.Type = &v\n}", "func (b IGMP) SetType(t IGMPType) { b[igmpTypeOffset] = byte(t) }", "func (m *NOCWidget) SetType(val string) {\n\n}", "func (g *Generator) SetRootfsType(rootfsType string) {\n\tg.image.RootFS.Type = rootfsType\n}", "func (o *WorkflowCliCommandAllOf) SetType(v string) {\n\to.Type = &v\n}", "func (s *PortalSummary) SetRendererType(v string) *PortalSummary {\n\ts.RendererType = &v\n\treturn s\n}", "func (ms MetricDescriptor) SetType(v MetricType) {\n\t(*ms.orig).Type = otlpmetrics.MetricDescriptor_Type(v)\n}", "func (o *VerificationTraits) SetType(v string) {\n\to.Type = v\n}", "func (o *CalendareventsIdJsonEventReminders) SetType(v string) {\n\to.Type = &v\n}", "func (m *User) SetInferenceClassification(value InferenceClassificationable)() {\n m.inferenceClassification = value\n}", "func (o *Partition) SetType(ctx context.Context, inType string, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfacePartition+\".SetType\", 0, inType, options).Store()\n\treturn\n}", "func (ggc *GithubGistCreate) SetType(s string) *GithubGistCreate {\n\tggc.mutation.SetType(s)\n\treturn ggc\n}", "func (m *StartsWithCompareOperation) SetType(val string) {\n\n}", "func (m *endpoint) SetType(val string) {\n}", "func (m *DetectionRule) SetDetectionAction(value DetectionActionable)() {\n err := m.GetBackingStore().Set(\"detectionAction\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *StorageNetAppCloudTargetAllOf) SetProviderType(v string) {\n\to.ProviderType = &v\n}", "func (o *LogsPipelineProcessor) SetType(v LogsPipelineProcessorType) {\n\to.Type = v\n}", "func (g *generator) SetRepositoryType(t int) {\n\tg.repositoryType = t\n}", "func DetectRendererType(filename string, input io.Reader) string {\n\tbuf, err := io.ReadAll(input)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tfor _, renderer := range renderers {\n\t\tif detector, ok := renderer.(RendererContentDetector); ok && detector.CanRender(filename, bytes.NewReader(buf)) {\n\t\t\treturn renderer.Name()\n\t\t}\n\t}\n\treturn \"\"\n}", "func (rb *DataframeAnalyticsFieldSelectionBuilder) FeatureType(featuretype string) *DataframeAnalyticsFieldSelectionBuilder {\n\trb.v.FeatureType = &featuretype\n\treturn rb\n}", "func (nuo *NodeUpdateOne) SetType(s string) *NodeUpdateOne {\n\tnuo.mutation.SetType(s)\n\treturn nuo\n}", "func SetWatchdogViaType(iType string, watchdog *Watchdog) (int64, error) {\n\twatchdog.Type = iType\n\treturn Engine.Insert(watchdog)\n}", "func (o *Wireless) SetType(v string) {\n\to.Type = &v\n}", "func (cmd *WebsocketCommandHandler) SetType(name string) {\n\tcmd.Command = name\n}", "func (nu *NodeUpdate) SetType(s string) *NodeUpdate {\n\tnu.mutation.SetType(s)\n\treturn nu\n}", "func (m *UserExperienceAnalyticsMetricHistory) SetMetricType(value *string)() {\n err := m.GetBackingStore().Set(\"metricType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *AppVulnerabilityTask) SetMitigationType(value *AppVulnerabilityTaskMitigationType)() {\n err := m.GetBackingStore().Set(\"mitigationType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (options *UpdateNotificationChannelOptions) SetType(typeVar string) *UpdateNotificationChannelOptions {\n\toptions.Type = core.StringPtr(typeVar)\n\treturn options\n}", "func RegisterType(t reflect.Type) {\n\tregistry.RegisterType(t)\n}", "func (o *KubernetesEthernetMatcher) SetType(v string) {\n\to.Type = &v\n}", "func (m *SocialIdentityProvider) SetIdentityProviderType(value *string)() {\n err := m.GetBackingStore().Set(\"identityProviderType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Shape) SetType(val string) {\n\tm.Type = val\n}", "func (o *StoragePhysicalDiskAllOf) SetType(v string) {\n\to.Type = &v\n}", "func (o *View) SetType(v string) {\n\to.Type = v\n}", "func (m *AssignedEntitiesWithMetricTile) SetTileType(val string) {\n\n}", "func (o *StorageEnclosure) SetType(v string) {\n\to.Type = &v\n}", "func (m *ResourceMutation) SetType(s string) {\n\tm._type = &s\n}", "func (o *PluginMount) SetType(v string) {\n\to.Type = v\n}", "func (du *DiagnosisUpdate) SetType(t *TreatmentType) *DiagnosisUpdate {\n\treturn du.SetTypeID(t.ID)\n}", "func (guo *GroupUpdateOne) SetType(s string) *GroupUpdateOne {\n\tguo.mutation.SetType(s)\n\treturn guo\n}", "func (o *PlatformImage) SetType(v string) {\n\to.Type = &v\n}", "func (g *Group) SetEngineType(e EngineType) *Group {\n\tg.EngineType = e\n\treturn g\n}", "func (m *Group) SetClassification(value *string)() {\n m.classification = value\n}", "func (this *ActivityStreamsImagePropertyIterator) SetType(t vocab.Type) error {\n\tif v, ok := t.(vocab.ActivityStreamsImage); ok {\n\t\tthis.SetActivityStreamsImage(v)\n\t\treturn nil\n\t}\n\tif v, ok := t.(vocab.ActivityStreamsLink); ok {\n\t\tthis.SetActivityStreamsLink(v)\n\t\treturn nil\n\t}\n\tif v, ok := t.(vocab.ActivityStreamsMention); ok {\n\t\tthis.SetActivityStreamsMention(v)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"illegal type to set on ActivityStreamsImage property: %T\", t)\n}", "func (u *GithubGistUpsert) SetType(v string) *GithubGistUpsert {\n\tu.Set(githubgist.FieldType, v)\n\treturn u\n}", "func (m *RegistryKeyState) SetValueType(value *RegistryValueType)() {\n m.valueType = value\n}", "func (o *GetPageDataUsingGETParams) SetPageType(pageType *string) {\n\to.PageType = pageType\n}", "func (b *Block) SetType(tlvType uint32) {\n\tif b.tlvType != tlvType {\n\t\tb.tlvType = tlvType\n\t\tb.wire = []byte{}\n\t}\n}", "func (options *CreateNotificationChannelOptions) SetType(typeVar string) *CreateNotificationChannelOptions {\n\toptions.Type = core.StringPtr(typeVar)\n\treturn options\n}", "func (gu *GroupUpdate) SetType(s string) *GroupUpdate {\n\tgu.mutation.SetType(s)\n\treturn gu\n}", "func (o *EquipmentBaseSensor) SetType(v string) {\n\to.Type = &v\n}", "func (o *UserActionNamingPlaceholderProcessingStep) SetType(v string) {\n\to.Type = v\n}", "func (m *FileMutation) SetType(s string) {\n\tm._type = &s\n}", "func (o *RecurrenceRepetition) SetType(v string) {\n\to.Type = v\n}", "func (m *SocialIdentityProvider) SetIdentityProviderType(value *string)() {\n m.identityProviderType = value\n}", "func (o *PrivilegedData) SetType(v Secrettypes) {\n\to.Type = v\n}", "func (ent Entity) SetType(newType Type) bool {\n\tif ent.Scope == nil || ent.ID == 0 {\n\t\tpanic(\"invalid entity handle\")\n\t}\n\tpriorTyp, seq := ent.typ()\n\treturn ent.setType(priorTyp, seq, newType)\n}", "func (g *Generator) SetType(t string) *Generator {\n\tg.opts.Type = t\n\treturn g\n}" ]
[ "0.7363352", "0.5975671", "0.5331663", "0.53013253", "0.52569485", "0.51956946", "0.51857483", "0.5160634", "0.5101551", "0.5071986", "0.49641094", "0.49582717", "0.4951682", "0.48980385", "0.48872924", "0.48744246", "0.48734355", "0.48619604", "0.48555112", "0.48502493", "0.48458427", "0.48358235", "0.4809168", "0.48087204", "0.47981334", "0.47625846", "0.47459584", "0.4745729", "0.47382477", "0.47344783", "0.47335157", "0.4732938", "0.47166443", "0.4678857", "0.46746793", "0.46616265", "0.4658934", "0.46583277", "0.46532828", "0.46447796", "0.46330753", "0.46214214", "0.46117336", "0.45859957", "0.45848182", "0.4581876", "0.45801568", "0.45684418", "0.4566939", "0.45614383", "0.45321402", "0.45244932", "0.4523592", "0.45169157", "0.4496417", "0.44883764", "0.44880033", "0.44861984", "0.44807518", "0.44804242", "0.4479112", "0.44754273", "0.44674397", "0.4464419", "0.44570923", "0.4439013", "0.44374812", "0.4433635", "0.44300187", "0.442679", "0.4424423", "0.4412666", "0.44044024", "0.44041127", "0.44009855", "0.4393913", "0.43872213", "0.43831196", "0.4379897", "0.43772557", "0.4376164", "0.4372493", "0.43669567", "0.43631563", "0.4363014", "0.4361322", "0.434833", "0.43450397", "0.43448773", "0.4344188", "0.43424124", "0.43415046", "0.4339491", "0.43295297", "0.4328492", "0.43283868", "0.43260017", "0.43244508", "0.43242013", "0.43226302" ]
0.78450286
0
SetDetectionValue sets the detectionValue property value. The registry detection value
func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() { err := m.GetBackingStore().Set("detectionValue", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *DeviceComplianceScriptDeviceState) SetDetectionState(value *RunState)() {\n err := m.GetBackingStore().Set(\"detectionState\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *FileEvidence) SetDetectionStatus(value *DetectionStatus)() {\n err := m.GetBackingStore().Set(\"detectionStatus\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryRule) SetComparisonValue(value *string)() {\n m.comparisonValue = value\n}", "func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}", "func setValue(value []byte) error {\n\terr := recognizersStore.Set(recognizersKey, string(value))\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\n\thashVal := md5.Sum(value)\n\tcalculatedHash := hex.EncodeToString(hashVal[:])\n\tlog.Info(\"Updating hash: \" + calculatedHash)\n\terr = recognizersStore.Set(hashKey, calculatedHash)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *DetectionRule) SetDetectionAction(value DetectionActionable)() {\n err := m.GetBackingStore().Set(\"detectionAction\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *KubernetesEthernetMatcher) SetValue(v string) {\n\to.Value = &v\n}", "func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() {\n err := m.GetBackingStore().Set(\"valueName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *WindowsMalwareCategoryCount) SetActiveMalwareDetectionCount(value *int32)() {\n err := m.GetBackingStore().Set(\"activeMalwareDetectionCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r *DNSResolvers) SetValue(val interface{}) {\n\t*r = val.(DNSResolvers)\n}", "func (o *FeatureFlag) SetValue(v string) {\n\to.Value = v\n}", "func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *CreateRiskRulesData) SetValue(v string) {\n\to.Value = v\n}", "func (m *ServicePrincipalRiskDetection) SetDetectionTimingType(value *RiskDetectionTimingType)() {\n err := m.GetBackingStore().Set(\"detectionTimingType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Measurement) SetValue(value string) {\n\tm.Values[\"value\"] = value\n}", "func (m *ServicePrincipalRiskDetection) SetDetectedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n err := m.GetBackingStore().Set(\"detectedDateTime\", value)\n if err != nil {\n panic(err)\n }\n}", "func (b *CapabilityBuilder) Value(value string) *CapabilityBuilder {\n\tb.value = value\n\tb.bitmap_ |= 4\n\treturn b\n}", "func RegisterValue(newFn func() Value) {\n\ttyp := newFn().Type()\n\n\tif _, ok := valueMap[typ]; ok {\n\t\tpanic(newValueErr(ErrValueRegistered, typ))\n\t}\n\n\tvalueMap[typ] = newFn\n}", "func (c *Counter) SetValue(value interface{}) {\n\tif val, ok := value.(float64); ok {\n\t\tc.count = val\n\t}\n}", "func (o *LabelProperties) SetValue(v string) {\n\n\to.Value = &v\n\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetOccurrence(value DeviceManagementConfigurationSettingOccurrenceable)() {\n err := m.GetBackingStore().Set(\"occurrence\", value)\n if err != nil {\n panic(err)\n }\n}", "func (cmd *Fuel) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsByte()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = float32(payload) / 255\n\n\treturn nil\n}", "func (s *GattDescriptor1) UpdateValue(value []byte) error {\n\ts.properties.Value = value\n\terr := s.PropertiesInterface.Instance().Set(s.Interface(), \"Value\", dbus.MakeVariant(value))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (part *PartSupported) SetRawValue(val uint32) {\n\tpart.Value = val\n}", "func (o *AllocationVersion) SetValue(v string) {\n\to.Value = &v\n}", "func (cmd *EngineLoad) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsByte()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = float32(payload) / 255\n\n\treturn nil\n}", "func (o *EquipmentBaseSensor) SetValue(v string) {\n\to.Value = &v\n}", "func (s *EvaluationAnswerInput_) SetValue(v *EvaluationAnswerData) *EvaluationAnswerInput_ {\n\ts.Value = v\n\treturn s\n}", "func (s *AnalyticsSessionMetricResult) SetValue(v float64) *AnalyticsSessionMetricResult {\n\ts.Value = &v\n\treturn s\n}", "func (s *EvaluationAnswerOutput_) SetValue(v *EvaluationAnswerData) *EvaluationAnswerOutput_ {\n\ts.Value = v\n\treturn s\n}", "func (s *EdgeMetric) SetValue(v float64) *EdgeMetric {\n\ts.Value = &v\n\treturn s\n}", "func (o *ResourceDefinitionFilter) SetValue(v string) {\n\to.Value = v\n}", "func (m *DeviceCompliancePolicyCollectionResponse) SetValue(value []DeviceCompliancePolicyable)() {\n err := m.GetBackingStore().Set(\"value\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *VerifiableAddress) SetValue(v string) {\n\to.Value = v\n}", "func (m *Metric) SetGaugeValue(labelValues []string, value float64) error {\n\tif m.Type == None {\n\t\treturn errors.Errorf(\"metric '%s' not existed.\", m.Name)\n\t}\n\n\tif m.Type != Gauge {\n\t\treturn errors.Errorf(\"metric '%s' not Gauge type\", m.Name)\n\t}\n\tm.vec.(*prometheus.GaugeVec).WithLabelValues(labelValues...).Set(value)\n\treturn nil\n}", "func (m *ManagedDeviceComplianceCollectionResponse) SetValue(value []ManagedDeviceComplianceable)() {\n err := m.GetBackingStore().Set(\"value\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *AnalyticsIntentStageMetricResult) SetValue(v float64) *AnalyticsIntentStageMetricResult {\n\ts.Value = &v\n\treturn s\n}", "func (s *EvaluationNote) SetValue(v string) *EvaluationNote {\n\ts.Value = &v\n\treturn s\n}", "func (cmd *MonitorStatus) SetValue(result *Result) error {\n\texpAmount := 4\n\tpayload := result.value[2:]\n\tamount := len(payload)\n\n\tif amount != expAmount {\n\t\treturn fmt.Errorf(\n\t\t\t\"Expected %d bytes of payload, got %d\", expAmount, amount,\n\t\t)\n\t}\n\n\t// 0x80 is the MSB: 0b10000000\n\tcmd.MilActive = (payload[0] & 0x80) == 0x80\n\t// 0x7F everything but the MSB: 0b01111111\n\tcmd.DtcAmount = byte(payload[0] & 0x7F)\n\n\treturn nil\n}", "func (s *ListServiceInstancesFilter) SetValue(v string) *ListServiceInstancesFilter {\n\ts.Value = &v\n\treturn s\n}", "func (m *DeviceHealthScriptRunSummary) SetDetectionScriptPendingDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"detectionScriptPendingDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *AnalyticsUtteranceMetricResult) SetValue(v float64) *AnalyticsUtteranceMetricResult {\n\ts.Value = &v\n\treturn s\n}", "func (o *MetricsDataValue) SetValue(v string) {\n\to.Value = &v\n}", "func SetFloat64Value(cfg *viper.Viper, name string, v *float64) {\n\tif cfg.IsSet(name) {\n\t\t*v = cfg.GetFloat64(name)\n\t}\n}", "func (ms SummaryValueAtPercentile) SetValue(v float64) {\n\t(*ms.orig).Value = v\n}", "func (s *AvailSuppression) SetValue(v string) *AvailSuppression {\n\ts.Value = &v\n\treturn s\n}", "func (rg *StaticGauge) Set(value float64) {\n\trg.Base.watcher.WithLabelValues(rg.values...).Set(value)\n}", "func (o *RiskRulesListAllOfData) SetValue(v string) {\n\to.Value = &v\n}", "func (self *HttpParam) setPresentValue(value interface{}) {\n\tself.Present = true\n\tself.Value = value\n}", "func (s *GeoMatchConstraint) SetValue(v string) *GeoMatchConstraint {\n\ts.Value = &v\n\treturn s\n}", "func (s *AnalyticsUtteranceGroupByKey) SetValue(v string) *AnalyticsUtteranceGroupByKey {\n\ts.Value = &v\n\treturn s\n}", "func (cmd *EngineRPM) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsUInt16()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = float32(payload) / 4\n\n\treturn nil\n}", "func (s *CurrentMetricData) SetValue(v float64) *CurrentMetricData {\n\ts.Value = &v\n\treturn s\n}", "func (rule *GameRule) SetValue(value interface{}) bool {\n\tif reflect.TypeOf(value).Kind() != reflect.TypeOf(rule.value).Kind() {\n\t\treturn false\n\t}\n\trule.value = value\n\treturn true\n}", "func (m *DeviceHealthScriptRunSummary) SetDetectionScriptNotApplicableDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"detectionScriptNotApplicableDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (w *Writer) WriteValue(v reflect.Value) {\n\tvalueEncoders[v.Kind()](w, v)\n}", "func (s *AnalyticsIntentStageGroupByKey) SetValue(v string) *AnalyticsIntentStageGroupByKey {\n\ts.Value = &v\n\treturn s\n}", "func (s *SystemControl) SetValue(v string) *SystemControl {\n\ts.Value = &v\n\treturn s\n}", "func (s *AnalyticsIntentMetricResult) SetValue(v float64) *AnalyticsIntentMetricResult {\n\ts.Value = &v\n\treturn s\n}", "func (o *UploadResponse) SetValue(v NFT) {\n\to.Value = &v\n}", "func (n *Node) SetVal(v Val)", "func setValue(fv *reflect.Value, c *Config, key string) error {\n\t// Update the value with the correct type\n\tswitch fv.Kind() {\n\tcase reflect.Int:\n\t\tval, err := c.GetInt(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetInt(int64(val))\n\tcase reflect.Float64:\n\t\tval, err := c.GetFloat(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetFloat(val)\n\tcase reflect.Bool:\n\t\tval, err := c.GetBool(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetBool(val)\n\tcase reflect.String:\n\t\tval, err := c.GetString(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetString(val)\n\t}\n\n\treturn nil\n}", "func (s *Float64Setting) SetValue(v interface{}) error {\n\tvar err error\n\t*s.Float64Value, err = cast.ToFloat64E(v)\n\treturn err\n}", "func (m *RegistryKeyState) SetValueType(value *RegistryValueType)() {\n m.valueType = value\n}", "func (o *AssetConcentrationRisk) SetValue(v float64) {\n\to.Value = v\n}", "func (s *FeatureParameter) SetValue(v string) *FeatureParameter {\n\ts.Value = &v\n\treturn s\n}", "func (o *Sensorefficiency) SetValue(v string) {\n\to.Value = v\n}", "func (g Generator) setTestResultValue(result *ir.Result, pathwayResult *pathway.Result, tt *orderprofile.TestType) error {\n\tswitch {\n\tcase pathwayResult.IsValueRandom() && pathwayResult.ReferenceRange != \"\":\n\t\t// Generate random value from the custom reference range.\n\t\treturn g.setRandomValueBasedOnCustomReferenceRange(result, pathwayResult)\n\n\tcase pathwayResult.IsValueRandom() && pathwayResult.ReferenceRange == \"\":\n\t\t// Generate random value from the order profile's reference range.\n\t\treturn g.setRandomValueBasedOnOrderProfileReferenceRange(result, pathwayResult, tt)\n\n\tdefault:\n\t\t// Use values specified in the pathway.\n\t\treturn g.setValueSpecifiedInThePathway(result, pathwayResult, tt)\n\t}\n\treturn nil\n}", "func CreateDetectionRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDetectionRule(), nil\n}", "func (s *AnalyticsSessionGroupByKey) SetValue(v string) *AnalyticsSessionGroupByKey {\n\ts.Value = &v\n\treturn s\n}", "func (s *AnalyticsIntentGroupByKey) SetValue(v string) *AnalyticsIntentGroupByKey {\n\ts.Value = &v\n\treturn s\n}", "func (s *StatusCodes) SetValue(val interface{}) {\n\t*s = val.(StatusCodes)\n}", "func (s *MetricDataV2) SetValue(v float64) *MetricDataV2 {\n\ts.Value = &v\n\treturn s\n}", "func (n *Node) SetValue(value int) {\n\tpriorValues := map[*Node]int{n: n.value}\n\tn.value = value\n\tqueue := append([]*Node{}, n.dependencies...)\n\n\t// update values of all dependencies in a BFS manner, tracking prior values\n\tfor len(queue) > 0 {\n\t\tnext := queue[0]\n\t\tqueue = append(queue[1:], next.dependencies...)\n\t\tpriorValues[next] = next.value\n\t\tif next.f1 != nil {\n\t\t\tnext.value = next.f1(next.a.Value())\n\t\t} else if next.f2 != nil {\n\t\t\tnext.value = next.f2(next.a.Value(), next.b.Value())\n\t\t}\n\t}\n\n\t// for any changed value, also trigger callbacks\n\tfor m := range priorValues {\n\t\tif priorValues[m] != m.value {\n\t\t\tfor _, f := range m.callbacks {\n\t\t\t\tif f != nil {\n\t\t\t\t\tf(m.value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *DeviceHealthScriptRunSummary) SetIssueDetectedDeviceCount(value *int32)() {\n err := m.GetBackingStore().Set(\"issueDetectedDeviceCount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *UrlReference) SetValue(v string) *UrlReference {\n\ts.Value = &v\n\treturn s\n}", "func (s *HandshakeResource) SetValue(v string) *HandshakeResource {\n\ts.Value = &v\n\treturn s\n}", "func (s *AnalyticsBinKey) SetValue(v int64) *AnalyticsBinKey {\n\ts.Value = &v\n\treturn s\n}", "func (s *GattDescriptor1) WriteValue(value []byte, options map[string]interface{}) *dbus.Error {\n\terr := s.config.characteristic.config.service.config.app.HandleDescriptorWrite(\n\t\ts.config.characteristic.config.service.properties.UUID, s.config.characteristic.properties.UUID,\n\t\ts.properties.UUID, value)\n\n\tif err != nil {\n\t\tif err.code == -1 {\n\t\t\t// No registered callback, so we'll just store this value\n\t\t\ts.UpdateValue(value)\n\t\t\treturn nil\n\t\t}\n\t\tdberr := dbus.NewError(err.Error(), nil)\n\t\treturn dberr\n\t}\n\n\treturn nil\n}", "func (neuron *Neuron) SetValue(x float64) {\n\tneuron.Value = &x\n}", "func (s *MetricData) SetValue(v float64) *MetricData {\n\ts.Value = &v\n\treturn s\n}", "func (n *node) setValue(value interface{}) bool {\n\tif values, ok := value.(*Values); ok {\n\t\treturn n.setValues(values)\n\t}\n\tchanged := false\n\tif n.isSet() {\n\t\tchanged = value != n.value\n\t} else {\n\t\tchanged = true\n\t}\n\tn.value = value\n\tn.children = nil\n\treturn changed\n}", "func (b *ProviderSpecApplyConfiguration) WithValue(value runtime.RawExtension) *ProviderSpecApplyConfiguration {\n\tb.Value = &value\n\treturn b\n}", "func (s *HierarchyGroupCondition) SetValue(v string) *HierarchyGroupCondition {\n\ts.Value = &v\n\treturn s\n}", "func (s *ModelMetadataFilter) SetValue(v string) *ModelMetadataFilter {\n\ts.Value = &v\n\treturn s\n}", "func (m *DiscoveredSensitiveType) SetConfidence(value *int32)() {\n err := m.GetBackingStore().Set(\"confidence\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *ResourceRequirement) SetValue(v string) *ResourceRequirement {\n\ts.Value = &v\n\treturn s\n}", "func (init *SPH_UDF_INIT) setvalue(value uintptr) {\n\t*(*uintptr)(unsafe.Pointer(&init.func_data)) = value\n}", "func Value(v float64) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldValue), v))\n\t})\n}", "func (cmd *ThrottlePosition) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsByte()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = float32(payload) / 255\n\n\treturn nil\n}", "func (s *AttachmentReference) SetValue(v string) *AttachmentReference {\n\ts.Value = &v\n\treturn s\n}", "func (m *DeviceHealthAttestationState) SetCodeIntegrityCheckVersion(value *string)() {\n err := m.GetBackingStore().Set(\"codeIntegrityCheckVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (cmd *VehicleSpeed) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsByte()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = uint32(payload)\n\n\treturn nil\n}", "func (options *UpdateCacheLevelOptions) SetValue(value string) *UpdateCacheLevelOptions {\n\toptions.Value = core.StringPtr(value)\n\treturn options\n}", "func (s *MetricDatum) SetValue(v float64) *MetricDatum {\n\ts.Value = &v\n\treturn s\n}", "func (c *cell) saveValue(v int) {\n\tc.value = v\n\tc.notifyObservers()\n}", "func (cmd *FuelPressure) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsByte()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = uint32(payload) * 3\n\n\treturn nil\n}" ]
[ "0.8194171", "0.6741127", "0.6581731", "0.64988846", "0.6003841", "0.59368724", "0.5703004", "0.5693805", "0.5605851", "0.5493374", "0.5358903", "0.53084475", "0.53084046", "0.5259993", "0.5254106", "0.51735765", "0.51641166", "0.509452", "0.5087088", "0.50843537", "0.50747174", "0.5067572", "0.50531024", "0.5045185", "0.5039265", "0.50392646", "0.5032242", "0.50211096", "0.49826464", "0.49330482", "0.49246654", "0.49003762", "0.48995844", "0.48949963", "0.48926786", "0.48869714", "0.4884057", "0.48682815", "0.4862672", "0.48599097", "0.48491803", "0.4842599", "0.48384506", "0.48369187", "0.4829272", "0.48281848", "0.4816797", "0.48159203", "0.48143867", "0.4809461", "0.47922468", "0.47899917", "0.47866008", "0.4780403", "0.47801623", "0.47763404", "0.4775028", "0.47727352", "0.477244", "0.47628707", "0.47598907", "0.47561294", "0.47541478", "0.47320038", "0.4730844", "0.47284037", "0.47191754", "0.47141618", "0.47130233", "0.4694391", "0.4692776", "0.46887425", "0.46828482", "0.46818838", "0.46735477", "0.46681154", "0.46636182", "0.46620753", "0.46518734", "0.4648086", "0.46443698", "0.4642668", "0.46407852", "0.46397614", "0.46368885", "0.46328485", "0.46323556", "0.4628834", "0.46287084", "0.46262103", "0.46250802", "0.46206757", "0.4619682", "0.46183896", "0.460803", "0.46072194", "0.46061268", "0.46059254", "0.46052292", "0.46050978" ]
0.8674166
0
SetKeyPath sets the keyPath property value. The registry key path to detect Win32 Line of Business (LoB) app
func (m *Win32LobAppRegistryDetection) SetKeyPath(value *string)() { err := m.GetBackingStore().Set("keyPath", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) SetKeyPath(value *string)() {\n m.keyPath = value\n}", "func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *Gojwt) SetPubKeyPath(path string)(){\n o.pubKeyPath = path\n}", "func (k *Keys) SealedKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn path.Join(k.dir, SealedKeysetPath)\n}", "func (k *Keys) PBEKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\treturn path.Join(k.dir, PBEKeysetPath)\n}", "func (m *Win32LobAppRegistryRule) GetKeyPath()(*string) {\n return m.keyPath\n}", "func SetPath(p string) {\n\tcurrentPath = \"\"\n\tbeginPath = p\n\tdirsAmount = 0\n}", "func (k *Item) SetPath(s string) {\n\tk.SetString(PathKey, s)\n}", "func (self *recordSet) KeyPath(key int64) (string, map[string]string) {\n var path = fmt.Sprintf(\"R%020d\", key)\n\tvar items = self.Decompose(path)\n path = fmt.Sprintf(\"%s.json\", path)\n return filepath.Join(self.RecordsPath(), path), items\n}", "func (m *Win32LobAppRegistryDetection) GetKeyPath()(*string) {\n val, err := m.GetBackingStore().Get(\"keyPath\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (c *client) SetPrivateKeyPath(path string) {\n\tc.privateKey = path\n}", "func (m *RegistryKeyState) SetKey(value *string)() {\n m.key = value\n}", "func (c *DiskCache) KeyPath(ctx context.Context, repo *gitalypb.Repository, req proto.Message) (string, error) {\n\treturn c.keyer.keyPath(ctx, repo, req)\n}", "func SetPath(newpath string) {\n\tpath = newpath\n}", "func (km *KeyManager) GetPathKey(path string, i int) (*bip32.Key, error) {\n\tkey, ok := km.getKey(path)\n\tif ok {\n\t\treturn key, nil\n\t}\n\n\tif path == \"m\" {\n\t\treturn km.getMasterKey()\n\t}\n\n\tderivationPath, err := ParseDerivationPath(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparentPath := derivationPath[:i] \t\n\tparent, err := km.GetPathKey(parentPath.toString(), i-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err = parent.NewChildKey(derivationPath[i])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkm.setKey(path, key)\n\treturn key, nil\n}", "func CertPathKey(key string) Option {\n\treturn func(ec *Envcfg) {\n\t\tec.certPathKey = key\n\t}\n}", "func getKeyPath(name string) string {\n\treturn configDir + \"/hil-vpn-\" + name + \".key\"\n}", "func SetPath(path string) {\n\tc.setPath(path)\n}", "func (o *Gojwt) SetPrivKeyPath(path string)(){\n o.privKeyPath = path\n}", "func (k *Key) ForceNewPath(path *Path) error {\n\tif !k.IsPrivate() && path.IsPrivate() {\n\t\treturn errors.New(\"path is for private key, but key is public\")\n\t}\n\n\tvar addrIdx uint32\n\tif len(path.Path) > 0 {\n\t\taddrIdx = path.Path[len(path.Path)-1]\n\t}\n\n\tkey := k.Key\n\tif k.IsPrivate() && !path.IsPrivate() {\n\t\tvar err error\n\t\tkey, err = k.Key.Neuter()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tnewKey, err := overrideBip32Sequence(key, addrIdx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*k.Key = *newKey\n\tk.Path = path\n\n\treturn nil\n}", "func (_m *requestHeaderMapUpdatable) SetPath(path string) {\n\t_m.Called(path)\n}", "func (c *Client) SetPath(path string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.path = path\n}", "func setPath(value string) {\n\tos.Setenv(pathEnvVar, value)\n}", "func (o *GetNdmpSettingsVariableParams) SetPath(path *string) {\n\to.Path = path\n}", "func (m *MicrosoftStoreForBusinessApp) SetProductKey(value *string)() {\n err := m.GetBackingStore().Set(\"productKey\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Config) KeyStorePath() string {\n\tkeystorePath := pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\treturn filepath.Join(keystorePath, \"keystore\")\n}", "func SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() // This will still keep the permissions themselves in memory\n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}", "func PathToKey(path string) (string) {\n\treturn base64.StdEncoding.EncodeToString([]byte(path))\n}", "func (k *K8S) Path() string {\n\treturn k.name + \"-root-master-key\"\n}", "func PathForKey(raw string) paths.Unencrypted {\n\treturn paths.NewUnencrypted(strings.TrimSuffix(raw, \"/\"))\n}", "func (m *GroupPolicyDefinition) SetCategoryPath(value *string)() {\n err := m.GetBackingStore().Set(\"categoryPath\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetPath(p string) error {\n\tif info, err := os.Stat(p); err != nil {\n\t\treturn err\n\t} else if !info.IsDir() {\n\t\treturn fmt.Errorf(\"path for persistence is not directory\")\n\t}\n\tdataPath = p\n\treturn nil\n}", "func TestKeyToPath(t *testing.T) {\n\ttestKey(t, \"\", \"/\")\n\ttestKey(t, \"/\", \"/\")\n\ttestKey(t, \"///\", \"/\")\n\ttestKey(t, \"hello/world/\", \"hello/world\")\n\ttestKey(t, \"///hello////world/../\", \"/hello\")\n}", "func (s *Server) SetSearchPath(ctx context.Context, paths, namespaces []string) {\n\t// Provide direct access to intercepted namespaces\n\tfor _, ns := range namespaces {\n\t\tpaths = append(paths, ns+\".svc.\"+s.clusterDomain)\n\t}\n\tselect {\n\tcase <-ctx.Done():\n\tcase s.searchPathCh <- paths:\n\t}\n}", "func (m *Resource) SetPath(name string) error {\n\tif len(m.name) > 0 {\n\t\treturn errors.New(\"name already set\")\n\t}\n\tname = strings.TrimSpace(strings.ToLower(s))\n\tmatched, err := regexp.MatchString(\"^[a-z]{4,15}$\", name)\n\tif err == nil && matched {\n\t\tm.name = name\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(\"name does not match requirements and has not been set: must be ^[a-z]{4-15}$\")\n\t}\n}", "func (b *Binary) SetPath(pathStr string) {\n\tif pathStr == \"\" {\n\t\treturn\n\t}\n\tref, err := url.Parse(pathStr)\n\tif err != nil {\n\t\treturn\n\t}\n\tb.url = b.url.ResolveReference(ref)\n}", "func (c *clientHandler) SetPath(path string) {\n\tc.path = path\n}", "func (rc RC) Path(key string) (string, bool) {\n\tv, ok := rc[key]\n\tif !ok {\n\t\treturn \"\", false\n\t} else if t := strings.TrimPrefix(v, \"~\"); t != v && (t == \"\" || t[0] == '/') {\n\t\treturn os.Getenv(\"HOME\") + t, true\n\t}\n\treturn v, true\n}", "func (k *Keys) PlaintextKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn path.Join(k.dir, PlaintextKeysetPath)\n}", "func (r *Input) SetPath(path string) error {\n\tquery, err := fetch.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Lock()\n\tr.Path = query\n\tr.Unlock()\n\treturn nil\n}", "func KBFSBinPath(runMode libkb.RunMode, binPath string) (string, error) {\n\treturn kbfsBinPathDefault(runMode, binPath)\n}", "func SetPackagePath(l *lua.LState, dir string) error {\n\treturn SetPackagePathRaw(l, PackagePath(dir))\n}", "func (f *FileStore) getPathByKey(key string) string {\n\treturn filepath.Join(f.directoryPath, key)\n}", "func (f *FileStore) getPathByKey(key string) string {\n\treturn filepath.Join(f.directoryPath, key)\n}", "func (md *MassDns) SetBinaryPath(bp string) error {\n\t// check is file/command exist\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", \"command -v \"+bp)\n\tif err := cmd.Run(); err != nil {\n\t\treturn errors.New(\"File or command not found\")\n\t}\n\n\t// set binary path\n\tmd.binaryPath = bp\n\treturn nil\n}", "func (m *MacOSSoftwareUpdateStateSummary) SetProductKey(value *string)() {\n err := m.GetBackingStore().Set(\"productKey\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Cookie) SetPath(path string) {\n\tc.path = path\n}", "func (j *JSONData) SetPath(v interface{}, path ...string) error {\n\tjson, err := sj.NewJson(j.data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjson.SetPath(path, v)\n\tbt, err := json.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\tj.data = bt\n\treturn nil\n}", "func (c *FileConfigReader) SetPath(path string) {\n\tc.path = path\n}", "func setPath(path []string, sessionID string) {\n\tdecisionTable := make(map[string][]string)\n\tdecisionTable[\"0001000100010001\"] = path\n\tDecisionTable = decisionTable\n\n\tpacketData := DecisionTableToByteArray(DecisionTable)\n\tblinkPacket := MakeBlinkPacket(\"0001000100010001\", oracleAddr, oracleAddr, DecisionTableType, packetData)\n\n\t// Send the decision table to all the nodes\n\tfor _, nodeAddrString := range nodesTable {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", nodeAddrString)\n\t\tCheckError(err)\n\n\t\t_, err = conn.WriteToUDP(blinkPacket, addr)\n\t\tCheckError(err)\n\t}\n\n\tfmt.Println(\"Paths set\")\n}", "func SaveKeyset(k *Keys, dir string) error {\n\tk.dir = dir\n\tm, err := MarshalKeys(k)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = util.WritePath(k.PlaintextKeysetPath(), m, 0700, 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetConfigPath(p string) {\n\tconfigPath = p\n}", "func (options *EditLoadBalancerMonitorOptions) SetPath(path string) *EditLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func (f *LogFile) SetPath(path string) { f.path = path }", "func (k Keeper) setValue(ctx sdk.Context, accessPath *vm_grpc.VMAccessPath, value []byte) {\n\tstore := ctx.KVStore(k.storeKey)\n\tkey := common_vm.GetPathKey(accessPath)\n\n\tstore.Set(key, value)\n}", "func (a tlsCredentials) getKeyMountPath() string {\n\tsecret := monitoringv1.SecretOrConfigMap{Secret: &a.keySecret}\n\treturn a.tlsPathForSelector(secret, \"key\")\n}", "func (k *Key) path() (string, error) {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get current user\")\n\t}\n\treturn path.Join(usr.HomeDir, *identity), nil\n}", "func (c *Quago) setPath(path string) {\n\tc.path = path\n}", "func (m *ServicePrincipalRiskDetection) SetKeyIds(value []string)() {\n err := m.GetBackingStore().Set(\"keyIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (di *directoryInfo) getPathKey(path string) (string, error) {\n\tif di.regexp == nil {\n\t\treturn \"\", errors.New(\"regexp is not set.\")\n\t}\n\n\tmatches := di.regexp.FindStringSubmatch(path)\n\tif matches != nil {\n\t\treturn matches[di.Config.MatchNum], nil\n\t} else {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"key not found. path: %s\", path))\n\t}\n}", "func (c *CmdReal) SetPath(path string) {\n\tc.cmd.Path = path\n}", "func (o *Global) SetCfgPath(v string) {\n\to.CfgPath = &v\n}", "func (hook *StackHook) SetLogPath(path string) {\n\thook.lock.Lock()\n\tdefer hook.lock.Unlock()\n\thook.path = path\n\thook.writeToFile = true\n}", "func (sb *Sandbox) SetKey(basePath string) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tlog.G(context.TODO()).Debugf(\"sandbox set key processing took %s for container %s\", time.Since(start), sb.ContainerID())\n\t}()\n\n\tif basePath == \"\" {\n\t\treturn types.InvalidParameterErrorf(\"invalid sandbox key\")\n\t}\n\n\tsb.mu.Lock()\n\tif sb.inDelete {\n\t\tsb.mu.Unlock()\n\t\treturn types.ForbiddenErrorf(\"failed to SetKey: sandbox %q delete in progress\", sb.id)\n\t}\n\toldosSbox := sb.osSbox\n\tsb.mu.Unlock()\n\n\tif oldosSbox != nil {\n\t\t// If we already have an OS sandbox, release the network resources from that\n\t\t// and destroy the OS snab. We are moving into a new home further down. Note that none\n\t\t// of the network resources gets destroyed during the move.\n\t\tif err := sb.releaseOSSbox(); err != nil {\n\t\t\tlog.G(context.TODO()).WithError(err).Error(\"Error destroying os sandbox\")\n\t\t}\n\t}\n\n\tosSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb.mu.Lock()\n\tsb.osSbox = osSbox\n\tsb.mu.Unlock()\n\n\t// If the resolver was setup before stop it and set it up in the\n\t// new osl sandbox.\n\tif oldosSbox != nil && sb.resolver != nil {\n\t\tsb.resolver.Stop()\n\n\t\tif err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil {\n\t\t\tif err := sb.resolver.Start(); err != nil {\n\t\t\t\tlog.G(context.TODO()).Errorf(\"Resolver Start failed for container %s, %q\", sb.ContainerID(), err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.G(context.TODO()).Errorf(\"Resolver Setup Function failed for container %s, %q\", sb.ContainerID(), err)\n\t\t}\n\t}\n\n\tfor _, ep := range sb.Endpoints() {\n\t\tif err = sb.populateNetworkResources(ep); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func SetConfigPath(path string) {\n\tconfigPath = path\n}", "func PathCacheKey(path []string) string {\n\t// There is probably a better way to do this, but this is working for now.\n\t// We just create an MD5 hash of all the MD5 hashes of all the path\n\t// elements. This gets us the property that it is unique per ordering.\n\thash := md5.New()\n\tfor _, p := range path {\n\t\tsingle := md5.Sum([]byte(p))\n\t\tif _, err := hash.Write(single[:]); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\treturn hex.EncodeToString(hash.Sum(nil))\n}", "func PSPath(path string) string {\n\tpsPath := path\n\tfor i, j := range map[string]string{\n\t\t`HKEY_CURRENT_USER\\`: `HKCU:`,\n\t\t`HKEY_LOCAL_MACHINE\\`: `HKLM:`,\n\t} {\n\t\tif strings.HasPrefix(path, i) {\n\t\t\tpsPath = j + path[len(i):]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn psPath\n}", "func (b *BaseBuild) Path(keys ...string) ([]string, error) {\n\tpaths := make([]string, len(keys))\n\tfor i, key := range keys {\n\t\tif path, found := b.Paths[key]; found {\n\t\t\tpaths[i] = path\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"no path for %q\", key)\n\t\t}\n\t}\n\treturn paths, nil\n}", "func SetPackagePathRaw(l *lua.LState, path string) error {\n\tl.Push(l.NewFunction(func(l *lua.LState) int {\n\t\tl.SetField(\n\t\t\tl.GetGlobal(\"package\"), \"path\",\n\t\t\tl.Get(1),\n\t\t)\n\t\treturn 0\n\t}))\n\tl.Push(lua.LString(path))\n\treturn l.PCall(1, 0, nil)\n}", "func (r *reaper) resetPath(path string) {\n\tr.pathsMtx.Lock()\n\tr.paths[path] = 0\n\tr.pathsMtx.Unlock()\n}", "func GetKeysPath() string {\n\tlocation := os.Getenv(\"SSH_KEYS_LOCATION\")\n\tif !strings.HasSuffix(location, fmt.Sprintf(\"%c\", os.PathSeparator)) {\n\t\tlocation += fmt.Sprintf(\"%c\", os.PathSeparator)\n\t}\n\treturn location\n}", "func (req *Request) SetPath(parts ...string) *Request {\n\treq.path = \"/\" + strings.Join(parts, \"/\")\n\treturn req\n}", "func newPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) {\n\treturn newPRSignedBy(keyType, keyPath, nil, nil, signedIdentity)\n}", "func (d *Fs) getPath(key string) (fPath string) {\n\tfPath = d.basePath\n\trunes := []rune(key)\n\tif len(key) > 4 {\n\t\tfPath = filepath.Join(fPath, string(runes[0:2]), string(runes[2:4]))\n\t}\n\treturn\n}", "func AppendToEnvPath(newPath string) {\n\tpath, err := getRegEnvValue(pathRegKey)\n\tif err != nil {\n\t\tlog.Fatal(\"GetStringValue\", err)\n\t}\n\tif err := saveRegEnvValue(pathRegKey, path+string(os.PathListSeparator)+newPath); err != nil {\n\t\tlog.Fatal(\"SetStringValue\", err)\n\t}\n\tsyscall.NewLazyDLL(\"user32.dll\").NewProc(\"SendMessageW\").Call(HWNDBroadcast, WMSettingChange, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(\"ENVIRONMENT\"))))\n}", "func (options *CreateLoadBalancerMonitorOptions) SetPath(path string) *CreateLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func SetRuntimePackagePath(path string) {\n\t// We're not going to check that the result is valid, we'll just accept it blindly.\n\trosPkgPath = path\n\t// Reset the message context\n\tResetContext()\n\t// All done.\n\treturn\n}", "func (c *cache) path(key string) string {\n\t// Prepend an intermediate directory of a couple of chars to make it a bit more explorable\n\treturn path.Join(c.root, string([]byte{key[0], key[1]}), key)\n}", "func (ev Vars) TLSKeyFilepath(defaults ...string) string {\n\treturn ev.String(VarTLSKeyPath, defaults...)\n}", "func CrypterFromKeyPath(armoredKeyPath string, loadPassphrase func() (string, bool)) crypto.Crypter {\n\treturn &Crypter{ArmoredKeyPath: armoredKeyPath, IsUseArmoredKeyPath: true, loadPassphrase: loadPassphrase}\n}", "func (m *RegistryKeyState) SetOldKey(value *string)() {\n m.oldKey = value\n}", "func K8sPKIPath(p string) string {\n\treturn filepath.Join(k8sPKIPath, p)\n}", "func (m *Reminder) SetChangeKey(value *string)() {\n err := m.GetBackingStore().Set(\"changeKey\", value)\n if err != nil {\n panic(err)\n }\n}", "func (rk *caIdemixRevocationKey) SetNewKey() (err error) {\n\trk.key, err = rk.idemixLib.GenerateLongTermRevocationKey()\n\treturn err\n}", "func (p *dfCollector) setProcPath(cfg interface{}) error {\n\tprocPath, err := config.GetConfigItem(cfg, \"proc_path\")\n\tif err == nil && len(procPath.(string)) > 0 {\n\t\tprocPathStats, err := os.Stat(procPath.(string))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !procPathStats.IsDir() {\n\t\t\treturn errors.New(fmt.Sprintf(\"%s is not a directory\", procPath.(string)))\n\t\t}\n\t\tp.proc_path = procPath.(string)\n\t}\n\treturn nil\n}", "func (c *Config) BindPath(path string) {\n\tc.path = append(c.path, path)\n}", "func (f *IndexFile) SetPath(path string) { f.path = path }", "func SetServerAddressBookPath(s string) func(*Server) error {\n\treturn func(c *Server) error {\n\t\tc.addressBookPath = s\n\t\treturn nil\n\t}\n}", "func (o *SamlConfigurationProperties) SetPath(v SamlConfigurationPropertyItemsArray) {\n\to.Path = &v\n}", "func (d *Diskv) ensurePath(key string) error {\n\treturn os.MkdirAll(d.pathFor(key), d.PathPerm)\n}", "func (a *PhonebookAccess1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func initPath() {\n\tAppPath, _ = os.Getwd()\n\tRootPath = strings.Replace(AppPath, \"app\", \"\", 1)\n}", "func SetLuaPath(lpath string) {\n\tlualib.SetPath(lpath)\n}", "func SetKeyHookRoutes(router *mux.Router) *mux.Router {\n\trouter.HandleFunc(\"/KeyHook\", addKey).Methods(\"POST\")\n\trouter.HandleFunc(\"/KeyHook\", getKeys).Methods(\"GET\")\n\trouter.HandleFunc(\"/KeyHook\", modifyKey).Methods(\"PUT\")\n\trouter.HandleFunc(\"/KeyHook\", removeKey).Methods(\"DELETE\")\n\treturn router\n}", "func (o *GetZippedParams) SetPath(path string) {\n\to.Path = path\n}", "func (m *Message) SetPathString(s string) {\n\tm.SetPath(strings.Split(s, \"/\"))\n}", "func (p *Resolver) SetProcessPath(fileEvent *model.FileEvent, pidCtx *model.PIDContext, ctrCtx *model.ContainerContext) (string, error) {\n\tonError := func(pathnameStr string, err error) (string, error) {\n\t\tfileEvent.SetPathnameStr(\"\")\n\t\tfileEvent.SetBasenameStr(\"\")\n\n\t\tp.pathErrStats.Inc()\n\n\t\treturn pathnameStr, err\n\t}\n\n\tif fileEvent.Inode == 0 {\n\t\treturn onError(\"\", &model.ErrInvalidKeyPath{Inode: fileEvent.Inode, MountID: fileEvent.MountID})\n\t}\n\n\tpathnameStr, err := p.pathResolver.ResolveFileFieldsPath(&fileEvent.FileFields, pidCtx, ctrCtx)\n\tif err != nil {\n\t\treturn onError(pathnameStr, err)\n\t}\n\tsetPathname(fileEvent, pathnameStr)\n\n\treturn fileEvent.PathnameStr, nil\n}", "func (c *Config) SetPath(path string) error {\n\tvar (\n\t\tisDir = false\n\t\trealPath = \"\"\n\t)\n\tif file := gres.Get(path); file != nil {\n\t\trealPath = path\n\t\tisDir = file.FileInfo().IsDir()\n\t} else {\n\t\t// Absolute path.\n\t\trealPath = gfile.RealPath(path)\n\t\tif realPath == \"\" {\n\t\t\t// Relative path.\n\t\t\tc.searchPaths.RLockFunc(func(array []string) {\n\t\t\t\tfor _, v := range array {\n\t\t\t\t\tif path, _ := gspath.Search(v, path); path != \"\" {\n\t\t\t\t\t\trealPath = path\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tif realPath != \"\" {\n\t\t\tisDir = gfile.IsDir(realPath)\n\t\t}\n\t}\n\t// Path not exist.\n\tif realPath == \"\" {\n\t\tbuffer := bytes.NewBuffer(nil)\n\t\tif c.searchPaths.Len() > 0 {\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"[gcfg] SetPath failed: cannot find directory \\\"%s\\\" in following paths:\", path))\n\t\t\tc.searchPaths.RLockFunc(func(array []string) {\n\t\t\t\tfor k, v := range array {\n\t\t\t\t\tbuffer.WriteString(fmt.Sprintf(\"\\n%d. %s\", k+1, v))\n\t\t\t\t}\n\t\t\t})\n\t\t} else {\n\t\t\tbuffer.WriteString(fmt.Sprintf(`[gcfg] SetPath failed: path \"%s\" does not exist`, path))\n\t\t}\n\t\terr := gerror.New(buffer.String())\n\t\tif errorPrint() {\n\t\t\tglog.Error(err)\n\t\t}\n\t\treturn err\n\t}\n\t// Should be a directory.\n\tif !isDir {\n\t\terr := fmt.Errorf(`[gcfg] SetPath failed: path \"%s\" should be directory type`, path)\n\t\tif errorPrint() {\n\t\t\tglog.Error(err)\n\t\t}\n\t\treturn err\n\t}\n\t// Repeated path check.\n\tif c.searchPaths.Search(realPath) != -1 {\n\t\treturn nil\n\t}\n\tc.jsonMap.Clear()\n\tc.searchPaths.Clear()\n\tc.searchPaths.Append(realPath)\n\tintlog.Print(context.TODO(), \"SetPath:\", realPath)\n\treturn nil\n}", "func KeyToPath(key string) (string) {\n\tpath, err := base64.StdEncoding.DecodeString(key)\n\tif err != nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn string(path)\n\t}\n}", "func (c classy) Path(path string) Classy {\n\tc.path = path\n\treturn c\n}" ]
[ "0.8021742", "0.67656904", "0.62937456", "0.62167495", "0.6206706", "0.6083632", "0.597346", "0.5902287", "0.58721584", "0.58346844", "0.5812029", "0.57700974", "0.5760498", "0.57318586", "0.5713192", "0.5710716", "0.57095003", "0.56565154", "0.5585007", "0.55487555", "0.55252177", "0.54303414", "0.54151154", "0.5388105", "0.53734547", "0.535818", "0.5354715", "0.53461015", "0.5343187", "0.53379273", "0.5329748", "0.531172", "0.5255996", "0.5242962", "0.52009106", "0.5198276", "0.5195721", "0.51734066", "0.51630336", "0.515815", "0.51317847", "0.5126272", "0.512215", "0.512215", "0.51217186", "0.51200163", "0.5112607", "0.5098123", "0.50923556", "0.50650877", "0.50558907", "0.5050278", "0.50244194", "0.49987006", "0.4995393", "0.4966353", "0.4955765", "0.49542585", "0.4951505", "0.49493718", "0.49453622", "0.49390227", "0.49343073", "0.49017447", "0.48929968", "0.48900416", "0.48703936", "0.4870034", "0.48660925", "0.4853604", "0.4837086", "0.48350972", "0.48334616", "0.48228082", "0.4822411", "0.48173362", "0.48160467", "0.48126844", "0.48083517", "0.47938251", "0.47900328", "0.47895375", "0.47871816", "0.47843617", "0.47816223", "0.47769496", "0.47752634", "0.4757032", "0.47505048", "0.4749327", "0.47356492", "0.47307897", "0.47232267", "0.47155043", "0.47012407", "0.46950912", "0.46842", "0.46636558", "0.4663588", "0.4662601" ]
0.8031149
0
SetOperator sets the operator property value. Contains properties for detection operator.
func (m *Win32LobAppRegistryDetection) SetOperator(value *Win32LobAppDetectionOperator)() { err := m.GetBackingStore().Set("operator", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (scsuo *SurveyCellScanUpdateOne) SetOperator(s string) *SurveyCellScanUpdateOne {\n\tscsuo.operator = &s\n\treturn scsuo\n}", "func (lc *LoggerCreate) SetOperator(s string) *LoggerCreate {\n\tlc.mutation.SetOperator(s)\n\treturn lc\n}", "func (m *Win32LobAppRegistryRule) SetOperator(value *Win32LobAppRuleOperator)() {\n m.operator = value\n}", "func (scsu *SurveyCellScanUpdate) SetOperator(s string) *SurveyCellScanUpdate {\n\tscsu.operator = &s\n\treturn scsu\n}", "func (f Filter) SetOperator(operator string) Filter {\n\tswitch operator {\n\tcase \"=\", \"!=\", \"<>\", \">=\", \"<=\", \">\", \"<\":\n\t\tf.operator = operator\n\t}\n\n\treturn f\n}", "func (m *Win32LobAppFileSystemDetection) SetOperator(value *Win32LobAppDetectionOperator)() {\n err := m.GetBackingStore().Set(\"operator\", value)\n if err != nil {\n panic(err)\n }\n}", "func (u ConstraintUpdater) SetOperator(operator string) ConstraintUpdater {\n\tu.fields[string(ConstraintDBSchema.Operator)] = operator\n\treturn u\n}", "func (s *AggregatedUtterancesFilter) SetOperator(v string) *AggregatedUtterancesFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *BotLocaleFilter) SetOperator(v string) *BotLocaleFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *BotFilter) SetOperator(v string) *BotFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AnalyticsIntentStageFilter) SetOperator(v string) *AnalyticsIntentStageFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AnalyticsUtteranceFilter) SetOperator(v string) *AnalyticsUtteranceFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AnalyticsPathFilter) SetOperator(v string) *AnalyticsPathFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AnalyticsSessionFilter) SetOperator(v string) *AnalyticsSessionFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AvailMatchingCriteria) SetOperator(v string) *AvailMatchingCriteria {\n\ts.Operator = &v\n\treturn s\n}", "func (s *AnalyticsIntentFilter) SetOperator(v string) *AnalyticsIntentFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *Filter) SetOperator(v string) *Filter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *SlotFilter) SetOperator(v string) *SlotFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *IntentFilter) SetOperator(v string) *IntentFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *PropertyFilter) SetOperator(v string) *PropertyFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *ImportFilter) SetOperator(v string) *ImportFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *ExportFilter) SetOperator(v string) *ExportFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *SlotTypeFilter) SetOperator(v string) *SlotTypeFilter {\n\ts.Operator = &v\n\treturn s\n}", "func (s *SearchExpression) SetOperator(v string) *SearchExpression {\n\ts.Operator = &v\n\treturn s\n}", "func Operator(operator string, fn ...string) Option {\n\treturn func(c *conf.Config) {\n\t\tc.Operators[operator] = append(c.Operators[operator], fn...)\n\t}\n}", "func Operator() error {\n\tif err := sh.RunV(\"mage\", \"-d\", \"operator\", \"all\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *Parser) DefineOperator(token string, operands, assoc, precedence int) {\n\tp.Operators[token] = &Operator{token, assoc, operands, precedence}\n}", "func (e *Evaluator) AddOperator(operator operators.Operator) error {\n\tif operator == nil {\n\t\treturn fmt.Errorf(\"Evaluator: added operator is empty\")\n\t}\n\tif err := e.checkUniqueness(operator.Name()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := e.cnvtr.AddOperator(operator.Name(), operator.Priority()); err != nil {\n\t\treturn err\n\t}\n\tif err := e.tknzr.AddOperator(operator.Name()); err != nil {\n\t\treturn err\n\t}\n\te.operators[operator.Name()] = operator\n\treturn nil\n}", "func (n *IfNode) SetOp(op string) {\n\tn.op = op\n}", "func (t *Tree) operator() *OperatorNode {\n\ttoken := t.expectOneOf(operators, \"operator\")\n\treturn t.newOperator(token.val, token.pos, t.list())\n}", "func (o MachineInstanceSpecClassSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MachineInstanceSpecClassSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o KubernetesClusterSpecClassSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v KubernetesClusterSpecClassSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (s *Notification) SetComparisonOperator(v string) *Notification {\n\ts.ComparisonOperator = &v\n\treturn s\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (m *Win32LobAppProductCodeDetection) SetProductVersionOperator(value *Win32LobAppDetectionOperator)() {\n err := m.GetBackingStore().Set(\"productVersionOperator\", value)\n if err != nil {\n panic(err)\n }\n}", "func (t *infixTokenizer) AddOperator(operator string) error {\n\tif err := t.checkUniqueness(operator); err != nil {\n\t\treturn err\n\t}\n\n\tt.operators[operator] = true\n\n\t_, ok := t.operatorsByLength[len(operator)]\n\tif !ok {\n\t\tt.operatorsByLength[len(operator)] = make(map[string]bool)\n\t}\n\tt.operatorsByLength[len(operator)][operator] = true\n\n\treturn nil\n}", "func (lc *LoggerCreate) SetNillableOperator(s *string) *LoggerCreate {\n\tif s != nil {\n\t\tlc.SetOperator(*s)\n\t}\n\treturn lc\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (s *SizeConstraint) SetComparisonOperator(v string) *SizeConstraint {\n\ts.ComparisonOperator = &v\n\treturn s\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (_KeepRegistry *KeepRegistryTransactor) SetOperatorContractUpgrader(opts *bind.TransactOpts, _serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _KeepRegistry.contract.Transact(opts, \"setOperatorContractUpgrader\", _serviceContract, _operatorContractUpgrader)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (f *FilterExpression) WithOperator(op string) *FilterExpression {\n\tf.Operator = op\n\treturn f\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (_Registry *RegistryTransactorSession) SetOperatorContractUpgrader(_serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _Registry.Contract.SetOperatorContractUpgrader(&_Registry.TransactOpts, _serviceContract, _operatorContractUpgrader)\n}", "func (_Registry *RegistrySession) SetOperatorContractUpgrader(_serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _Registry.Contract.SetOperatorContractUpgrader(&_Registry.TransactOpts, _serviceContract, _operatorContractUpgrader)\n}", "func (o StorageClusterSpecNodesSelectorLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecNodesSelectorLabelSelectorMatchExpressions) *string { return v.Operator }).(pulumi.StringPtrOutput)\n}", "func (_KeepRegistry *KeepRegistrySession) SetOperatorContractUpgrader(_serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _KeepRegistry.Contract.SetOperatorContractUpgrader(&_KeepRegistry.TransactOpts, _serviceContract, _operatorContractUpgrader)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (_KeepRegistry *KeepRegistryTransactorSession) SetOperatorContractUpgrader(_serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _KeepRegistry.Contract.SetOperatorContractUpgrader(&_KeepRegistry.TransactOpts, _serviceContract, _operatorContractUpgrader)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (_Registry *RegistryTransactor) SetOperatorContractUpgrader(opts *bind.TransactOpts, _serviceContract common.Address, _operatorContractUpgrader common.Address) (*types.Transaction, error) {\n\treturn _Registry.contract.Transact(opts, \"setOperatorContractUpgrader\", _serviceContract, _operatorContractUpgrader)\n}", "func (n *NVDCVEFeedJSON10DefNode) LogicalOperator() string {\n\treturn n.Operator\n}", "func (o SysbenchSpecPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SysbenchSpecPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumePersistentVolumeClaimSpecSelectorMatchExpressions) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityPodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Iperf3SpecServerConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfigPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o SchedulingNodeAffinityResponseOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SchedulingNodeAffinityResponse) string { return v.Operator }).(pulumi.StringOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFieldsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityNodeAffinityPreferredDuringSchedulingIgnoredDuringExecutionPreferenceMatchFields) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}", "func (o QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressionsOutput) Operator() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfigurationPodSchedulingAffinityPodAffinityRequiredDuringSchedulingIgnoredDuringExecutionLabelSelectorMatchExpressions) string {\n\t\treturn v.Operator\n\t}).(pulumi.StringOutput)\n}" ]
[ "0.80421716", "0.79923975", "0.791156", "0.78952646", "0.78148216", "0.7810365", "0.7804072", "0.7628318", "0.75511897", "0.7523939", "0.7450194", "0.74377996", "0.740163", "0.7357658", "0.73568285", "0.7344076", "0.7294106", "0.7279736", "0.72420436", "0.7235667", "0.7217714", "0.7196311", "0.713865", "0.7121048", "0.65359324", "0.641145", "0.6367478", "0.63540876", "0.63055253", "0.62427986", "0.62143147", "0.616835", "0.6163571", "0.6154546", "0.61381525", "0.6110781", "0.610806", "0.61020225", "0.6095539", "0.60861015", "0.6081876", "0.6078626", "0.60777557", "0.6052066", "0.6050058", "0.6018065", "0.601668", "0.60157996", "0.60088354", "0.6004477", "0.6004452", "0.6003565", "0.60021275", "0.5999426", "0.59957504", "0.5995712", "0.59956044", "0.5991028", "0.598707", "0.59815305", "0.5977441", "0.5975135", "0.59671247", "0.5964948", "0.5964482", "0.59630734", "0.5961249", "0.59603727", "0.5959892", "0.5958815", "0.59582525", "0.5953732", "0.5951796", "0.5950875", "0.59493583", "0.594752", "0.59454274", "0.59436464", "0.5938443", "0.59382766", "0.5933064", "0.5930735", "0.5930092", "0.59281623", "0.5927667", "0.5926984", "0.5925455", "0.5921946", "0.59125376", "0.59103763", "0.5910214", "0.59100604", "0.5908665", "0.59076387", "0.5906512", "0.5904858", "0.5904051", "0.5901773", "0.58989376", "0.58936036" ]
0.7785249
7
SetValueName sets the valueName property value. The registry value name
func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() { err := m.GetBackingStore().Set("valueName", value) if err != nil { panic(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Win32LobAppRegistryRule) SetValueName(value *string)() {\n m.valueName = value\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *RegistryKeyState) SetValueName(value *string)() {\n m.valueName = value\n}", "func (m *DeviceManagementConfigurationPolicy) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (k keeper) SetName(ctx sdk.Context, name string, value, string){\n\twhois := k.GetWhois(ctx, name)\n\twhois.Value = value\n\tk.SetWhois(ctx, name, whois)\n}", "func (m *CalendarGroup) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *PolicyRule) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *WorkbookNamedItem) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *WorkbookWorksheet) SetName(value *string)() {\n m.name = value\n}", "func (k Keeper) SetName(ctx sdk.Context, name string, value string) {\n\twhois := k.GetWhois(ctx, name)\n\twhois.Value = value\n\tk.SetWhois(ctx, name, whois)\n}", "func (m *DeviceManagementApplicabilityRuleOsEdition) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *LabelActionBase) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *WorkbookPivotTable) SetName(value *string)() {\n m.name = value\n}", "func (cli *SetWrapper) SetName(name string) error {\n\treturn cli.set.SetValue(fieldSetName, name)\n}", "func (m *SDKScriptCollectorAttribute) SetName(val string) {\n\n}", "func (m *AgedAccountsPayable) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (fp MockProvider) SetName(name string) {\n\tfp.faux.SetName(name)\n}", "func (m *ParentLabelDetails) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (v VirtualSwitch) SetName(newName string) error {\n\t// Get fresh settings info\n\tswitchSettingsResult, err := v.virtualSwitch.Get(\"associators_\", nil, VMSwitchSettings)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"associators_\")\n\t}\n\n\tresult, err := switchSettingsResult.ItemAtIndex(0)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"ItemAtIndex\")\n\t}\n\n\tif err := result.Set(\"ElementName\", newName); err != nil {\n\t\treturn errors.Wrap(err, \"ElementName\")\n\t}\n\n\ttext, err := result.GetText(1)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"GetText\")\n\t}\n\tif err := v.modifySwitchSettings(text); err != nil {\n\t\treturn errors.Wrap(err, \"modifySwitchSettings\")\n\t}\n\n\tif err := v.setInternalPortName(newName); err != nil {\n\t\treturn errors.Wrap(err, \"setInternalPortName\")\n\t}\n\treturn nil\n}", "func (request *DomainRegisterRequest) SetName(value *string) {\n\trequest.SetStringProperty(\"Name\", value)\n}", "func (m *DeviceCompliancePolicySettingStateSummary) SetSettingName(value *string)() {\n err := m.GetBackingStore().Set(\"settingName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Configurator) SetName(name string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.name = name\n}", "func (h *MPU6050Driver) SetName(n string) { h.name = n }", "func (p *Provider) SetName(name string) {\n\tp.name = name\n}", "func (s UserSet) SetName(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Name\", \"name\"), value)\n}", "func (m *ExternalConnection) SetName(value *string)() {\n m.name = value\n}", "func (m *RegistryKeyState) SetOldValueName(value *string)() {\n m.oldValueName = value\n}", "func SetKeyValueViaName(iName string, key_value *KeyValue) (int64, error) {\n\tkey_value.Name = iName\n\treturn Engine.Insert(key_value)\n}", "func (m *etcdMinion) SetName(name string) error {\n\tnameKey := filepath.Join(m.rootDir, \"name\")\n\topts := &etcdclient.SetOptions{\n\t\tPrevExist: etcdclient.PrevIgnore,\n\t}\n\n\t_, err := m.kapi.Set(context.Background(), nameKey, name, opts)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to set name of minion: %s\\n\", err)\n\t}\n\n\treturn err\n}", "func (w *Worker) SetName(n string) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tw.wr.name = n\n}", "func (b *TestDriver) SetName(n string) { b.name = n }", "func (d *Driver) SetName(n string) { d.name = n }", "func (css *Settings) SetName(name string) {\n\tcss.NameVal = name\n}", "func (suo *SettingUpdateOne) SetName(s string) *SettingUpdateOne {\n\tsuo.mutation.SetName(s)\n\treturn suo\n}", "func (su *SettingUpdate) SetName(s string) *SettingUpdate {\n\tsu.mutation.SetName(s)\n\treturn su\n}", "func (ms MetricDescriptor) SetName(v string) {\n\t(*ms.orig).Name = v\n}", "func (e *Element) SetName(value string) {\n\tif e.Parent != nil {\n\t\te.Parent.children.Rename(e.name, value)\n\t}\n\te.name = value\n}", "func (e *Entry) SetName(name string) {\n\tif utf8.ValidString(name) {\n\t\te.Name = name\n\t} else {\n\t\te.NameRaw = []byte(name)\n\t}\n}", "func (m *Resource) SetName(name string) error {\n\tif len(m.name) > 0 {\n\t\treturn errors.New(\"name already set\")\n\t}\n\tn := Name(name)\n\tok, err := n.IsValid()\n\tif err == nil && ok {\n\t\tm.name = n\n\t\treturn nil\n\t} else {\n\t\treturn err\n\t}\n}", "func (r *ProductRow) SetName(name string) { r.Data.Name = name }", "func (xs *Sheet) SetName(name string) {\n\txs.xb.lib.NewProc(\"xlSheetSetNameW\").\n\t\tCall(xs.self, S(name))\n}", "func (n *Node) SetName(name string) {\n\tn.name = name\n\tif n.cf != nil && n.cf.unquotedKey && (strings.IndexFunc(name, unicode.IsSpace) != -1 || strings.ContainsAny(name, \"\\\"{}\")) {\n\t\tn.cf.unquotedKey = false\n\t}\n}", "func (o *GstObj) SetName(name string) bool {\n\ts := C.CString(name)\n\tdefer C.free(unsafe.Pointer(s))\n\treturn C.gst_object_set_name(o.g(), (*C.gchar)(s)) != 0\n}", "func (m *DomainDnsSrvRecord) SetNameTarget(value *string)() {\n err := m.GetBackingStore().Set(\"nameTarget\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *SmsLogRow) SetDestinationName(value *string)() {\n err := m.GetBackingStore().Set(\"destinationName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (entry *Entry) SetName(name ndn.Name) error {\n\tnameV, _ := name.MarshalBinary()\n\tnameL := len(nameV)\n\tif nameL > MaxNameLength {\n\t\treturn fmt.Errorf(\"FIB entry name cannot exceed %d octets\", MaxNameLength)\n\t}\n\n\tc := (*CEntry)(entry)\n\tc.NameL = uint16(copy(c.NameV[:], nameV))\n\tc.NComps = uint8(len(name))\n\treturn nil\n}", "func (h *Handler) SetName(name string) {\n\th.name = name\n}", "func (m *AttachmentItem) SetName(value *string)() {\n m.name = value\n}", "func SetName(name string) {\n\tcname := C.CString(name)\n\t/*if Name() != \"\" {\n\t\tC.free(unsafe.Pointer(C.rl_readline_name))\n\t}*/\n\tC.rl_readline_name = cname\n}", "func (p *Provider) SetName(name string) {\n\tp.providerName = name\n}", "func (p *Provider) SetName(name string) {\n\tp.providerName = name\n}", "func (p *Provider) SetName(name string) {\n\tp.providerName = name\n}", "func (_ResolverContract *ResolverContractTransactor) SetName(opts *bind.TransactOpts, node [32]byte, name string) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setName\", node, name)\n}", "func SetValue(name string, value interface{}) error {\n\tif log.RootLogger().TraceEnabled() {\n\t\tlog.RootLogger().Tracef(\"Set App Value '%s': %v\", name, value)\n\t}\n\treturn appData.SetValue(name, value)\n}", "func (r *PackageRow) SetName(name string) { r.Data.Name = name }", "func (k *Kitten) SetName(name string) {\n k.Name = name\n}", "func ValueName(vName string) OptFunc {\n\treturn func(p *ByName) error {\n\t\tif vName == \"\" {\n\t\t\treturn errors.New(\"some non-empty value name must be given\")\n\t\t}\n\t\tp.valueName = vName\n\n\t\treturn nil\n\t}\n}", "func (n *FnInvNode) SetName(a string) {\n\tn.name = a\n}", "func (_Contract *ContractTransactor) SetName(opts *bind.TransactOpts, node [32]byte, name string) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"setName\", node, name)\n}", "func (m *WindowsInformationProtectionAppLearningSummary) SetApplicationName(value *string)() {\n m.applicationName = value\n}", "func (nc *NodeCreate) SetName(s string) *NodeCreate {\n\tnc.mutation.SetName(s)\n\treturn nc\n}", "func (m *ChatMessageAttachment) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_options *CreateConfigurationActionOptions) SetName(name string) *CreateConfigurationActionOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}", "func (c *Color) SetName(name string) error {\n\tnc, ok := colornames.Map[name]\n\tif !ok {\n\t\terr := fmt.Errorf(\"gi Color Name: name not found %v\", name)\n\t\tlog.Printf(\"%v\\n\", err)\n\t\treturn err\n\t}\n\tc.SetUInt8(nc.R, nc.G, nc.B, nc.A)\n\treturn nil\n}", "func (p *Parser)FuncSetValue(name string, value interface{}) string {\n\tp.parserValueMap[name] = value\n\treturn \"\"\n}", "func (xdc *XxxDemoCreate) SetName(s string) *XxxDemoCreate {\n\txdc.mutation.SetName(s)\n\treturn xdc\n}", "func SetKeyValueExpireViaName(iName string, key_value_expire *KeyValueExpire) (int64, error) {\n\tkey_value_expire.Name = iName\n\treturn Engine.Insert(key_value_expire)\n}", "func (s *serverMetricsRecorder) SetNamedMetric(name string, val float64) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.state.NamedMetrics[name] = val\n}", "func (n *Node) SetName(name string) bool {\n\tif n.Nm == name {\n\t\treturn false\n\t}\n\tn.Nm = name\n\tn.UniqueNm = name\n\tif n.Par != nil {\n\t\tn.Par.UniquifyNames()\n\t}\n\treturn true\n}", "func (n *nameHistory) SetName(oid dbutils.OID, lsn dbutils.LSN, name message.NamespacedName) {\n\tif tableHistory, ok := n.entries[oid]; !ok {\n\t\tn.entries[oid] = []nameAtLSN{{Name: name, LSN: lsn}}\n\t\tn.isChanged = true\n\t} else {\n\t\tif tableHistory[len(tableHistory)-1].Name != name {\n\t\t\tn.entries[oid] = append(n.entries[oid], nameAtLSN{Name: name, LSN: lsn})\n\t\t\tn.isChanged = true\n\t\t}\n\t}\n}", "func (self *Conn) SetName(name string) error {\n\toperation := NewOperation(self)\n\tdefer operation.Destroy()\n\n\toperation.paOper = C.pa_context_set_name(\n\t\tself.context,\n\t\tC.CString(name),\n\t\t(C.pa_context_success_cb_t)(unsafe.Pointer(C.pulse_generic_success_callback)),\n\t\toperation.Userdata(),\n\t)\n\n\treturn operation.Wait()\n}", "func (ktu *KqiTargetUpdate) SetName(s string) *KqiTargetUpdate {\n\tktu.mutation.SetName(s)\n\treturn ktu\n}", "func (s *MyTestStruct) SetName(n string) *MyTestStruct {\n\tif s.mutable {\n\t\ts.field_Name = n\n\t\treturn s\n\t}\n\n\tres := *s\n\tres.field_Name = n\n\treturn &res\n}", "func (m *WindowsUniversalAppX) SetIdentityName(value *string)() {\n m.identityName = value\n}", "func (nu *NodeUpdate) SetName(s string) *NodeUpdate {\n\tnu.mutation.SetName(s)\n\treturn nu\n}", "func (o *Partition) SetName(ctx context.Context, name string, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfacePartition+\".SetName\", 0, name, options).Store()\n\treturn\n}", "func (o *EnvironmentVariablePair1) SetName(v string) {\n\to.Name = v\n}", "func (p *BasePool) SetName(name string) {\n\tp.name = name\n}", "func (e *ObservableEditableBuffer) SetName(name string) {\n\tif e.Name() == name {\n\t\treturn\n\t}\n\n\t// SetName always forces an update of the tag.\n\t// TODO(rjk): This reset of filtertagobservers might now be unnecessary.\n\te.filtertagobservers = false\n\tbefore := e.getTagStatus()\n\tdefer e.notifyTagObservers(before)\n\n\tif e.seq > 0 {\n\t\t// TODO(rjk): Pass in the name, make the function name better reflect its purpose.\n\t\te.f.UnsetName(e.Name(), e.seq)\n\t}\n\te.setfilename(name)\n}", "func (i *Config) SetName(name string) {\n\ti.name = name\n}", "func (mnu *MetricNameUpdate) SetName(s string) *MetricNameUpdate {\n\tmnu.mutation.SetName(s)\n\treturn mnu\n}", "func (r *PackageAggRow) SetName(name string) { r.Data.Name = &name }", "func (p *MockPeer) SetName(name string) {\r\n\tp.MockName = name\r\n}", "func (_options *CreateConfigOptions) SetName(name string) *CreateConfigOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}", "func (r *PopRow) SetName(name string) { r.Data.Name = name }", "func (ggc *GithubGistCreate) SetName(s string) *GithubGistCreate {\n\tggc.mutation.SetName(s)\n\treturn ggc\n}", "func (ktuo *KqiTargetUpdateOne) SetName(s string) *KqiTargetUpdateOne {\n\tktuo.mutation.SetName(s)\n\treturn ktuo\n}", "func (nuo *NodeUpdateOne) SetName(s string) *NodeUpdateOne {\n\tnuo.mutation.SetName(s)\n\treturn nuo\n}", "func (t *Type) SetNname(n *Node)", "func (d *APA102Driver) SetName(n string) { d.name = n }", "func (kcuo *K8sContainerUpdateOne) SetName(s string) *K8sContainerUpdateOne {\n\tkcuo.mutation.SetName(s)\n\treturn kcuo\n}", "func (_ResolverContract *ResolverContractSession) SetName(node [32]byte, name string) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetName(&_ResolverContract.TransactOpts, node, name)\n}", "func (f *Flow) setName(n string) {\n\tf.Name = n\n}", "func (_options *UpdateProviderGatewayOptions) SetName(name string) *UpdateProviderGatewayOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}", "func (_options *CreateProviderGatewayOptions) SetName(name string) *CreateProviderGatewayOptions {\n\t_options.Name = core.StringPtr(name)\n\treturn _options\n}", "func (tc *TokenCreate) SetName(s string) *TokenCreate {\n\ttc.mutation.SetName(s)\n\treturn tc\n}", "func (m *WindowsInformationProtectionDeviceRegistration) SetDeviceName(value *string)() {\n err := m.GetBackingStore().Set(\"deviceName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_SweetToken *SweetTokenTransactor) SetName(opts *bind.TransactOpts, name_ string) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"setName\", name_)\n}", "func (p *MockPeer) SetName(name string) {\n\tp.MockName = name\n}", "func (h *ResourceHeader) SetName(v string) {\n\th.Metadata.SetName(v)\n}" ]
[ "0.78868264", "0.7496409", "0.73644394", "0.7253709", "0.7116289", "0.7098057", "0.7074809", "0.68688095", "0.68526214", "0.6824271", "0.6811829", "0.67920977", "0.6751485", "0.6687682", "0.6659015", "0.6655721", "0.6622989", "0.6557222", "0.6513872", "0.65062916", "0.6446837", "0.6439374", "0.640026", "0.6369397", "0.6369388", "0.63651484", "0.63225806", "0.6313041", "0.6280582", "0.6256255", "0.62013376", "0.617667", "0.6169331", "0.6161105", "0.61459076", "0.61417085", "0.60981613", "0.6081625", "0.6071155", "0.6042618", "0.6010394", "0.5984796", "0.5982058", "0.5944396", "0.5943667", "0.5935164", "0.5932839", "0.5932655", "0.5929757", "0.59297204", "0.59297204", "0.59297204", "0.59229326", "0.5917525", "0.59173477", "0.5916467", "0.5908186", "0.5900333", "0.588471", "0.58645725", "0.58598804", "0.58537567", "0.5849134", "0.58487505", "0.58369", "0.5824817", "0.5822713", "0.579261", "0.57870513", "0.5778504", "0.57767326", "0.57738155", "0.57736725", "0.57706785", "0.5760427", "0.57523215", "0.5744034", "0.5722397", "0.56914157", "0.5687847", "0.5677235", "0.56749153", "0.5669487", "0.56656003", "0.5659623", "0.56522596", "0.56487596", "0.56487244", "0.5637929", "0.56371266", "0.5625184", "0.5620691", "0.5615069", "0.56119245", "0.5609494", "0.5607742", "0.5604967", "0.5602324", "0.56002253", "0.5598659" ]
0.8065578
0
/ SignRequest uses a preshared secret to generate a signature that RTM will verify. You should set the api_sig parameter with the return value.
func SignRequest(params map[string]string) string { keys := make([]string, len(params)) for key := range params { keys = append(keys, key) } pairs := make([]string, len(keys)) sort.Strings(keys) for idx, key := range keys { pairs[idx] = key + params[key] } slug := []byte(SharedSecret + strings.Join(pairs, "")) return fmt.Sprintf("%x", md5.Sum(slug)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RPCRequest) GenerateSig(key, secret string) error {\n\tif len(key) == 0 || len(secret) == 0 {\n\t\treturn errors.New(\"You must supply an access key and an access secret\")\n\t}\n\tnonce := time.Now().UnixNano() / int64(time.Millisecond)\n\tsigString := fmt.Sprintf(\"_=%d&_ackey=%s&_acsec=%s&_action=%s\", nonce, key, secret, r.Action)\n\n\t// Append args if present\n\tif len(r.Arguments) != 0 {\n\t\tvar argsString string\n\n\t\t// We have to do this to sort by keys\n\t\tkeys := make([]string, 0, len(r.Arguments))\n\t\tfor key := range r.Arguments {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\tfor _, k := range keys {\n\t\t\tv := r.Arguments[k]\n\t\t\tvar s string\n\n\t\t\tswitch t := v.(type) {\n\t\t\tcase []SubscriptionEvent:\n\t\t\t\tvar str = make([]string, len(t))\n\t\t\t\tfor _, j := range t {\n\t\t\t\t\tstr = append(str, string(j))\n\t\t\t\t}\n\t\t\t\ts = strings.Join(str, \"\")\n\t\t\tcase []string:\n\t\t\t\ts = strings.Join(t, \"\")\n\t\t\tcase bool:\n\t\t\t\ts = strconv.FormatBool(t)\n\t\t\tcase int:\n\t\t\t\ts = strconv.FormatInt(int64(t), 10)\n\t\t\tcase int64:\n\t\t\t\ts = strconv.FormatInt(t, 10)\n\t\t\tcase float64:\n\t\t\t\ts = strconv.FormatFloat(t, 'f', -1, 64)\n\t\t\tcase string:\n\t\t\t\ts = t\n\t\t\tdefault:\n\t\t\t\t// Absolutely panic here\n\t\t\t\tpanic(fmt.Sprintf(\"Cannot generate sig string: Unable to handle arg of type %T\", t))\n\t\t\t}\n\t\t\targsString += fmt.Sprintf(\"&%s=%s\", k, s)\n\t\t}\n\t\tsigString += argsString\n\t}\n\thasher := sha256.New()\n\thasher.Write([]byte(sigString))\n\tsigHash := base64.StdEncoding.EncodeToString(hasher.Sum(nil))\n\tr.Sig = fmt.Sprintf(\"%s.%d.%s\", key, nonce, sigHash)\n\treturn nil\n}", "func (s *APISigner) Sign(r *http.Request, now time.Time) error {\n\n\tif r == nil {\n\t\treturn ErrNoRequest\n\t}\n\n\t// We expect path to begin with the version of the API, which currently\n\t// must be 1.0\n\tif !strings.HasPrefix(r.URL.Path, \"/1.0/\") {\n\t\treturn ErrRequestInvalidURL\n\t}\n\n\tk := s.accessKey\n\n\tif !k.ValidUntil(now, time.Minute) {\n\t\treturn ErrExpiredAccessKey\n\t}\n\n\tutcStr := now.UTC().Format(time.RFC3339)\n\n\tss := []string{r.Method, \"\\n\"}\n\n\thasBody := false // Body might be empty but not nil\n\tif r.Body != nil {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(b) > 0 {\n\t\t\thasBody = true\n\n\t\t\td := md5.Sum(b)\n\t\t\tmd5s := hex.EncodeToString(d[:])\n\t\t\tss = append(ss, md5s, \"\\n\")\n\t\t\tss = append(ss, RequiredContentType, \"\\n\")\n\t\t\t// As we've read the body, we have to put things back so that it can\n\t\t\t// be read again when the request is eventually sent over the wire...\n\t\t\t// See https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361#.pd96yml71\n\t\t\tr.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t}\n\t}\n\n\tif !hasBody {\n\t\tss = append(ss, \"\\n\\n\")\n\t}\n\n\tss = append(ss, utcStr, \"\\n\")\n\n\tss = append(ss, r.URL.Path)\n\n\tfingerprint := strings.Join(ss, \"\")\n\n\th := hmac.New(sha256.New, []byte(k.SecretAccessKey))\n\th.Write([]byte(fingerprint))\n\n\thStr := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n\tauth := strings.Join([]string{\"ELS \", string(k.ID), \":\", hStr}, \"\")\n\n\tr.Header.Set(\"Authorization\", auth)\n\tr.Header.Set(\"X-Els-Date\", utcStr)\n\tr.Header.Set(\"Content-Type\", RequiredContentType)\n\n\tlog.WithFields(log.Fields{\"Time\": time.Now(), \"fp\": fingerprint, \"auth\": auth, \"utcStr\": utcStr}).Debug(\"Signer: sign\")\n\n\treturn nil\n}", "func SignRequest(req *http.Request, kid string, arg interface{}, minutes int) error {\n\tif req == nil {\n\t\treturn ErrRequest\n\t} else if token, err := Sign(kid, arg, minutes); err != nil {\n\t\treturn err\n\t} else {\n\t\treq.Header.Set(HEADER_KEY(), HEADER_VALUE(token))\n\t}\n\treturn nil\n}", "func Sign(request *http.Request, accessKeyId, secretAccessKey string) *http.Request {\n\t// Step 1. create canonical request\n\t// The canonical request structure is\n\t// HTTPRequestMethod + '\\n' +\n\t// CanonicalURI + '\\n' +\n\t// CanonicalQueryString + '\\n' +\n\t// CanonicalHeaders + '\\n' +\n\t// SignedHeaders + '\\n' +\n\t// HexEncode(Hash(RequestPayload))\n\t// reference https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\tcanonicalRequestMethod := request.Method\n\n\t// Generate canonical request uri\n\turi := request.URL.Path\n\tif len(uri) == 0 {\n\t\turi = \"/\"\n\t}\n\tif strings.HasPrefix(uri, \"/\") {\n\t\turi = uri[1:]\n\t}\n\tcanonicalRequestUri := \"/\" + uriEncode(uri, false)\n\n\t// Generate canonical request query string\n\tqueryString := request.URL.Query().Encode()\n\tcanonicalQueryString := strings.Replace(queryString, \"+\", \"%20\", -1)\n\n\t// Set the headers and generate the canonical headers, signed headers and payload\n\tvar payload []byte\n\tif request.Body != nil {\n\t\tpayload, _ = ioutil.ReadAll(request.Body)\n\t\trequest.Body = ioutil.NopCloser(bytes.NewReader(payload))\n\t}\n\thashedPayload := hashSha256Hex(payload)\n\trequest.Header.Set(\"X-Amz-Content-Sha256\", hashedPayload)\n\tdate := signDateString()\n\tif request.Header.Get(\"X-Amz-Date\") == \"\" {\n\t\trequest.Header.Set(\"X-Amz-Date\", date)\n\t}\n\tif request.Header.Get(\"Content-Type\") == \"\" {\n\t\trequest.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\t}\n\trequest.Header.Set(\"Host\", request.Host)\n\n\tvar sortedHeaderKeys []string\n\tfor key, _ := range request.Header {\n\t\tswitch key {\n\t\tcase \"Content-Type\", \"Content-Md5\", \"Host\":\n\t\tdefault:\n\t\t\tif !strings.HasPrefix(key, \"X-Amz-\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tsortedHeaderKeys = append(sortedHeaderKeys, strings.ToLower(key))\n\t}\n\tsort.Strings(sortedHeaderKeys)\n\n\tvar headersToSign string\n\tfor _, key := range sortedHeaderKeys {\n\t\tvalue := strings.TrimSpace(request.Header.Get(key))\n\t\tif key == \"host\" {\n\t\t\t//AWS does not include port in signing request.\n\t\t\tif strings.Contains(value, \":\") {\n\t\t\t\tsplit := strings.Split(value, \":\")\n\t\t\t\tport := split[1]\n\t\t\t\tif port == \"80\" || port == \"443\" {\n\t\t\t\t\tvalue = split[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\theadersToSign += key + \":\" + value + \"\\n\"\n\t}\n\tsignedHeaders := strings.Join(sortedHeaderKeys, \";\")\n\tcanonicalRequest := strings.Join([]string{\n\t\tcanonicalRequestMethod,\n\t\tcanonicalRequestUri,\n\t\tcanonicalQueryString,\n\t\theadersToSign,\n\t\tsignedHeaders,\n\t\thashedPayload,\n\t}, \"\\n\")\n\thashedCanonicalRequest := hashSha256Hex([]byte(canonicalRequest))\n\n\t// Step 2. create the string to sign\n\t// StringToSign =\n\t// Algorithm + \\n +\n\t// RequestDateTime + \\n +\n\t// CredentialScope + \\n +\n\t// HashedCanonicalRequest\n\tcredentialScope := fmt.Sprintf(\"%s/%s/%s/%s\", date[:8], signRegion, signService, signRequest)\n\tstringToSign := fmt.Sprintf(\"%s\\n%s\\n%s\\n%s\",\n\t\tsignAlgorithm, date, credentialScope, hashedCanonicalRequest)\n\n\t// Step 3. calculate the signature\n\tkSecret := secretAccessKey\n\tkDate := hmacSha256([]byte(\"AWS4\"+kSecret), date[:8])\n\tkRegion := hmacSha256(kDate, signRegion)\n\tkService := hmacSha256(kRegion, signService)\n\tkSigning := hmacSha256(kService, signRequest)\n\tsignature := hex.EncodeToString(hmacSha256(kSigning, stringToSign))\n\n\t// Step 4. generate the authorization string\n\tauthorizationString := fmt.Sprintf(\"%s Credential=%s/%s, SignedHeaders=%s, Signature=%s\",\n\t\tsignAlgorithm, accessKeyId, credentialScope, signedHeaders, signature)\n\n\trequest.Header.Set(\"Authorization\", authorizationString)\n\treturn request\n}", "func (s *Signer) SignRequest(req *http.Request) error {\n\ttype param struct {\n\t\tkey, val string\n\t}\n\tvar params []string\n\tadd := func(p param) {\n\t\tparams = append(params, fmt.Sprintf(`%s=\"%s\"`, p.key, p.val))\n\t}\n\n\tvar buf bytes.Buffer\n\tgz := gzip.NewWriter(&buf)\n\tif _, err := io.WriteString(gz, s.Token); err != nil {\n\t\treturn fmt.Errorf(\"zip token: %s\", err)\n\t}\n\tif err := gz.Close(); err != nil {\n\t\treturn fmt.Errorf(\"zip token: %s\", err)\n\t}\n\tadd(param{\n\t\tkey: \"token\",\n\t\tval: base64.StdEncoding.EncodeToString(buf.Bytes()),\n\t})\n\n\tif s.Certificate != nil {\n\t\tnonce := fmt.Sprintf(\"%d:%d\", time.Now().UnixNano()/1e6, mrand.Int())\n\t\tvar body []byte\n\t\tif req.GetBody != nil {\n\t\t\tr, rerr := req.GetBody()\n\t\t\tif rerr != nil {\n\t\t\t\treturn fmt.Errorf(\"sts: getting http.Request body: %s\", rerr)\n\t\t\t}\n\t\t\tdefer r.Close()\n\t\t\tbody, rerr = ioutil.ReadAll(r)\n\t\t\tif rerr != nil {\n\t\t\t\treturn fmt.Errorf(\"sts: reading http.Request body: %s\", rerr)\n\t\t\t}\n\t\t}\n\t\tbhash := sha256.Sum256(body)\n\n\t\tport := req.URL.Port()\n\t\tif port == \"\" {\n\t\t\tport = \"80\" // Default port for the \"Host\" header on the server side\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\thost := req.URL.Hostname()\n\n\t\t// Check if the host IP is in IPv6 format. If yes, add the opening and closing square brackets.\n\t\tif isIPv6(host) {\n\t\t\thost = fmt.Sprintf(\"%s%s%s\", \"[\", host, \"]\")\n\t\t}\n\n\t\tmsg := []string{\n\t\t\tnonce,\n\t\t\treq.Method,\n\t\t\treq.URL.Path,\n\t\t\tstrings.ToLower(host),\n\t\t\tport,\n\t\t}\n\t\tfor i := range msg {\n\t\t\tbuf.WriteString(msg[i])\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t\tbuf.Write(bhash[:])\n\t\tbuf.WriteByte('\\n')\n\n\t\tsum := sha256.Sum256(buf.Bytes())\n\t\tkey, ok := s.Certificate.PrivateKey.(*rsa.PrivateKey)\n\t\tif !ok {\n\t\t\treturn errors.New(\"sts: rsa.PrivateKey is required to sign http.Request\")\n\t\t}\n\t\tsig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tadd(param{\n\t\t\tkey: \"signature_alg\",\n\t\t\tval: \"RSA-SHA256\",\n\t\t})\n\t\tadd(param{\n\t\t\tkey: \"signature\",\n\t\t\tval: base64.StdEncoding.EncodeToString(sig),\n\t\t})\n\t\tadd(param{\n\t\t\tkey: \"nonce\",\n\t\t\tval: nonce,\n\t\t})\n\t\tadd(param{\n\t\t\tkey: \"bodyhash\",\n\t\t\tval: base64.StdEncoding.EncodeToString(bhash[:]),\n\t\t})\n\t}\n\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"SIGN %s\", strings.Join(params, \", \")))\n\n\treturn nil\n}", "func GenerateSign(requestData []byte, requestTime int64, secret string) (string, error) {\n\tvar rdata map[string]interface{}\n\terr := json.Unmarshal(requestData, &rdata)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\n\tstr := serialize(rdata)\n\tserial := ext.StringSplice(secret, str.(string), secret, strconv.FormatInt(int64(requestTime), 10))\n\turlencodeSerial := url.QueryEscape(serial)\n\turlencodeBase64Serial := base64.StdEncoding.EncodeToString([]byte(urlencodeSerial))\n\tsign, err := crypto.Sha1(urlencodeBase64Serial)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\tsign, err = crypto.MD5(sign)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\n\treturn strings.ToUpper(sign), nil\n}", "func signature(req *http.Request, awsSecretAccessKey string) string {\n\treturn signWithKey(stringToSign(req), awsSecretAccessKey)\n}", "func (s *Signer) Sign(request *http.Request) error {\n\t// Calculate body checksum if body present\n\tif request.Body != http.NoBody {\n\t\tvar rawBodyBuffer bytes.Buffer\n\t\t// Duplicate any bytes read from the body so we can refill\n\t\t// the request body after reading it in order to calculate a checksum\n\t\tbody := io.TeeReader(request.Body, &rawBodyBuffer)\n\t\tvar bodyBytes []byte\n\t\tbodyBytes, err := ioutil.ReadAll(body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Calculate and set checksum based off request body\n\t\tbodyChecksum := CalculateBodyChecksum(bodyBytes)\n\t\trequest.Header.Set(ChecksumHeaderKey, bodyChecksum)\n\t\t// Refill request body with the data read\n\t\trequest.Body = ioutil.NopCloser(&rawBodyBuffer)\n\t}\n\t// Hello from Golan(d)g!\n\trequest.Header.Set(UserAgentHeaderKey, UserAgentHeaderValue)\n\t// Identify request as coming from the user identified by this API key\n\trequest.Header.Set(UserIdHeaderKey, s.apiKey)\n\t// Set request timestamp value as close to the end of this function to\n\t// minimize drift between calculation and request processing\n\trequest.Header.Set(TimestampHeaderKey, time.Now().UTC().Format(TimestampFormatString))\n\t// Calculate signature for authorizing request\n\trequestSignature, err := CalculateRequestSignature(request, *s.rawAPISecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest.Header.Set(AuthorizationHeaderKey, requestSignature)\n\treturn nil\n}", "func Sign(req *request.Request) {\n\n\t// Sets the logger for the Request to be signed\n\tlogger := req.Config.Logger\n\tif !req.Config.LogLevel.Matches(aws.LogDebug) {\n\t\tlogger = nil\n\t}\n\n\t// Obtains the IBM IAM Credentials Object\n\t// The objects includes:\n\t//\t\tIBM IAM Token\n\t//\t\tIBM IAM Service Instance ID\n\tvalue, err := req.Config.Credentials.Get()\n\tif err != nil {\n\t\tif logger != nil {\n\t\t\tlogger.Log(debugLog, signRequestHandlerLog, \"CREDENTIAL GET ERROR\", err)\n\t\t}\n\t\treq.Error = err\n\t\treq.SignedHeaderVals = nil\n\t\treturn\n\t}\n\n\t// Check the type of the Token\n\t// If does not exist, return with an error in the request\n\tif value.TokenType == \"\" {\n\t\terr = errTokenTypeNotSet\n\t\tif logger != nil {\n\t\t\tlogger.Log(debugLog, err)\n\t\t}\n\t\treq.Error = err\n\t\treq.SignedHeaderVals = nil\n\t\treturn\n\t}\n\n\t// Checks the Access Token\n\t// If does not exist, return with an error in the request\n\tif value.AccessToken == \"\" {\n\t\terr = errAccessTokenNotSet\n\t\tif logger != nil {\n\t\t\tlogger.Log(debugLog, err)\n\t\t}\n\t\treq.Error = err\n\t\treq.SignedHeaderVals = nil\n\t\treturn\n\t}\n\n\t// Get the Service Instance ID from the IBM IAM Credentials object\n\tserviceInstanceID := req.HTTPRequest.Header.Get(\"ibm-service-instance-id\")\n\tif serviceInstanceID == \"\" && value.ServiceInstanceID != \"\" {\n\t\t// Log the Service Instance ID\n\t\tif logger != nil {\n\t\t\tlogger.Log(debugLog, \"Setting the 'ibm-service-instance-id' from the Credentials\")\n\n\t\t}\n\t\treq.HTTPRequest.Header.Set(\"ibm-service-instance-id\", value.ServiceInstanceID)\n\t}\n\n\t// Use the IBM IAM Token Bearer as the Authorization Header\n\tauthString := value.TokenType + \" \" + value.AccessToken\n\treq.HTTPRequest.Header.Set(\"Authorization\", authString)\n\tif logger != nil {\n\t\tlogger.Log(debugLog, signRequestHandlerLog, \"Set Header Authorization\", authString)\n\t}\n}", "func (signer *DynamicSigner) Sign(r *http.Request) error {\n\tclaims, err := signer.ClaimsFunc()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to get claims\")\n\t}\n\n\ttoken := jwtgo.NewWithClaims(signer.Method, claims)\n\tkey, err := token.SignedString(signer.Secret)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to sign with provided secret\")\n\t}\n\n\tr.Header.Set(signer.KeyName, fmt.Sprintf(signer.KeyFormat, key))\n\treturn nil\n}", "func (pv *ParamsVerification) Sign(p []byte) string {\n\t// Generate hash code\n\tmac := hmac.New(sha256.New, []byte(pv.ClientSecret))\n\t_, _ = mac.Write(p)\n\texpectedMAC := mac.Sum(nil)\n\n\t// Generate base64\n\tbase64Sign := base64.StdEncoding.EncodeToString(expectedMAC)\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"+\", \"-\")\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"/\", \"_\")\n\tbase64Sign = strings.TrimRight(base64Sign, \"=\")\n\n\treturn base64Sign\n}", "func SignHandler(w http.ResponseWriter, r *http.Request) ErrorResponse {\n\n\t// Check that we have an authorised API key header\n\terr := checkAPIKey(r.Header.Get(\"api-key\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-api-key\", \"Invalid API key used\")\n\t\treturn ErrorInvalidAPIKey\n\t}\n\n\tif r.Body == nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"Uninitialized POST data\")\n\t\treturn ErrorNilData\n\t}\n\n\t// Read the full request body\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"error-sign-read\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\tif len(data) == 0 {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"No data supplied for signing\")\n\t\treturn ErrorEmptyData\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Use the snapd assertions module to decode the body and validate\n\tassertion, err := asserts.Decode(data)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"decode-assertion\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\n\t// Check that we have a serial-request assertion (the details will have been validated by Decode call)\n\tif assertion.Type() != asserts.SerialRequestType {\n\t\tlogMessage(\"SIGN\", \"invalid-type\", \"The assertion type must be 'serial-request'\")\n\t\treturn ErrorInvalidType\n\t}\n\n\t// Verify that the nonce is valid and has not expired\n\terr = Environ.DB.ValidateDeviceNonce(assertion.HeaderString(\"request-id\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-nonce\", \"Nonce is invalid or expired\")\n\t\treturn ErrorInvalidNonce\n\t}\n\n\t// Validate the model by checking that it exists on the database\n\tmodel, err := Environ.DB.FindModel(assertion.HeaderString(\"brand-id\"), assertion.HeaderString(\"model\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"Cannot find model with the matching brand and model\")\n\t\treturn ErrorInvalidModel\n\t}\n\n\t// Check that the model has an active keypair\n\tif !model.KeyActive {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"The model is linked with an inactive signing-key\")\n\t\treturn ErrorInactiveModel\n\t}\n\n\t// Create a basic signing log entry (without the serial number)\n\tsigningLog := SigningLog{Make: assertion.HeaderString(\"brand-id\"), Model: assertion.HeaderString(\"model\"), Fingerprint: assertion.SignKeyID()}\n\n\t// Convert the serial-request headers into a serial assertion\n\tserialAssertion, err := serialRequestToSerial(assertion, &signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"create-assertion\", err.Error())\n\t\treturn ErrorCreateAssertion\n\t}\n\n\t// Sign the assertion with the snapd assertions module\n\tsignedAssertion, err := Environ.KeypairDB.SignAssertion(asserts.SerialType, serialAssertion.Headers(), serialAssertion.Body(), model.AuthorityID, model.KeyID, model.SealedKey)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"signing-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"signing-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Store the serial number and device-key fingerprint in the database\n\terr = Environ.DB.CreateSigningLog(signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"logging-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"logging-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Return successful JSON response with the signed text\n\tformatSignResponse(true, \"\", \"\", \"\", signedAssertion, w)\n\treturn ErrorResponse{Success: true}\n}", "func sign(req *http.Request, accessKey, secretKey, signName string) {\n\tif accessKey == \"\" {\n\t\treturn\n\t}\n\ttoSign := req.Method + \"\\n\"\n\tfor _, n := range HEADER_NAMES {\n\t\ttoSign += req.Header.Get(n) + \"\\n\"\n\t}\n\tbucket := strings.Split(req.URL.Host, \".\")[0]\n\ttoSign += \"/\" + bucket + req.URL.Path\n\th := hmac.New(sha1.New, []byte(secretKey))\n\t_, _ = h.Write([]byte(toSign))\n\tsig := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\ttoken := signName + \" \" + accessKey + \":\" + sig\n\treq.Header.Add(\"Authorization\", token)\n}", "func SignRequest(xml string, privateKeyPath string) (string, error) {\n\treturn sign(xml, privateKeyPath, xmlRequestID)\n}", "func SignRequest(xml string, privateKeyPath string) (string, error) {\n\treturn sign(xml, privateKeyPath, xmlRequestID)\n}", "func (h *Handler) Sign(ctx context.Context, req *pb.SignRequest) (*pb.SignResponse, error) {\n\tlog.Trace().Msg(\"Handling request\")\n\n\tres := &pb.SignResponse{}\n\tif req == nil {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Request not specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\tif req.GetAccount() == \"\" && req.GetPublicKey() == nil {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Neither accout nor public key specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\tif !strings.Contains(req.GetAccount(), \"/\") {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Invalid account specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\n\tdata := &rules.SignData{\n\t\tDomain: req.Domain,\n\t\tData: req.Data,\n\t}\n\tresult, signature := h.signer.SignGeneric(ctx, handlers.GenerateCredentials(ctx), req.GetAccount(), req.GetPublicKey(), data)\n\tswitch result {\n\tcase core.ResultSucceeded:\n\t\tres.State = pb.ResponseState_SUCCEEDED\n\t\tres.Signature = signature\n\tcase core.ResultDenied:\n\t\tres.State = pb.ResponseState_DENIED\n\tcase core.ResultFailed:\n\t\tres.State = pb.ResponseState_FAILED\n\tdefault:\n\t\tres.State = pb.ResponseState_UNKNOWN\n\t}\n\n\tlog.Trace().Str(\"result\", \"succeeded\").Msg(\"Success\")\n\treturn res, nil\n}", "func GenSignature(w http.ResponseWriter, r *http.Request) {\n\t// Returns a Public / Private Key Pair\n\t// Uses eliptic curve cryptography\n\n\t// Generate a public / private key pair\n\tprivatekey := new(ecdsa.PrivateKey)\n\n\t// Generate an elliptic curve using NIST P-224\n\tecurve := elliptic.P224()\n\tprivatekey, err := ecdsa.GenerateKey(ecurve, rand.Reader)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Marshal the JSON\n\tprivkey, _ := json.Marshal(privatekey)\n\tpublikey, _ := json.Marshal(privatekey.Public())\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = privatekey.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"This is a test\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, privatekey, message)\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintln(w, \"Marshaled Private Key:\", string(privkey))\n\tfmt.Fprintln(w, \"Marshaled Public Key:\", string(publikey))\n\tfmt.Fprintln(w, \"Curve: \", pubkey.Curve)\n\tfmt.Fprintf(w, \"Curve: Private: %#v\\nPublic: %#v\\n\\nSignature:\\n%v\\n%v\\n\\nVerified: %v\", privatekey, pubkey, sig1, sig2, result)\n\n}", "func (o *OAuth) SignRequest(req *http.Request) *http.Request {\n\torderedParams := oauth.NewOrderedParams()\n\torderedParams.Add(\"oauth_version\", \"1.0\")\n\torderedParams.Add(\"oauth_consumer_key\", o.key)\n\torderedParams.Add(\"oauth_signature_method\", \"HMAC-SHA1\")\n\torderedParams.Add(\"oauth_timestamp\", fmt.Sprintf(\"%v\", time.Now().Unix()))\n\n\tnonce, err := o.generateNonce()\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to generate nonce: %v\", err)\n\t}\n\torderedParams.Add(\"oauth_nonce\", nonce)\n\n\tbaseString := o.baseString(req, orderedParams)\n\tsig := o.buildSignature(req, baseString)\n\n\t// Build Authorization header\n\tauthHeader := \"OAuth realm=\\\"\\\",\"\n\tvar authHeaderParams []string\n\tfor _, key := range orderedParams.Keys() {\n\t\tfor _, value := range orderedParams.Get(key) {\n\t\t\tvalString := fmt.Sprintf(\"%v=\\\"%v\\\"\", url.QueryEscape(key), url.QueryEscape(value))\n\t\t\tauthHeaderParams = append(authHeaderParams, valString)\n\t\t}\n\t}\n\tauthHeader = authHeader + strings.Join(authHeaderParams, \",\")\n\tauthHeader = authHeader + fmt.Sprintf(\",oauth_signature=\\\"%v\\\"\", sig)\n\n\treq.Header.Add(\"Authorization\", authHeader)\n\treturn req\n}", "func CalculateRequestSignature(request *http.Request, privateKey [APISecretByteLength]byte) (string, error) {\n\tmac := hmac.New(sha256.New, privateKey[:])\n\tmac.Write([]byte(fmt.Sprintf(\"%s\\n\", request.Method)))\n\tmac.Write([]byte(fmt.Sprintf(\"%s\\n\", fmt.Sprintf(\"%s\", request.URL.RequestURI()))))\n\tmac.Write([]byte(fmt.Sprintf(\"%s\\n\", request.Header.Get(ChecksumHeaderKey))))\n\tmac.Write([]byte(fmt.Sprintf(\"%s\\n\", request.Header.Get(ContentTypeHeaderKey))))\n\tmac.Write([]byte(fmt.Sprintf(\"%s\\n\", request.Header.Get(TimestampHeaderKey))))\n\trawRequestSignature := mac.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(rawRequestSignature), nil\n}", "func (client *KeyVaultClient) signCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeySignParameters, options *KeyVaultClientSignOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/{key-version}/sign\"\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\tif keyVersion == \"\" {\n\t\treturn nil, errors.New(\"parameter keyVersion cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-version}\", url.PathEscape(keyVersion))\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 GenerateSignature( resourceURL, method, consumerKey, consumerSecret string, params map[string]string ) ( signature string ){\n\t\n\tEscapeParamValues( params )\n\n\tparams[ \"oauth_nonce\" ] = GenerateNonce( 10 )\n\tparams[ \"oauth_timestamp\" ] = GetTimestamp()\n\tparams[ \"oauth_signature_method\" ] = \"HMAC-SHA1\"\n\tparams[ \"oauth_consumer_key\" ] = consumerKey\n\n\tbaseString := method\n\tbaseString += \"&\"\n\tbaseString += UrlEncode( resourceURL )\n\tbaseString += \"&\"\n\tbaseString += UrlEncode( GetOrderedParamString( params ) )\n\t\n\tsignature = HashString( []byte( UrlEncode( consumerSecret ) + \"&\" ), baseString )\n\t// log.Println( \"Signature: \", signature )\n\treturn\n}", "func (client *KeyVaultClient) signCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeySignParameters, options *KeyVaultClientSignOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}/{key-version}/sign\"\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\tif keyVersion == \"\" {\n\t\treturn nil, errors.New(\"parameter keyVersion cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-version}\", url.PathEscape(keyVersion))\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 generateSignatureFromKey(requestBody []byte, privateKey *ecdsa.PrivateKey) (string, error) {\n\t// Follows the Sila example for Golang\n\t// Generate the message hash using the Keccak 256 algorithm.\n\tmsgHash := crypto.Keccak256(requestBody)\n\n\t// Create a signature using your private key and hashed message.\n\tsigBytes, err := crypto.Sign(msgHash, privateKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// The signature just created is off by -27 from what the API\n\t// will expect. Correct that by converting the signature bytes\n\t// to a big int and adding 27.\n\tvar offset int64 = 27\n\tvar bigSig = new(big.Int).SetBytes(sigBytes)\n\tsigBytes = bigSig.Add(bigSig, big.NewInt(offset)).Bytes()\n\n\t// The big library takes out any padding, but the resultant\n\t// signature must be 130 characters (65 bytes) long. In some\n\t// cases, you might find that sigBytes now has a length of 64 or\n\t// less, so you can fix that in this way (this prepends the hex\n\t// value with \"0\" until the requisite length is reached).\n\t// Example: if two digits were required but the value was 1, you'd\n\t// pass in 01.\n\tvar sigBytesLength = 65 // length of a valid signature byte array\n\tvar arr = make([]byte, sigBytesLength)\n\tcopy(arr[(sigBytesLength-len(sigBytes)):], sigBytes)\n\n\t// Encode the bytes to a hex string.\n\treturn hex.EncodeToString(arr), nil\n}", "func (v4 Signer) Sign(ctx context.Context, r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) {\n\treturn v4.signWithBody(ctx, r, body, service, region, 0, signTime)\n}", "func (is *Signer) BuildSignature(request *http.Request) (string, error) {\n\tstringToSign, err := is.BuildStringToSign(request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\th := hmac.New(sha256.New, []byte(is.SecretAccessKey))\n\th.Write([]byte(stringToSign))\n\n\tsignature := strings.TrimSpace(base64.StdEncoding.EncodeToString(h.Sum(nil)))\n\tsignature = strings.Replace(signature, \" \", \"+\", -1)\n\tsignature = url.QueryEscape(signature)\n\n\tlogger.Debug(fmt.Sprintf(\n\t\t\"QingCloud signature: [%d] %s\",\n\t\tutils.StringToUnixInt(request.Header.Get(\"Date\"), \"RFC 822\"),\n\t\tsignature))\n\tif request.Method == \"GET\" {\n\t\tis.BuiltURL += \"&signature=\" + signature\n\t} else if request.Method == \"POST\" {\n\t\tis.BuiltForm += \"&signature=\" + signature\n\t}\n\n\treturn signature, nil\n}", "func sign(credentials Credentials, req Request, option *SignOption) string {\n\tsigningKey := getSigningKey(credentials, option)\n\treq.prepareHeaders(option)\n\tcanonicalRequest := req.canonical(option)\n\tsignature := util.HmacSha256Hex(signingKey, canonicalRequest)\n\n\treturn signature\n}", "func Sign(payload string, secretKey string) string {\n\tmac := hmac.New(sha256.New, []byte(secretKey))\n\tmac.Write([]byte(payload))\n\treturn hex.EncodeToString(mac.Sum(nil))\n}", "func (b *Base) Sign(req *SignReq) (*SignResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func CreateSignatureForRequest(method string, values *url.Values, accessKeySecret string) string {\n\n\tcanonicalizedQueryString := percentReplace(values.Encode())\n\n\tstringToSign := method + \"&\" + percentEncode(\"/\") + \"&\" + percentEncode(canonicalizedQueryString)\n\n\treturn CreateSignature(stringToSign, accessKeySecret)\n}", "func Sign(req *request.Request) {\n\t// If the request does not need to be signed ignore the signing of the\n\t// request if the AnonymousCredentials object is used.\n\tif req.Config.Credentials == credentials.AnonymousCredentials {\n\t\treturn\n\t}\n\n\tv2 := signer{\n\t\tRequest: req.HTTPRequest,\n\t\tTime: req.Time,\n\t\tCredentials: req.Config.Credentials,\n\t\tDebug: req.Config.LogLevel.Value(),\n\t\tLogger: req.Config.Logger,\n\t}\n\n\treq.Error = v2.sign()\n}", "func BuildRequestSignature(requestMethod, requestPath string, requestBody []byte) (string, string) {\n\tsecret, err := base64.StdEncoding.DecodeString(secrets.CoinbaseAPISecret())\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"base64 decoding error\"))\n\t}\n\n\ttimestamp := time.Now().Unix()\n\ttimestampStr := fmt.Sprintf(\"%d\", timestamp)\n\n\tprehashStr := timestampStr + strings.ToUpper(requestMethod) + requestPath\n\tif requestBody != nil {\n\t\tprehashStr += string(requestBody)\n\t}\n\n\tprehashBytes := []byte(prehashStr)\n\n\tmac := hmac.New(sha256.New, secret)\n\t_, err = mac.Write(prehashBytes)\n\tif err != nil {\n\t\tpanic(errors.Wrap(err, \"error attempting to write prehash bytes to hmac\"))\n\t}\n\n\tsigBytes := mac.Sum(nil)\n\n\tsigEncoded := base64.StdEncoding.EncodeToString(sigBytes)\n\n\treturn sigEncoded, timestampStr\n}", "func TestSign(w http.ResponseWriter, r *http.Request) {\n\tconf := ConfLoad()\n\n\t// Returns a Public / Private Key Pair\n\t// Read JSON config from app.yaml\n\tif v := os.Getenv(\"PRIV_KEY\"); v != \"\" {\n\t\terr := json.Unmarshal([]byte(v), &conf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%#v\", conf)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = conf.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"99999999\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintf(w, \"message: %#v\\n\\nsig1: %#v\\nsig2: %#v\", string(message[:]), sig1, sig2)\n\n}", "func (ac *AgentClient) SignRequest(key PublicKey, data []byte) ([]byte, error) {\r\n\treq := marshal(agentSignRequest, signRequestAgentMsg{\r\n\t\tKeyBlob: MarshalPublicKey(key),\r\n\t\tData: data,\r\n\t})\r\n\r\n\tmsg, msgType, err := ac.sendAndReceive(req)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tswitch msg := msg.(type) {\r\n\tcase *signResponseAgentMsg:\r\n\t\treturn msg.SigBlob, nil\r\n\tcase *failureAgentMsg:\r\n\t\treturn nil, errors.New(\"ssh: failed to sign challenge\")\r\n\t}\r\n\treturn nil, UnexpectedMessageError{agentSignResponse, msgType}\r\n}", "func (n *Notifier) sign() (v url.Values) {\n\ttimestamp := strconv.FormatInt(time.Now().Unix()*1000, 10)\n\thmacHash := hmac.New(sha256.New, []byte(n.conf.Secret))\n\thmacHash.Write([]byte(timestamp + \"\\n\" + n.conf.Secret))\n\tr := hmacHash.Sum(nil)\n\tsign := base64.StdEncoding.EncodeToString(r)\n\tv = url.Values{}\n\tv.Add(\"timestamp\", timestamp)\n\tv.Add(\"sign\", sign)\n\tv.Add(\"access_token\", n.conf.AccessToken)\n\treturn v\n}", "func (rc *Router) verifyRequest(request *http.Request) error {\n\tsigningSecret := rc.signingSecret\n\tif len(signingSecret) > 0 {\n\t\tsv, err := slack.NewSecretsVerifier(request.Header, signingSecret)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"cannot create secrets verifier\")\n\t\t}\n\n\t\t// Read the request body\n\t\tbody, err := getRequestBody(request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = sv.Write([]byte(string(body)))\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error writing body: cannot verify signature\")\n\t\t}\n\n\t\terr = sv.Ensure()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"signature validation failed\")\n\t\t}\n\t}\n\treturn nil\n}", "func GenerateSignature(url, body, key string) string {\n\tmac := hmac.New(sha1.New, []byte(key))\n\tmac.Write([]byte(url + body))\n\treturn base64.StdEncoding.EncodeToString(mac.Sum(nil))\n}", "func (ra *RestrictedAgent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {\n\treturn nil, ErrForbidden\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func SignResponse(rw http.ResponseWriter, kid string, arg interface{}, minutes int) error {\n\tif rw == nil {\n\t\treturn ErrResponse\n\t} else if token, err := Sign(kid, arg, minutes); err != nil {\n\t\treturn err\n\t} else {\n\t\trw.Header().Set(HEADER_KEY(), HEADER_VALUE(token))\n\t}\n\treturn nil\n}", "func (fi *FakeIdentity) SignIdk(req *ssp.CliRequest) {\n\treq.Client.Idk = ssp.Sqrl64.EncodeToString(fi.Idk)\n\tfi.signIdk(req)\n}", "func (client *BaseClient) GetSignature(request *tea.Request, secret string) string {\n\tstringToSign := buildRpcStringToSign(request)\n\tsignature := client.Sign(stringToSign, secret, \"&\")\n\treturn signature\n}", "func GetSignedURLFromHTTPRequest(r *http.Request) (string, error) {\n\n\tbaseURL := fmt.Sprintf(\"%s://%s\", r.URL.Scheme, r.Host)\n\toriginalURL := fmt.Sprintf(\"%s?%s\", r.URL.Path, r.URL.RawQuery)\n\n\t// Read body if exists\n\tvar body []byte\n\tvar err error\n\tif r.Body != nil {\n\t\tbody, err = ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Throw error if reserved query params are used in signature request\n\tq := r.URL.Query()\n\tif q.Get(cfg.SignatureQueryKey) != \"\" {\n\t\treturn \"\", fmt.Errorf(\"%s is a reserved query parameter when generating signed routes\", cfg.SignatureQueryKey)\n\t} else if q.Get(cfg.PrivateKeyQueryKey) != \"\" {\n\t\treturn \"\", fmt.Errorf(\"%s is a reserved query parameter when generating signed routes\", cfg.PrivateKeyQueryKey)\n\t} else if q.Get(cfg.BodyHashQueryKey) != \"\" {\n\t\treturn \"\", fmt.Errorf(\"%s is a reserved query parameter when generating signed routes\", cfg.BodyHashQueryKey)\n\t}\n\n\t// Get signature\n\tsignature, _ := getSignature(r.Method, baseURL, originalURL, body)\n\n\t// Append signature to query params\n\tq.Add(\"signature\", signature)\n\tr.URL.RawQuery = q.Encode()\n\n\treturn r.URL.String(), nil\n}", "func Sign(m string, kp *Keypair) *Signature {\n\treturn genSignature(m, kp.private)\n}", "func PostTokenRequest(param string, url string, auth model.Auth) (string, error) {\n\tlog.Infof(\"PostTokenRequest param: %s, url: %s, ak: %s\", param, url, auth.AccessKey)\n\t// construct http request\n\treq, errNewRequest := http.NewRequest(\"POST\", url, strings.NewReader(param))\n\tif errNewRequest != nil {\n\t\treturn \"\", errNewRequest\n\t}\n\n\t// request header\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(util.DATE_HEADER, time.Now().Format(util.DATE_FORMAT))\n\treq.Header.Set(\"Host\", req.Host)\n\t// calculate signature by safe algorithm\n\tsign := util.Sign{\n\t\tAccessKey: auth.AccessKey,\n\t\tSecretKey: auth.SecretKey,\n\t}\n\tauthorization, errSign := sign.GetAuthorizationValueWithSign(req)\n\tif errSign != nil {\n\t\treturn \"\", errSign\n\t}\n\treq.Header.Set(\"Authorization\", authorization)\n\n\t// send http request\n\tresponse, errDo := DoRequest(req)\n\tif errDo != nil {\n\t\treturn \"\", errDo\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err2 := ioutil.ReadAll(response.Body)\n\tif err2 != nil {\n\t\treturn \"\", err2\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\tlog.Errorf(\"response status: %s, body: %s\", response.Status, string(body))\n\t\treturn \"\", errors.New(\"request failed, status is \" + strconv.Itoa(response.StatusCode))\n\t}\n\tlog.Infof(\"response status: %s\", response.Status)\n\treturn string(body), nil\n}", "func VerifySignatureFromRequest(r *http.Request, keys []*rsa.PublicKey) error {\n\tif len(keys) == 0 {\n\t\treturn ErrNoSecret\n\t}\n\n\tif r.Body == nil {\n\t\treturn ErrNoBody\n\t}\n\n\tvar buf bytes.Buffer\n\ttee := io.TeeReader(r.Body, &buf)\n\n\tbody, err := ioutil.ReadAll(tee)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar data interface{}\n\n\terr = json.Unmarshal(body, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\theaderSignature := r.Header.Get(\"X-Pot-Signature\")\n\n\tif headerSignature == \"\" {\n\t\treturn ErrNoSignature\n\t}\n\n\terr = VerifySignature(data, headerSignature, keys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Body = ioutil.NopCloser(&buf)\n\n\treturn nil\n}", "func signV2( r *rest.Rest, accessKeyID, secretAccessKey string ) (string,error) {\n\n\t// Calculate HMAC for secretAccessKey.\n\tstringToSign := stringToSignV2( r )\n\n\thm := hmac.New(sha1.New, []byte(secretAccessKey))\n\thm.Write([]byte(stringToSign))\n\n\t// Prepare auth header.\n\tauthHeader := new(bytes.Buffer)\n\tauthHeader.WriteString(fmt.Sprintf(\"%s %s:\", signV2Algorithm, accessKeyID))\n\n\tencoder := base64.NewEncoder(base64.StdEncoding, authHeader)\n\tencoder.Write(hm.Sum(nil))\n\tencoder.Close()\n\n\t// Authorization header.\n return authHeader.String(), nil\n}", "func (v4 Signer) Presign(ctx context.Context, r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) {\n\treturn v4.signWithBody(ctx, r, body, service, region, exp, signTime)\n}", "func SignSDKRequest(req *aws.Request, opts ...func(*Signer)) {\n\t// If the request does not need to be signed ignore the signing of the\n\t// request if the AnonymousCredentials object is used.\n\tif req.Config.Credentials == aws.AnonymousCredentials {\n\t\treturn\n\t}\n\n\tregion := req.Endpoint.SigningRegion\n\tif region == \"\" {\n\t\tregion = req.Metadata.SigningRegion\n\t}\n\n\tname := req.Endpoint.SigningName\n\tif name == \"\" {\n\t\tname = req.Metadata.SigningName\n\t}\n\n\tv4 := NewSigner(req.Config.Credentials, func(v4 *Signer) {\n\t\tv4.Debug = req.Config.LogLevel\n\t\tv4.Logger = req.Config.Logger\n\t\tv4.DisableHeaderHoisting = req.NotHoist\n\t\tif name == \"s3\" {\n\t\t\t// S3 service should not have any escaping applied\n\t\t\tv4.DisableURIPathEscaping = true\n\t\t}\n\t\t// Prevents setting the HTTPRequest's Body. Since the Body could be\n\t\t// wrapped in a custom io.Closer that we do not want to be stompped\n\t\t// on top of by the signer.\n\t\tv4.DisableRequestBodyOverwrite = true\n\t})\n\n\tfor _, opt := range opts {\n\t\topt(v4)\n\t}\n\n\tsigningTime := req.Time\n\tif !req.LastSignedAt.IsZero() {\n\t\tsigningTime = req.LastSignedAt\n\t}\n\n\tsignedHeaders, err := v4.signWithBody(req.Context(), req.HTTPRequest, req.GetBody(),\n\t\tname, region, req.ExpireTime, signingTime,\n\t)\n\tif err != nil {\n\t\treq.Error = err\n\t\treq.SignedHeaderVals = nil\n\t\treturn\n\t}\n\n\treq.SignedHeaderVals = signedHeaders\n\treq.LastSignedAt = sdk.NowTime()\n}", "func (p *Proxy) SignRequest(signer cryptutil.JWTSigner) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx, span := trace.StartSpan(r.Context(), \"proxy.SignRequest\")\n\t\t\tdefer span.End()\n\t\t\ts, err := sessions.FromContext(r.Context())\n\t\t\tif err != nil {\n\t\t\t\thttputil.ErrorResponse(w, r.WithContext(ctx), httputil.Error(\"\", http.StatusForbidden, err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjwt, err := signer.SignJWT(s.User, s.Email, strings.Join(s.Groups, \",\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.FromRequest(r).Warn().Err(err).Msg(\"proxy: failed signing jwt\")\n\t\t\t} else {\n\t\t\t\tr.Header.Set(HeaderJWT, jwt)\n\t\t\t\tw.Header().Set(HeaderJWT, jwt)\n\t\t\t}\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func AddSignature(r *http.Request, created time.Time, keyID string, secret, payload []byte) {\n\tdigest := fmt.Sprintf(\"SHA-512=%x\", sha512.Sum512(payload))\n\tr.Header.Add(\"Digest\", digest)\n\n\tcreatedValue := created.Unix()\n\n\tr.Header.Add(\"Date\", created.Format(time.RFC3339))\n\n\tr.Header.Add(authorizationHeader, fmt.Sprintf(`Signature keyId=\"%s\"`, keyID))\n\tr.Header.Add(authorizationHeader, `algorithm=\"hs2019\"`)\n\tr.Header.Add(authorizationHeader, `created=`+strconv.FormatInt(createdValue, 10))\n\tr.Header.Add(authorizationHeader, `headers=\"(request-target) (created) digest\"`)\n\tsignature := signContent(secret, buildSignatureString(r, []string{requestTargetHeader, createdHeader, \"digest\"}, createdValue))\n\tr.Header.Add(authorizationHeader, fmt.Sprintf(`signature=\"%s\"`, base64.StdEncoding.EncodeToString(signature)))\n}", "func (_Ethdkg *EthdkgCallerSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func (cosigner *LocalCosigner) Sign(req CosignerSignRequest) (CosignerSignResponse, error) {\n\tcosigner.lastSignStateMutex.Lock()\n\tdefer cosigner.lastSignStateMutex.Unlock()\n\n\tres := CosignerSignResponse{}\n\tlss := cosigner.lastSignState\n\n\theight, round, step, err := UnpackHRS(req.SignBytes)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\tsameHRS, err := lss.CheckHRS(height, round, step)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\t// If the HRS is the same the sign bytes may still differ by timestamp\n\t// It is ok to re-sign a different timestamp if that is the only difference in the sign bytes\n\tif sameHRS {\n\t\tif bytes.Equal(req.SignBytes, lss.SignBytes) {\n\t\t\tres.EphemeralPublic = lss.EphemeralPublic\n\t\t\tres.Signature = lss.Signature\n\t\t\treturn res, nil\n\t\t} else if _, ok := lss.OnlyDifferByTimestamp(req.SignBytes); !ok {\n\t\t\treturn res, errors.New(\"Mismatched data\")\n\t\t}\n\n\t\t// saame HRS, and only differ by timestamp - ok to sign again\n\t}\n\n\thrsKey := HRSKey{\n\t\tHeight: height,\n\t\tRound: round,\n\t\tStep: step,\n\t}\n\tmeta, ok := cosigner.hrsMeta[hrsKey]\n\tif !ok {\n\t\treturn res, errors.New(\"No metadata at HRS\")\n\t}\n\n\tshareParts := make([]tsed25519.Scalar, 0)\n\tpublicKeys := make([]tsed25519.Element, 0)\n\n\t// calculate secret and public keys\n\tfor _, peer := range meta.Peers {\n\t\tif len(peer.Share) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tshareParts = append(shareParts, peer.Share)\n\t\tpublicKeys = append(publicKeys, peer.EphemeralSecretPublicKey)\n\t}\n\n\tephemeralShare := tsed25519.AddScalars(shareParts)\n\tephemeralPublic := tsed25519.AddElements(publicKeys)\n\n\t// check bounds for ephemeral share to avoid passing out of bounds valids to SignWithShare\n\t{\n\t\tif len(ephemeralShare) != 32 {\n\t\t\treturn res, errors.New(\"Ephemeral share is out of bounds.\")\n\t\t}\n\n\t\tvar scalarBytes [32]byte\n\t\tcopy(scalarBytes[:], ephemeralShare)\n\t\tif !edwards25519.ScMinimal(&scalarBytes) {\n\t\t\treturn res, errors.New(\"Ephemeral share is out of bounds.\")\n\t\t}\n\t}\n\n\tshare := cosigner.key.ShareKey[:]\n\tsig := tsed25519.SignWithShare(req.SignBytes, share, ephemeralShare, cosigner.pubKeyBytes, ephemeralPublic)\n\n\tcosigner.lastSignState.Height = height\n\tcosigner.lastSignState.Round = round\n\tcosigner.lastSignState.Step = step\n\tcosigner.lastSignState.EphemeralPublic = ephemeralPublic\n\tcosigner.lastSignState.Signature = sig\n\tcosigner.lastSignState.SignBytes = req.SignBytes\n\tcosigner.lastSignState.Save()\n\n\tfor existingKey := range cosigner.hrsMeta {\n\t\t// delete any HRS lower than our signed level\n\t\t// we will not be providing parts for any lower HRS\n\t\tif existingKey.Less(hrsKey) {\n\t\t\tdelete(cosigner.hrsMeta, existingKey)\n\t\t}\n\t}\n\n\tres.EphemeralPublic = ephemeralPublic\n\tres.Signature = sig\n\treturn res, nil\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func RequestVerify(req *http.Request, key Key) (*JWT, error) {\n\treturn decode(req, key)\n}", "func Sign(enrollID, enrollToken, fileName, fileContent, fileHash string) string {\n\tvar signRequest signRequest\n\tsignRequest.EnrollID = enrollID\n\tsignRequest.EnrollToken = enrollToken\n\tsignRequest.FileName = fileName\n\tsignRequest.FileContent = fileContent\n\tsignRequest.FileHash = fileHash\n\n\treqBody, err := json.Marshal(signRequest)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\turlstr := getHTTPURL(\"sign\")\n\tresponse, err := performHTTPPost(urlstr, reqBody)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tvar result restResult\n\terr = json.Unmarshal(response, &result)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif result.OK == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn result.OK\n}", "func (c *Client) GetSignature(req *http.Request) string {\n\t// Sort fcHeaders.\n\theaders := &fcHeaders{}\n\tfor k := range req.Header {\n\t\tif strings.HasPrefix(strings.ToLower(k), \"x-fc-\") {\n\t\t\theaders.Keys = append(headers.Keys, strings.ToLower(k))\n\t\t\theaders.Values = append(headers.Values, req.Header.Get(k))\n\t\t}\n\t}\n\tsort.Sort(headers)\n\tfcHeaders := \"\"\n\tfor i := range headers.Keys {\n\t\tfcHeaders += headers.Keys[i] + \":\" + headers.Values[i] + \"\\n\"\n\t}\n\n\thttpMethod := req.Method\n\tcontentMd5 := req.Header.Get(\"Content-MD5\")\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tdate := req.Header.Get(\"Date\")\n\tfcResource := req.URL.Path\n\n\tsignStr := httpMethod + \"\\n\" + contentMd5 + \"\\n\" + contentType + \"\\n\" + date + \"\\n\" + fcHeaders + fcResource\n\n\th := hmac.New(func() hash.Hash { return sha256.New() }, []byte(c.accessKeySecret))\n\t_, _ = io.WriteString(h, signStr)\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func (is *Signer) WriteSignature(request *http.Request) error {\n\t_, err := is.BuildSignature(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewRequest, err := http.NewRequest(request.Method,\n\t\trequest.URL.Scheme+\"://\"+request.URL.Host+is.BuiltURL, strings.NewReader(is.BuiltForm))\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest.URL = newRequest.URL\n\trequest.Body = newRequest.Body\n\n\tlogger.Info(fmt.Sprintf(\n\t\t\"Signed QingCloud request: [%d] %s\",\n\t\tutils.StringToUnixInt(request.Header.Get(\"Date\"), \"RFC 822\"),\n\t\trequest.URL.String()))\n\n\treturn nil\n}", "func (_Ethdkg *EthdkgSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func (self *NNTPDaemon) WrapSign(nntp NNTPMessage) {\n\tsk, ok := self.conf.daemon[\"secretkey\"]\n\tif ok {\n\t\tseed := parseTripcodeSecret(sk)\n\t\tif seed == nil {\n\t\t\tlog.Println(\"invalid secretkey will not sign\")\n\t\t} else {\n\t\t\tpk, sec := naclSeedToKeyPair(seed)\n\t\t\tsig := msgidFrontendSign(sec, nntp.MessageID())\n\t\t\tnntp.Headers().Add(\"X-Frontend-Signature\", sig)\n\t\t\tnntp.Headers().Add(\"X-Frontend-Pubkey\", hexify(pk))\n\t\t}\n\t} else {\n\t\tlog.Println(\"sending\", nntp.MessageID(), \"unsigned\")\n\t}\n}", "func Sign(plainText string, secretKey string) (sign string) {\n\thmacObj := hmac.New(sha1.New, []byte(secretKey))\n\thmacObj.Write([]byte(plainText))\n\tsignObj := string(hmacObj.Sum(nil)) + plainText\n\tsign = base64.StdEncoding.EncodeToString([]byte(signObj))\n\treturn\n}", "func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)", "func TmSign(publicKey PublicKey, privateKey PrivateKey, digest Digest) Seal { panic(\"\") }", "func (_Ethdkg *EthdkgCaller) Sign(opts *bind.CallOpts, message []byte, privK *big.Int) ([2]*big.Int, error) {\n\tvar (\n\t\tret0 = new([2]*big.Int)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"Sign\", message, privK)\n\treturn *ret0, err\n}", "func GetAuthToken(address string, pkey string, API string) (string, error) {\n var data = new(StringRes)\n // 1: Get the auth data to sign\n // ----------------------------\n res_data, err := http.Get(API+\"/AuthDatum\")\n // Data will need to be hashed\n if err != nil { return \"\", fmt.Errorf(\"Could not get authentication data: (%s)\", err) }\n body, err1 := ioutil.ReadAll(res_data.Body)\n if err != nil { return \"\", fmt.Errorf(\"Could not parse authentication data: (%s)\", err1) }\n err2 := json.Unmarshal(body, &data)\n if err2 != nil { return \"\", fmt.Errorf(\"Could not unmarshal authentication data: (%s)\", err2) }\n\n // Hash the data. Keep the byte array\n data_hash := sig.Keccak256Hash([]byte(data.Result))\n // Sign the data with the private key\n privkey, err3 := crypto.HexToECDSA(pkey)\n if err3 != nil { return \"\", fmt.Errorf(\"Could not parse private key: (%s)\", err3) }\n // Sign the auth data\n _sig, err4 := sig.Ecsign(data_hash, privkey)\n if err4 != nil { return \"\", fmt.Errorf(\"Could not sign with private key: (%s)\", err4) }\n\n // 2: Send sigature, get token\n // ---------------------\n var authdata = new(StringRes)\n var jsonStr = []byte(`{\"owner\":\"`+address+`\",\"sig\":\"0x`+_sig+`\"}`)\n res, err5 := http.Post(API+\"/Authenticate\", \"application/json\", bytes.NewBuffer(jsonStr))\n if err5 != nil { return \"\", fmt.Errorf(\"Could not hit POST /Authenticate: (%s)\", err5) }\n if res.StatusCode != 200 { return \"\", fmt.Errorf(\"(%s): Error in POST /Authenticate\", res.StatusCode)}\n body, err6 := ioutil.ReadAll(res.Body)\n if err6 != nil { return \"\" , fmt.Errorf(\"Could not read /Authenticate body: (%s)\", err6)}\n err7 := json.Unmarshal(body, &authdata)\n if err7 != nil { return \"\", fmt.Errorf(\"Could not unmarshal /Authenticate body: (%s)\", err7) }\n\n // Return the JSON web token\n return string(authdata.Result), nil\n}", "func generateSigningKey(secretKey, regionName, serviceName string, t time.Time) ([]byte, error) {\n\tkey := []byte(PreSKString + secretKey)\n\tvar err error\n\tdateStamp := t.UTC().Format(BasicDateFormatShort)\n\tdata := []string{dateStamp, regionName, serviceName, TerminationString}\n\tfor _, d := range data {\n\t\tkey, err = hmacsha256(key, d)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn key, nil\n}", "func GenerateRequestToken(proxy, uid, checkid int) (string, error) {\n\tclaims := struct {\n\t\tProxy int `json:\"proxy\"`\n\t\tID int `json:\"id\"`\n\t\tCheckID int `json:\"checkid\"`\n\t\tjwt.StandardClaims\n\t}{\n\t\tproxy,\n\t\tuid,\n\t\tcheckid,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: time.Now().Add(time.Minute * 10).Unix(),\n\t\t\tIssuer: \"Server\",\n\t\t},\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\treturn token.SignedString([]byte(os.Getenv(\"JWTSecret\")))\n}", "func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)", "func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)", "func signToken(secret []byte, token *AccessToken) (string, error) {\n\tt := accessTokenToJwt(token)\n\treturn t.SignedString(secret)\n}", "func (v *Verifier) Verify(req *http.Request, body io.Reader) error {\n\tsigHeader := req.Header.Get(\"X-Signature\")\n\tif sigHeader == \"\" {\n\t\treturn &Error{Code: 400, Message: \"Missing X-Signature header\"}\n\t}\n\n\tsig, err := ParseSignature(sigHeader)\n\tif err != nil {\n\t\treturn &Error{Code: 400, Message: \"Could not parse X-Signature header\"}\n\t}\n\n\theaderList := req.Header.Get(\"X-Signed-Headers\")\n\tif headerList == \"\" {\n\t\treturn &Error{Code: 400, Message: \"Missing X-Signed-Headers header\"}\n\t}\n\n\trt, err := time.Parse(time.RFC3339, req.Header.Get(\"Date\"))\n\tif err != nil {\n\t\treturn &Error{Code: 400, Message: \"Unable to read request date\"}\n\t}\n\n\tdelta := timeSince(rt)\n\tif delta < 0 {\n\t\tdelta = -delta\n\t}\n\n\tif delta > PermittedTimeSkew {\n\t\treturn &Error{Code: 400, Message: \"Request time skew is too great\"}\n\t}\n\n\tb, err := Canonize(req, body)\n\tif err != nil {\n\t\treturn &Error{Code: 400, Message: \"Unable to read request body\"}\n\t}\n\n\treturn sig.Validate(v.pk, b)\n}", "func (asap *ASAP) Sign(audience string, privateKey cr.PrivateKey) (token []byte, err error) {\n\treturn asap.SignCustomClaims(audience, jws.Claims{}, privateKey)\n}", "func SignV4(req http.Request, accessKey, secretAccessKey, location string, body io.Reader) *http.Request {\n\t// Signature calculation is not needed for anonymous credentials.\n\tif accessKey == \"\" || secretAccessKey == \"\" {\n\t\treturn &req\n\t}\n\n\th := sha256.New()\n\tif body != nil {\n\t\tstreamutils.StreamPipe(body, h, false, nil)\n\t}\n\treq.Header.Set(\"X-Amz-Content-Sha256\", hex.EncodeToString(h.Sum(nil)))\n\n\t// Initial time.\n\tt := time.Now().UTC()\n\n\t// Set x-amz-date.\n\treq.Header.Set(\"X-Amz-Date\", t.Format(iso8601DateFormat))\n\treq.Header.Set(\"Date\", timeutils.RFC2882Time(t))\n\n\tsignedHeaders := getSignedHeaders(req, v4IgnoredHeaders)\n\t// Get canonical request.\n\tcanonicalRequest := getCanonicalRequest(req, signedHeaders)\n\n\t// Get string to sign from canonical request.\n\tstringToSign := getStringToSignV4(t, location, canonicalRequest)\n\n\t// Get hmac signing key.\n\tsigningKey := getSigningKey(secretAccessKey, location, t)\n\n\t// Get credential string.\n\tcredential := getCredential(accessKey, location, t)\n\n\t// Calculate signature.\n\tsignature := getSignature(signingKey, stringToSign)\n\n\t// If regular request, construct the final authorization header.\n\tparts := []string{\n\t\tsignV4Algorithm + \" Credential=\" + credential,\n\t\t\"SignedHeaders=\" + strings.Join(signedHeaders, \";\"),\n\t\t\"Signature=\" + signature,\n\t}\n\n\t// Set authorization header.\n\tauth := strings.Join(parts, \",\")\n\treq.Header.Set(\"Authorization\", auth)\n\n\treturn &req\n}", "func Sign(s *big.Int, params *Params, key *PrivateKey, attrs AttributeList, message *big.Int) (*Signature, error) {\n\treturn SignPrecomputed(s, params, key, attrs, PrepareAttributeSet(params, attrs), message)\n}", "func signatureFromRequest(recent types.FileContractRevision, pbcr modules.PayByContractRequest) types.TransactionSignature {\n\treturn types.TransactionSignature{\n\t\tParentID: crypto.Hash(recent.ParentID),\n\t\tCoveredFields: types.CoveredFields{FileContractRevisions: []uint64{0}},\n\t\tPublicKeyIndex: 0,\n\t\tSignature: pbcr.Signature,\n\t}\n}", "func generateSignature(postData, secret []byte) string {\n\tmac := hmac.New(md5.New, secret)\n\tmac.Write(postData)\n\tsignature := fmt.Sprintf(\"%x\", mac.Sum(nil))\n\n\treturn signature\n}", "func (s *Signer) Sign(env soap.Envelope) ([]byte, error) {\n\tvar key *rsa.PrivateKey\n\thasKey := false\n\tif s.Certificate != nil {\n\t\tkey, hasKey = s.Certificate.PrivateKey.(*rsa.PrivateKey)\n\t\tif !hasKey {\n\t\t\treturn nil, errors.New(\"sts: rsa.PrivateKey is required\")\n\t\t}\n\t}\n\n\tcreated := time.Now().UTC()\n\theader := &internal.Security{\n\t\tWSU: internal.WSU,\n\t\tWSSE: \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\",\n\t\tTimestamp: internal.Timestamp{\n\t\t\tNS: internal.WSU,\n\t\t\tID: newID(),\n\t\t\tCreated: created.Format(internal.Time),\n\t\t\tExpires: created.Add(time.Minute).Format(internal.Time), // If STS receives this request after this, it is assumed to have expired.\n\t\t},\n\t}\n\tenv.Header.Security = header\n\n\tinfo := internal.KeyInfo{XMLName: xml.Name{Local: \"ds:KeyInfo\"}}\n\tvar c14n, body string\n\ttype requestToken interface {\n\t\tRequestSecurityToken() *internal.RequestSecurityToken\n\t}\n\n\tswitch x := env.Body.(type) {\n\tcase requestToken:\n\t\tif hasKey {\n\t\t\t// We need c14n for all requests, as its digest is included in the signature and must match on the server side.\n\t\t\t// We need the body in original form when using an ActAs or RenewTarget token, where the token and its signature are embedded in the body.\n\t\t\treq := x.RequestSecurityToken()\n\t\t\tc14n = req.C14N()\n\t\t\tbody = req.String()\n\n\t\t\tif len(s.Certificate.Certificate) == 0 {\n\t\t\t\theader.Assertion = s.Token\n\t\t\t\tif err := s.setTokenReference(&info); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tid := newID()\n\n\t\t\t\theader.BinarySecurityToken = &internal.BinarySecurityToken{\n\t\t\t\t\tEncodingType: \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\",\n\t\t\t\t\tValueType: \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\",\n\t\t\t\t\tID: id,\n\t\t\t\t\tValue: base64.StdEncoding.EncodeToString(s.Certificate.Certificate[0]),\n\t\t\t\t}\n\n\t\t\t\tinfo.SecurityTokenReference = &internal.SecurityTokenReference{\n\t\t\t\t\tReference: &internal.SecurityReference{\n\t\t\t\t\t\tURI: \"#\" + id,\n\t\t\t\t\t\tValueType: \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// When requesting HoK token for interactive user, request will have both priv. key and username/password.\n\t\tif s.user.Username() != \"\" {\n\t\t\theader.UsernameToken = &internal.UsernameToken{\n\t\t\t\tUsername: s.user.Username(),\n\t\t\t}\n\t\t\theader.UsernameToken.Password, _ = s.user.Password()\n\t\t}\n\tcase *methods.LoginByTokenBody:\n\t\theader.Assertion = s.Token\n\n\t\tif hasKey {\n\t\t\tif err := s.setTokenReference(&info); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tc14n = internal.Marshal(x.Req)\n\t\t}\n\tdefault:\n\t\t// We can end up here via ssoadmin.SessionManager.Login().\n\t\t// No other known cases where a signed request is needed.\n\t\theader.Assertion = s.Token\n\t\tif hasKey {\n\t\t\tif err := s.setTokenReference(&info); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttype Req interface {\n\t\t\t\tC14N() string\n\t\t\t}\n\t\t\tc14n = env.Body.(Req).C14N()\n\t\t}\n\t}\n\n\tif !hasKey {\n\t\treturn xml.Marshal(env) // Bearer token without key to sign\n\t}\n\n\tid := newID()\n\ttmpl := `<soap:Body xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsu=\"%s\" wsu:Id=\"%s\">%s</soap:Body>`\n\tc14n = fmt.Sprintf(tmpl, internal.WSU, id, c14n)\n\tif body == \"\" {\n\t\tbody = c14n\n\t} else {\n\t\tbody = fmt.Sprintf(tmpl, internal.WSU, id, body)\n\t}\n\n\theader.Signature = &internal.Signature{\n\t\tXMLName: xml.Name{Local: \"ds:Signature\"},\n\t\tNS: internal.DSIG,\n\t\tID: s.keyID,\n\t\tKeyInfo: info,\n\t\tSignedInfo: internal.SignedInfo{\n\t\t\tXMLName: xml.Name{Local: \"ds:SignedInfo\"},\n\t\t\tNS: internal.DSIG,\n\t\t\tCanonicalizationMethod: internal.Method{\n\t\t\t\tXMLName: xml.Name{Local: \"ds:CanonicalizationMethod\"},\n\t\t\t\tAlgorithm: \"http://www.w3.org/2001/10/xml-exc-c14n#\",\n\t\t\t},\n\t\t\tSignatureMethod: internal.Method{\n\t\t\t\tXMLName: xml.Name{Local: \"ds:SignatureMethod\"},\n\t\t\t\tAlgorithm: internal.SHA256,\n\t\t\t},\n\t\t\tReference: []internal.Reference{\n\t\t\t\tinternal.NewReference(header.Timestamp.ID, header.Timestamp.C14N()),\n\t\t\t\tinternal.NewReference(id, c14n),\n\t\t\t},\n\t\t},\n\t}\n\n\tsum := sha256.Sum256([]byte(header.Signature.SignedInfo.C14N()))\n\tsig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theader.Signature.SignatureValue = internal.Value{\n\t\tXMLName: xml.Name{Local: \"ds:SignatureValue\"},\n\t\tValue: base64.StdEncoding.EncodeToString(sig),\n\t}\n\n\treturn xml.Marshal(signedEnvelope{\n\t\tNS: \"http://schemas.xmlsoap.org/soap/envelope/\",\n\t\tHeader: *env.Header,\n\t\tBody: body,\n\t})\n}", "func SignatureV2(req *http.Request, Auth interface{}) (err error) {\n\tauth, _ := Auth.(map[string]string)\n\tqueryVals := req.URL.Query()\n\tqueryVals.Set(\"AWSAccessKeyId\", auth[\"AccessKey\"])\n\tqueryVals.Set(\"SignatureVersion\", \"2\")\n\tqueryVals.Set(\"SignatureMethod\", \"HmacSHA256\")\n\n\tqueryStr, err := canonicalQueryString(queryVals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath := req.URL.Path\n\tif path == \"\" {\n\t\tpath = \"/\"\n\t}\n\n\tpayload := new(bytes.Buffer)\n\n\tpayloadstring := checkrequestMethod(req.Method) + \"\\n\" + req.Host + \"\\n\" + path + \"\\n\" + queryStr\n\n\tfmt.Fprintf(payload, \"%s\", payloadstring)\n\n\thash := hmac.New(sha256.New, []byte(auth[\"SecretKey\"]))\n\n\thash.Write(payload.Bytes())\n\n\tsignature := make([]byte, base64.StdEncoding.EncodedLen(hash.Size()))\n\n\tbase64.StdEncoding.Encode(signature, hash.Sum(nil))\n\n\tqueryVals.Set(\"Signature\", string(signature))\n\n\treq.URL.RawQuery = queryVals.Encode()\n\n\treturn nil\n}", "func Sign(key string, qs string) string {\n\tmac := hmac.New(sha1.New, []byte(key))\n\tmac.Write([]byte(qs))\n\n\tbyteArray := mac.Sum(nil)\n\n\treturn hex.EncodeToString(byteArray)\n}", "func (a *Consensus) GenerationSignature(ctx context.Context) (string, *Response, error) {\n\tif a.options.ApiKey == \"\" {\n\t\treturn \"\", nil, NoApiKeyError\n\t}\n\n\turl, err := joinUrl(a.options.BaseUrl, \"/consensus/generationsignature\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\treq.Header.Set(\"X-API-Key\", a.options.ApiKey)\n\n\tout := make(map[string]string)\n\tresponse, err := doHttp(ctx, a.options, req, &out)\n\tif err != nil {\n\t\treturn \"\", response, err\n\t}\n\n\treturn out[\"generationSignature\"], response, nil\n}", "func GetSignature(key string, method string, req map[string]string, fcResource string) string {\n\theader := &headers{}\n\tlowerKeyHeaders := map[string]string{}\n\tfor k, v := range req {\n\t\tlowerKey := strings.ToLower(k)\n\t\tif strings.HasPrefix(lowerKey, HTTPHeaderPrefix) {\n\t\t\theader.Keys = append(header.Keys, lowerKey)\n\t\t\theader.Vals = append(header.Vals, v)\n\t\t}\n\t\tlowerKeyHeaders[lowerKey] = v\n\t}\n\tsort.Sort(header)\n\n\tfcHeaders := \"\"\n\tfor i := range header.Keys {\n\t\tfcHeaders += header.Keys[i] + \":\" + header.Vals[i] + \"\\n\"\n\t}\n\n\tdate := req[HTTPHeaderDate]\n\tif expires, ok := getExpiresFromURLQueries(fcResource); ok {\n\t\tdate = expires\n\t}\n\n\tsignStr := method + \"\\n\" + lowerKeyHeaders[strings.ToLower(HTTPHeaderContentMD5)] + \"\\n\" + lowerKeyHeaders[strings.ToLower(HTTPHeaderContentType)] + \"\\n\" + date + \"\\n\" + fcHeaders + fcResource\n\n\th := hmac.New(func() hash.Hash { return sha256.New() }, []byte(key))\n\tio.WriteString(h, signStr)\n\tsignedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n\treturn signedStr\n}", "func (obj *request) Signature() signature.Signature {\n\treturn obj.sig\n}", "func Sign(psk, uri string, post []string) ([]byte, error) {\n\tvar signString = \"\"\n\tvar hasher = hmac.New(sha256.New, []byte(psk))\n\n\tif uri[:1] != \"/\" {\n\t\turi = \"/\" + uri\n\t}\n\tif len(post) > 0 {\n\t\tfor i, v := range post {\n\t\t\tvs := strings.SplitN(v, \"=\", 2)\n\t\t\tif len(vs) != 2 {\n\t\t\t\tlog.Printf(\"%#v\", v)\n\t\t\t\tlog.Printf(\"%#v\", vs)\n\t\t\t\treturn nil, ErrInvalidPost\n\t\t\t}\n\t\t\tvs[0] = url.QueryEscape(vs[0])\n\t\t\tvs[1] = url.QueryEscape(vs[1])\n\t\t\tpost[i] = strings.Join(vs, \"=\")\n\t\t}\n\t\tsignString = url.QueryEscape(fmt.Sprintf(\"%s?%s\", uri, strings.Join(post, \"&\")))\n\t} else {\n\t\tsignString = url.QueryEscape(uri)\n\t}\n\tif _, err := hasher.Write([]byte(signString)); err != nil {\n\t\treturn nil, ErrWritingHasher\n\t}\n\treturn hasher.Sum(nil), nil\n}", "func (validator *validatorImpl) Sign(msg []byte) ([]byte, error) {\n\treturn validator.signWithEnrollmentKey(msg)\n}", "func (s *Sword) Sign(data []byte) []byte {\n\n\t// Build the payload\n\tel := base64.RawURLEncoding.EncodedLen(s.hash.Size())\n\tvar t []byte\n\n\tif s.timestamp {\n\t\tts := time.Now().Unix() - s.epoch\n\t\tetl := encodeBase58Len(ts)\n\t\tt = make([]byte, 0, len(data)+etl+el+2) // +2 for \".\" chars\n\t\tt = append(t, data...)\n\t\tt = append(t, '.')\n\t\tt = t[0 : len(t)+etl] // expand for timestamp\n\t\tencodeBase58(ts, t)\n\t} else {\n\t\tt = make([]byte, 0, len(data)+el+1)\n\t\tt = append(t, data...)\n\t}\n\n\t// Append and encode signature to token\n\tt = append(t, '.')\n\ttl := len(t)\n\tt = t[0 : tl+el]\n\n\t// Add the signature to the token\n\ts.sign(t[tl:], t[0:tl-1])\n\n\t// Return the token to the caller\n\treturn t\n}", "func Sign(message, secretKey []byte) ([]byte, error) {\n\treturn defaultPH.cryptoSign(message, secretKey)\n}", "func signV4(req *http.Request, credService awsCredentialService, theTime time.Time) error {\n\tvar body []byte\n\tif req.Body == nil {\n\t\tbody = []byte(\"\")\n\t} else {\n\t\tvar err error\n\t\tbody, err = ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"error getting request body: \" + err.Error())\n\t\t}\n\t}\n\tcreds, err := credService.credentials()\n\tif err != nil {\n\t\treturn errors.New(\"error getting AWS credentials: \" + err.Error())\n\t}\n\n\tbodyHexHash := fmt.Sprintf(\"%x\", sha256.Sum256(body))\n\n\tnow := theTime.UTC()\n\n\t// V4 signing has specific ideas of how it wants to see dates/times encoded\n\tdateNow := now.Format(\"20060102\")\n\tiso8601Now := now.Format(\"20060102T150405Z\")\n\n\t// certain mandatory headers for V4 signing\n\tawsHeaders := map[string]string{\n\t\t\"host\": req.URL.Hostname(),\n\t\t\"x-amz-content-sha256\": bodyHexHash,\n\t\t\"x-amz-date\": iso8601Now}\n\n\t// the security token header is necessary for ephemeral credentials, e.g. from\n\t// the EC2 metadata service\n\tif creds.SecurityToken != \"\" {\n\t\tawsHeaders[\"x-amz-security-token\"] = creds.SecurityToken\n\t}\n\n\t// ref. https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html\n\n\t// the \"canonical request\" is the normalized version of the AWS service access\n\t// that we're attempting to perform; in this case, a GET from an S3 bucket\n\tcanonicalReq := req.Method + \"\\n\" // HTTP method\n\tcanonicalReq += req.URL.EscapedPath() + \"\\n\" // URI-escaped path\n\tcanonicalReq += \"\\n\" // query string; not implemented\n\n\t// include the values for the signed headers\n\torderedKeys := sortKeys(awsHeaders)\n\tfor _, k := range orderedKeys {\n\t\tcanonicalReq += k + \":\" + awsHeaders[k] + \"\\n\"\n\t}\n\tcanonicalReq += \"\\n\" // linefeed to terminate headers\n\n\t// include the list of the signed headers\n\theaderList := strings.Join(orderedKeys, \";\")\n\tcanonicalReq += headerList + \"\\n\"\n\tcanonicalReq += bodyHexHash\n\n\t// the \"string to sign\" is a time-bounded, scoped request token which\n\t// is linked to the \"canonical request\" by inclusion of its SHA-256 hash\n\tstrToSign := \"AWS4-HMAC-SHA256\\n\" // V4 signing with SHA-256 HMAC\n\tstrToSign += iso8601Now + \"\\n\" // ISO 8601 time\n\tstrToSign += dateNow + \"/\" + creds.RegionName + \"/s3/aws4_request\\n\" // scoping for signature\n\tstrToSign += fmt.Sprintf(\"%x\", sha256.Sum256([]byte(canonicalReq))) // SHA-256 of canonical request\n\n\t// the \"signing key\" is generated by repeated HMAC-SHA256 based on the same\n\t// scoping that's included in the \"string to sign\"; but including the secret key\n\t// to allow AWS to validate it\n\tsigningKey := sha256MAC([]byte(dateNow), []byte(\"AWS4\"+creds.SecretKey))\n\tsigningKey = sha256MAC([]byte(creds.RegionName), signingKey)\n\tsigningKey = sha256MAC([]byte(\"s3\"), signingKey)\n\tsigningKey = sha256MAC([]byte(\"aws4_request\"), signingKey)\n\n\t// the \"signature\" is finally the \"string to sign\" signed by the \"signing key\"\n\tsignature := sha256MAC([]byte(strToSign), signingKey)\n\n\t// required format of Authorization header; n.b. the access key corresponding to\n\t// the secret key is included here\n\tauthHdr := \"AWS4-HMAC-SHA256 Credential=\" + creds.AccessKey + \"/\" + dateNow\n\tauthHdr += \"/\" + creds.RegionName + \"/s3/aws4_request,\"\n\tauthHdr += \"SignedHeaders=\" + headerList + \",\"\n\tauthHdr += \"Signature=\" + fmt.Sprintf(\"%x\", signature)\n\n\t// add the computed Authorization\n\treq.Header.Add(\"Authorization\", authHdr)\n\n\t// populate the other signed headers into the request\n\tfor _, k := range orderedKeys {\n\t\treq.Header.Add(k, awsHeaders[k])\n\t}\n\n\treturn nil\n}", "func (d *Dao) sign(params url.Values) (query string, err error) {\n\ttmp := params.Encode()\n\tsignTmp := d.encode(params)\n\tif strings.IndexByte(tmp, '+') > -1 {\n\t\ttmp = strings.Replace(tmp, \"+\", \"%20\", -1)\n\t}\n\tvar b bytes.Buffer\n\tb.WriteString(d.c.Berserker.Secret)\n\tb.WriteString(signTmp)\n\tb.WriteString(d.c.Berserker.Secret)\n\tmh := md5.Sum(b.Bytes())\n\t// query\n\tvar qb bytes.Buffer\n\tqb.WriteString(tmp)\n\tqb.WriteString(\"&sign=\")\n\tqb.WriteString(strings.ToUpper(hex.EncodeToString(mh[:])))\n\tquery = qb.String()\n\treturn\n}", "func (m *MetricsProvider) SignerSign(value time.Duration) {\n}", "func (s Signer) Sign(url string, expires int, options SignOptions) (string, error) {\n\tif expires == 0 {\n\t\tdefaultAge, _ := time.ParseDuration(fmt.Sprintf(\"%ds\", s.GetDefaultAge()))\n\t\texpires = int(time.Now().Add(defaultAge).Unix())\n\t}\n\n\tqueryParams, marshalError := qs.Marshal(makeQueryParams(s, url, expires, options))\n\n\tif marshalError != nil {\n\t\treturn \"\", marshalError\n\t}\n\n\treturn fmt.Sprintf(\"%s?%s\", url, queryParams), nil\n}", "func (s *SigningMethodGCPJWTImpl) Sign(signingString string, key interface{}) (string, error) {\n\tvar ctx context.Context\n\n\t// check to make sure the key is a context.Context\n\tswitch k := key.(type) {\n\tcase context.Context:\n\t\tctx = k\n\tdefault:\n\t\treturn \"\", jwt.ErrInvalidKey\n\t}\n\n\t// Get the IAMSignBlobConfig from the context\n\tconfig, ok := FromContextJWT(ctx)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"IAMSignJWTConfig missing from provided context!\")\n\t}\n\n\t// Default config.OAuth2HTTPClient is a google.DefaultClient\n\tif config.OAuth2HTTPClient == nil {\n\t\tc, err := getDefaultOauthClient(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tconfig.OAuth2HTTPClient = c\n\t}\n\n\t// Default the ProjectID to a wildcard\n\tif config.ProjectID == \"\" {\n\t\tconfig.ProjectID = \"-\"\n\t}\n\n\t// Prepare the call\n\t// First decode the JSON string and discard the header\n\tparts := strings.Split(signingString, \".\")\n\tif len(parts) != 2 {\n\t\treturn \"\", fmt.Errorf(\"expected a 2 part string to sign, but got %d instead\", len(parts))\n\t}\n\tjwtClaimSet, err := jwt.DecodeSegment(parts[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignReq := &iam.SignJwtRequest{Payload: string(jwtClaimSet)}\n\tname := fmt.Sprintf(\"projects/%s/serviceAccounts/%s\", config.ProjectID, config.ServiceAccount)\n\n\t// Do the call\n\tiamService, err := iam.New(config.OAuth2HTTPClient)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignResp, err := iamService.Projects.ServiceAccounts.SignJwt(name, signReq).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Check the response\n\tif signResp.HTTPStatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"unexpected response code from signing request, expected %d but got %d instead\", http.StatusOK, signResp.HTTPStatusCode)\n\t}\n\n\treturn signResp.SignedJwt, nil\n}", "func getSigningKey(secret, loc string, t time.Time) []byte {\n\tdate := sumHMAC([]byte(\"AWS4\"+secret), []byte(t.Format(yyyymmdd)))\n\tlocation := sumHMAC(date, []byte(loc))\n\tservice := sumHMAC(location, []byte(\"s3\"))\n\tsigningKey := sumHMAC(service, []byte(\"aws4_request\"))\n\treturn signingKey\n}", "func VerifyRequestSignature(xml string, publicCertPath string) error {\n\treturn verify(xml, publicCertPath, xmlRequestID)\n}", "func Call(context *Context, params Params) (r []byte, err error) {\n\tparams.Sign(context)\n\tr, err = Post(context, params.GetQuery())\n\treturn\n}", "func (k otherKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {\n\t_, _, _ = rand, digest, opts\n\treturn nil, nil\n}", "func (r *Reservation) SignatureVerify(pk string, sig []byte) error {\n\tkey, err := crypto.KeyFromHex(pk)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invalid verification key\")\n\t}\n\n\tvar buf bytes.Buffer\n\tif _, err := buf.WriteString(fmt.Sprint(int64(r.ID))); err != nil {\n\t\treturn errors.Wrap(err, \"failed to write id to buffer\")\n\t}\n\n\tif _, err := buf.WriteString(r.Json); err != nil {\n\t\treturn errors.Wrap(err, \"failed to write json to buffer\")\n\t}\n\n\treturn crypto.Verify(key, buf.Bytes(), sig)\n}", "func (rec *Recorder) Start(secret *string) error {\n\tcurrentTime := strconv.FormatInt(time.Now().Unix(), 10)\n\n\tvar requestBody string\n\tif secret != nil && *secret != \"\" {\n\t\trequestBody = fmt.Sprintf(`\n\t\t{\n\t\t\t\"cname\": \"%s\",\n\t\t\t\"uid\": \"%d\",\n\t\t\t\"clientRequest\": {\n\t\t\t\t\"token\": \"%s\",\n\t\t\t\t\"recordingConfig\": {\n\t\t\t\t\t\"maxIdleTime\": 30,\n\t\t\t\t\t\"streamTypes\": 2,\n\t\t\t\t\t\"channelType\": 1,\n\t\t\t\t\t\"decryptionMode\": 1,\n\t\t\t\t\t\"secret\": \"%s\",\n\t\t\t\t\t\"transcodingConfig\": {\n\t\t\t\t\t\t\"height\": 720, \n\t\t\t\t\t\t\"width\": 1280,\n\t\t\t\t\t\t\"bitrate\": 2260, \n\t\t\t\t\t\t\"fps\": 15, \n\t\t\t\t\t\t\"mixedVideoLayout\": 1,\n\t\t\t\t\t\t\"backgroundColor\": \"#000000\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"storageConfig\": {\n\t\t\t\t\t\"vendor\": 1, \n\t\t\t\t\t\"region\": 0,\n\t\t\t\t\t\"bucket\": \"%s\",\n\t\t\t\t\t\"accessKey\": \"%s\",\n\t\t\t\t\t\"secretKey\": \"%s\",\n\t\t\t\t\t\"fileNamePrefix\": [\"%s\", \"%s\"]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, rec.Channel, rec.UID, rec.Token, *secret, viper.GetString(\"BUCKET_NAME\"),\n\t\t\tviper.GetString(\"BUCKET_ACCESS_KEY\"), viper.GetString(\"BUCKET_ACCESS_SECRET\"),\n\t\t\trec.Channel, currentTime)\n\t} else {\n\t\trequestBody = fmt.Sprintf(`\n\t\t{\n\t\t\t\"cname\": \"%s\",\n\t\t\t\"uid\": \"%d\",\n\t\t\t\"clientRequest\": {\n\t\t\t\t\"token\": \"%s\",\n\t\t\t\t\"recordingConfig\": {\n\t\t\t\t\t\"maxIdleTime\": 30,\n\t\t\t\t\t\"streamTypes\": 2,\n\t\t\t\t\t\"channelType\": 1,\n\t\t\t\t\t\"transcodingConfig\": {\n\t\t\t\t\t\t\"height\": 720, \n\t\t\t\t\t\t\"width\": 1280,\n\t\t\t\t\t\t\"bitrate\": 2260, \n\t\t\t\t\t\t\"fps\": 15, \n\t\t\t\t\t\t\"mixedVideoLayout\": 1,\n\t\t\t\t\t\t\"backgroundColor\": \"#000000\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\"storageConfig\": {\n\t\t\t\t\t\"vendor\": 1, \n\t\t\t\t\t\"region\": 0,\n\t\t\t\t\t\"bucket\": \"%s\",\n\t\t\t\t\t\"accessKey\": \"%s\",\n\t\t\t\t\t\"secretKey\": \"%s\",\n\t\t\t\t\t\"fileNamePrefix\": [\"%s\", \"%s\"]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, rec.Channel, rec.UID, rec.Token, viper.GetString(\"BUCKET_NAME\"),\n\t\t\tviper.GetString(\"BUCKET_ACCESS_KEY\"), viper.GetString(\"BUCKET_ACCESS_SECRET\"),\n\t\t\trec.Channel, currentTime)\n\t}\n\n\treq, err := http.NewRequest(\"POST\", \"https://api.agora.io/v1/apps/\"+viper.GetString(\"APP_ID\")+\"/cloud_recording/resourceid/\"+rec.RID+\"/mode/mix/start\",\n\t\tbytes.NewBuffer([]byte(requestBody)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(viper.GetString(\"CUSTOMER_ID\"), viper.GetString(\"CUSTOMER_CERTIFICATE\"))\n\n\tresp, err := rec.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tvar result map[string]string\n\tjson.NewDecoder(resp.Body).Decode(&result)\n\trec.SID = result[\"sid\"]\n\n\treturn nil\n}", "func transactionSign(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusMethodNotAllowed, \"\")\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tif r.Header.Get(\"Content-Type\") != ContentTypeJSON {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusUnsupportedMediaType, \"\")\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tvar req TransactionSignRequest\n\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusBadRequest, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tif err := req.validate(); err != nil {\n\t\t\tlogger.WithError(err).Error(\"invalid sign transaction request\")\n\t\t\tresp := NewHTTPErrorResponse(http.StatusBadRequest, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\ttxnInputs, txnOutputs, err := req.TransactionParams()\n\t\tif err != nil {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusUnprocessableEntity, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\t// for integration tests\n\t\tif autoPressEmulatorButtons {\n\t\t\terr := gateway.SetAutoPressButton(true, skyWallet.ButtonRight)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"transactionSign failed: %s\", err.Error())\n\t\t\t\tresp := NewHTTPErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t\t\twriteHTTPResponse(w, resp)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvar msg wire.Message\n\t\tretCH := make(chan int)\n\t\terrCH := make(chan int)\n\t\tctx := r.Context()\n\n\t\tgo func() {\n\t\t\tmsg, err = gateway.TransactionSign(txnInputs, txnOutputs)\n\t\t\tif err != nil {\n\t\t\t\terrCH <- 1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tretCH <- 1\n\t\t}()\n\n\t\tselect {\n\t\tcase <-retCH:\n\t\t\tHandleFirmwareResponseMessages(w, msg)\n\t\tcase <-errCH:\n\t\t\tlogger.Errorf(\"transactionSign failed: %s\", err.Error())\n\t\t\tresp := NewHTTPErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\tcase <-ctx.Done():\n\t\t\tdisConnErr := gateway.Disconnect()\n\t\t\tif disConnErr != nil {\n\t\t\t\tresp := NewHTTPErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t\t\twriteHTTPResponse(w, resp)\n\t\t\t} else {\n\t\t\t\tresp := NewHTTPErrorResponse(499, \"Client Closed Request\")\n\t\t\t\twriteHTTPResponse(w, resp)\n\t\t\t}\n\t\t}\n\t}\n}", "func createSignature(c *Credentials, formattedShortTime, stringToSign string) string {\n\th1 := makeHmac([]byte(\"AWS4\"+c.SecretAccessKey), []byte(formattedShortTime))\n\th2 := makeHmac(h1, []byte(c.Region))\n\th3 := makeHmac(h2, []byte(\"s3\"))\n\th4 := makeHmac(h3, []byte(\"aws4_request\"))\n\tsignature := makeHmac(h4, []byte(stringToSign))\n\treturn hex.EncodeToString(signature)\n}" ]
[ "0.6788081", "0.67776895", "0.6675929", "0.6542208", "0.63614374", "0.6207327", "0.61996496", "0.61905056", "0.6190193", "0.6114812", "0.6018926", "0.59692407", "0.59104216", "0.58937895", "0.58937895", "0.58688444", "0.5864342", "0.5819719", "0.58161354", "0.57641745", "0.5754926", "0.57498395", "0.56787765", "0.56532925", "0.56272674", "0.561861", "0.5603575", "0.5555403", "0.55528975", "0.5544066", "0.552134", "0.55148405", "0.55142397", "0.5482396", "0.54760987", "0.5439908", "0.54295677", "0.5428098", "0.5428098", "0.5425236", "0.5414456", "0.5404935", "0.5382273", "0.53686666", "0.5334122", "0.53313375", "0.5330267", "0.5318372", "0.5295145", "0.52893203", "0.52778715", "0.5275949", "0.52542275", "0.5249438", "0.52448523", "0.5242796", "0.5241275", "0.5237034", "0.52334416", "0.5232081", "0.52229565", "0.519513", "0.5195072", "0.5194922", "0.51763517", "0.5175825", "0.516071", "0.5147021", "0.5131556", "0.5131556", "0.51194274", "0.51161486", "0.5112329", "0.5110485", "0.5109149", "0.5105782", "0.5103133", "0.50751317", "0.50475705", "0.5039705", "0.5031629", "0.5030871", "0.50281465", "0.5023963", "0.5018974", "0.5015644", "0.50113344", "0.5011189", "0.500133", "0.49920395", "0.49849623", "0.49785075", "0.49713346", "0.49407187", "0.4935407", "0.49340895", "0.49331093", "0.4925789", "0.49256912", "0.491784" ]
0.6311796
5
/ FormURL creates a URL that you can use for making API requests or authenticating your users.
func FormURL(baseURL string, method string, params map[string]string) *url.URL { u, err := url.Parse(baseURL) if err != nil { log.Fatalf("Failed to set root URL: %s\n", err) } params["method"] = method params["format"] = "json" log.WithField("params", params).Debug("got arguments for request") query := u.Query() for key, value := range params { query.Set(key, value) } query.Set("api_sig", SignRequest(params)) u.RawQuery = query.Encode() log.Debugf("creating URL: %s", u) return u }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func URLform(url, body string) (result string) {\n\tresult = fmt.Sprintf(`[%s](%s)`, body, url)\n\treturn\n}", "func (c *Client) URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error {\n\tif len(qv) == 0 {\n\t\treturn fmt.Errorf(\"URLFormCall() requires qv to have non-zero length\")\n\t}\n\n\tif err := c.checkResp(reflect.ValueOf(resp)); err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse path URL(%s): %w\", endpoint, err)\n\t}\n\n\theaders := http.Header{}\n\theaders.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\taddStdHeaders(headers)\n\n\tenc := qv.Encode()\n\n\treq := &http.Request{\n\t\tMethod: http.MethodPost,\n\t\tURL: u,\n\t\tHeader: headers,\n\t\tContentLength: int64(len(enc)),\n\t\tBody: io.NopCloser(strings.NewReader(enc)),\n\t\tGetBody: func() (io.ReadCloser, error) {\n\t\t\treturn io.NopCloser(strings.NewReader(enc)), nil\n\t\t},\n\t}\n\n\tdata, err := c.do(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv := reflect.ValueOf(resp)\n\tif err := c.checkResp(v); err != nil {\n\t\treturn err\n\t}\n\n\tvar unmarshal = json.Unmarshal\n\tif _, ok := v.Elem().Type().FieldByName(\"AdditionalFields\"); ok {\n\t\tunmarshal = customJSON.Unmarshal\n\t}\n\tif resp != nil {\n\t\tif err := unmarshal(data, resp); err != nil {\n\t\t\treturn fmt.Errorf(\"json decode error: %w\\nraw message was: %s\", err, string(data))\n\t\t}\n\t}\n\treturn nil\n}", "func (a Auth) URL() string {\n\tu := url.URL{}\n\tu.Host = oauthHost\n\tu.Scheme = oauthScheme\n\tu.Path = oauthPath\n\n\tif len(a.RedirectURI) == 0 {\n\t\ta.RedirectURI = oauthRedirectURI\n\t}\n\tif len(a.ResponseType) == 0 {\n\t\ta.ResponseType = oauthResponseType\n\t}\n\tif len(a.Display) == 0 {\n\t\ta.Display = oauthDisplay\n\t}\n\n\tvalues := u.Query()\n\tvalues.Add(paramResponseType, a.ResponseType)\n\tvalues.Add(paramScope, a.Scope.String())\n\tvalues.Add(paramAppID, int64s(a.ID))\n\tvalues.Add(paramRedirectURI, a.RedirectURI)\n\tvalues.Add(paramVersion, defaultVersion)\n\tvalues.Add(paramDisplay, a.Display)\n\tu.RawQuery = values.Encode()\n\n\treturn u.String()\n}", "func PostForm(url string, data url.Values) (resp *http.Response, err error) {\n\treturn DefaultClient.PostForm(url, data)\n}", "func PostForm(url string, data url.Values) (resp *http.Response, err error) {\n\treturn DefaultClient.PostForm(url, data)\n}", "func PostURL(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"POST URL\")\n\n\t// Generate key for storage\n\turlKey := GenerateKey(false)\n\n\twriteURLInfo(w, r, urlKey, http.StatusCreated)\n}", "func (r *Request) URLf(format string, args ...interface{}) *Request {\n\tr.url = fmt.Sprintf(format, args...)\n\treturn r\n}", "func PostForm(ctx context.Context, url string, u url.Values) (int, string) {\n\treturn Call(ctx, http.MethodPost, url, strings.NewReader(u.Encode()))\n}", "func PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn DefaultClient.PostForm(url, data)\n}", "func CreateURL(base string, args map[string][]string) string {\r\n\tu, _ := url.Parse(base)\r\n\tq := u.Query()\r\n\r\n\tfor arg, vals := range args {\r\n\t\tfor _, val := range vals {\r\n\t\t\tq.Add(arg, val)\r\n\t\t}\r\n\t}\r\n\r\n\tu.RawQuery = q.Encode()\r\n\treturn u.String()\r\n}", "func (config *TOTPConfig) generateURL(label string) string {\n\tsecret := config.ExportKey()\n\tu := url.URL{}\n\tv := url.Values{}\n\tu.Scheme = \"otpauth\"\n\tu.Host = \"totp\"\n\tu.Path = label\n\tv.Add(\"secret\", secret)\n\tif config.Size != totpDefaultDigits {\n\t\tv.Add(\"digits\", fmt.Sprintf(\"%d\", config.Size))\n\t}\n\n\t// If other hash algorithms become supported in Google\n\t// Authenticator, enable these.\n\t// switch {\n\t// case config.Algo == crypto.SHA256:\n\t// \tv.Add(\"algorithm\", \"SHA256\")\n\t// case config.Algo == crypto.SHA512:\n\t// \tv.Add(\"algorithm\", \"SHA512\")\n\t// }\n\n\tif config.Provider != \"\" {\n\t\tv.Add(\"provider\", config.Provider)\n\t}\n\n\tu.RawQuery = v.Encode()\n\treturn u.String()\n}", "func (c *client) createURL(urlPath string, query url.Values) string {\n\tu := c.endpoint\n\tu.Path = urlPath\n\tif query != nil {\n\t\tu.RawQuery = query.Encode()\n\t}\n\treturn u.String()\n}", "func PostForm(ctx context.Context, url string, data url.Values) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"POST\", url, strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq = req.WithContext(ctx)\n\n\treturn http.DefaultClient.Do(req)\n}", "func (a *AWSSigv4) CreateURL() string {\n\n\tqs := a.QueryString\n\tver := apisVersion[a.Svc]\n\thostname := a.Svc + \".\" + a.Region + \".\" + a.AWSDomain\n\n\turl := a.Scheme + \"://\" + hostname + a.URI\n\tif a.Method == \"GET\" {\n\t\tif qs != \"\" {\n\t\t\tqs += \"&\"\n\t\t}\n\t\tqs += \"Action=\" + kebabToCamelCase(a.Action)\n\t\tqs += \"&Version=\" + ver\n\t\turl += \"?\" + qs\n\n\t\ta.QueryString = qs\n\t}\n\n\treturn url\n}", "func (a *API) PostForm(path string, data url.Values) (resp *http.Response, err error) {\n\tu, err := url.ParseRequestURI(a.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu.Path = path\n\n\treturn a.Client.PostForm(u.String(), data)\n}", "func (c *Client) PostForm(url string, data url.Values) (*Response, error) {\n\treturn c.Post(url, \"application/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n}", "func URL(scheme, fqdn string) *apis.URL {\n\treturn &apis.URL{\n\t\tScheme: scheme,\n\t\tHost: fqdn,\n\t}\n}", "func MakeForm(method string, base, path string, params url.Values, headers http.Header) *http.Request {\n\treturn EncodeForm(&http.Request{\n\t\tMethod: method,\n\t\tURL: URL(base, path, nil),\n\t\tHeader: headers,\n\t}, params)\n}", "func formatSignInURL(signInToken string) (*url.URL, error) {\n\tissuer := defaultIssuer\n\n\tsignInFederationURL, err := url.Parse(federationEndpointURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigninParams := url.Values{}\n\n\tsigninParams.Add(\"Action\", \"login\")\n\tsigninParams.Add(\"Destination\", awsConsoleURL)\n\tsigninParams.Add(\"Issuer\", issuer)\n\tsigninParams.Add(\"SigninToken\", signInToken)\n\n\tsignInFederationURL.RawQuery = signinParams.Encode()\n\n\treturn signInFederationURL, nil\n}", "func buildURL(t *Tickets, u string) string {\n\turl := \"\"\n\turl = fmt.Sprintf(\"%s?hapikey=%s\", u, t.APIKey)\n\n\tif t.OffSet > 0 {\n\t\turl = fmt.Sprintf(\"%s&offset=%d\", url, t.OffSet)\n\t}\n\n\tfor idx := range t.Properties {\n\t\turl = fmt.Sprintf(\"%s&properties=%s\", url, t.Properties[idx])\n\t}\n\n\treturn url\n}", "func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {\n\treturn nil, gerror.NewCode(\n\t\tgcode.CodeNotSupported,\n\t\t`PostForm is not supported, please use Post instead`,\n\t)\n}", "func (c Client) AuthURL(state string) string {\n\tvalues := url.Values{\"client_id\": {c.ISS}, \"state\": {\"state\"}, \"response_type\": {\"code\"}}\n\treturn fmt.Sprintf(\"%s?%s\", c.Endpoint.AuthURL, values.Encode())\n}", "func (dm *Datamuse) URL() string {\n\treturn dm.apiURL.String()\n}", "func (input *BeegoInput) URL() string {\n\treturn input.Context.Request.URL.Path\n}", "func (r CreateRequest) URL() string {\n\treturn \"v3/campaigns\"\n}", "func (client *HTTPClient) PostForm(url string, data url.Values, opts *RequestOptions) (resp *http.Response, req *http.Request, err error) {\n\treq, err = http.NewRequest(\"POST\", url, strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tresp, err = client.Do(req, opts)\n\treturn\n}", "func (c *Client) Url(method string, e ...Endpoint) Modifier {\n\t// TODO Create composite URLs? Add().Add().. etc? Easier to modify on the fly..\n\treturn func(r *http.Request) error {\n\t\tu := c.createURL(e...)\n\t\tr.URL = u\n\t\tr.Method = method\n\t\treturn nil\n\t}\n}", "func (op OperationRequest) BuildURL() (endpoint string, err error) {\n\tnParams := countParams(op.ForAccount, op.ForLedger, op.ForLiquidityPool, op.forOperationID, op.ForTransaction)\n\n\tif nParams > 1 {\n\t\treturn endpoint, errors.New(\"invalid request: too many parameters\")\n\t}\n\n\tif op.endpoint == \"\" {\n\t\treturn endpoint, errors.New(\"internal error, endpoint not set\")\n\t}\n\n\tendpoint = op.endpoint\n\tif op.ForAccount != \"\" {\n\t\tendpoint = fmt.Sprintf(\"accounts/%s/%s\", op.ForAccount, op.endpoint)\n\t}\n\tif op.ForClaimableBalance != \"\" {\n\t\tendpoint = fmt.Sprintf(\"claimable_balances/%s/%s\", op.ForClaimableBalance, op.endpoint)\n\t}\n\tif op.ForLedger > 0 {\n\t\tendpoint = fmt.Sprintf(\"ledgers/%d/%s\", op.ForLedger, op.endpoint)\n\t}\n\tif op.ForLiquidityPool != \"\" {\n\t\tendpoint = fmt.Sprintf(\"liquidity_pools/%s/%s\", op.ForLiquidityPool, op.endpoint)\n\t}\n\tif op.forOperationID != \"\" {\n\t\tendpoint = fmt.Sprintf(\"operations/%s\", op.forOperationID)\n\t}\n\tif op.ForTransaction != \"\" {\n\t\tendpoint = fmt.Sprintf(\"transactions/%s/%s\", op.ForTransaction, op.endpoint)\n\t}\n\n\tqueryParams := addQueryParams(cursor(op.Cursor), limit(op.Limit), op.Order,\n\t\tincludeFailed(op.IncludeFailed), join(op.Join))\n\tif queryParams != \"\" {\n\t\tendpoint = fmt.Sprintf(\"%s?%s\", endpoint, queryParams)\n\t}\n\n\t_, err = url.Parse(endpoint)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"failed to parse endpoint\")\n\t}\n\n\treturn endpoint, err\n}", "func (F *Frisby) Post(url string) *Frisby {\n\tF.Method = \"POST\"\n\tF.Url = url\n\treturn F\n}", "func (h *handler) CreateURL(response http.ResponseWriter, request *http.Request) {\n\tvar body createURLRequest\n\n\tdecoder := json.NewDecoder(request.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\thttp.Error(response, \"Invalid body: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := getUniquePath(body.URL)\n\n\tlog.Infof(\"Request to shorten URL '%s'. Path assigned: '%s'\", body.URL, path)\n\n\tif err := h.store.Put(path, body.URL); err != nil {\n\t\tlog.Errorf(\"Generated path '%s' cannot be stored due to: %+v\", path, err)\n\t\thttp.Error(response, \"There was a collision with the generated path, please try again\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Location\", \"/\"+path)\n\tresponse.WriteHeader(http.StatusCreated)\n}", "func (s *XPackSecurityPutUserService) buildURL() (string, url.Values, error) {\n\t// Build URL\n\tpath, err := uritemplates.Expand(\"/_security/user/{username}\", map[string]string{\n\t\t\"username\": s.username,\n\t})\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif v := s.pretty; v != nil {\n\t\tparams.Set(\"pretty\", fmt.Sprint(*v))\n\t}\n\tif v := s.human; v != nil {\n\t\tparams.Set(\"human\", fmt.Sprint(*v))\n\t}\n\tif v := s.errorTrace; v != nil {\n\t\tparams.Set(\"error_trace\", fmt.Sprint(*v))\n\t}\n\tif len(s.filterPath) > 0 {\n\t\tparams.Set(\"filter_path\", strings.Join(s.filterPath, \",\"))\n\t}\n\tif v := s.refresh; v != \"\" {\n\t\tparams.Set(\"refresh\", v)\n\t}\n\treturn path, params, nil\n}", "func CreateRequestURL(address string, endpointPath string) string {\n\tforwardSlash := \"/\"\n\tif strings.HasSuffix(address, forwardSlash) {\n\t\taddress = strings.TrimSuffix(address, forwardSlash)\n\t}\n\tif strings.HasPrefix(endpointPath, forwardSlash) {\n\t\tendpointPath = strings.TrimPrefix(endpointPath, forwardSlash)\n\t}\n\treturn address + forwardSlash + endpointPath\n}", "func (cbr ClaimableBalanceRequest) BuildURL() (endpoint string, err error) {\n\tendpoint = \"claimable_balances\"\n\n\t//max limit is 200\n\tif cbr.Limit > 200 {\n\t\treturn endpoint, errors.New(\"invalid request: limit \" + fmt.Sprint(cbr.Limit) + \" is greater than limit max of 200\")\n\t}\n\n\t// Only one filter parameter is allowed, and you can't mix an ID query and\n\t// filters.\n\tnParams := countParams(cbr.Asset, cbr.Claimant, cbr.Sponsor, cbr.ID)\n\tif cbr.ID != \"\" && nParams > 1 {\n\t\treturn endpoint, errors.New(\"invalid request: too many parameters\")\n\t}\n\n\tif cbr.ID != \"\" {\n\t\tendpoint = fmt.Sprintf(\"%s/%s\", endpoint, cbr.ID)\n\t} else {\n\t\tparams := map[string]string{\n\t\t\t\"claimant\": cbr.Claimant,\n\t\t\t\"sponsor\": cbr.Sponsor,\n\t\t\t\"asset\": cbr.Asset,\n\t\t}\n\t\tqueryParams := addQueryParams(\n\t\t\tparams, limit(cbr.Limit), cursor(cbr.Cursor),\n\t\t)\n\t\tendpoint = fmt.Sprintf(\"%s?%s\", endpoint, queryParams)\n\t}\n\n\t_, err = url.Parse(endpoint)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"failed to parse endpoint\")\n\t}\n\n\treturn endpoint, err\n}", "func (c *CaptchaGID) URL() string {\n\tif *c == \"\" || *c == \"-1\" {\n\t\treturn \"\"\n\t}\n\treturn APIEndpoints.CommunityBase.String() + \"/public/captcha.php?gid=\" + c.String()\n}", "func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn c.Post(url, contentTypeFormURLEncoded, strings.NewReader(data.Encode()))\n}", "func (input *Input) URL() string {\n\treturn input.Context.Request.URL.Path\n}", "func (c *Client) requestURL(method, endpointURL string) *url.URL {\n\tendpoint, _ := url.Parse(endpointURL)\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\thash := c.generateHash(method, endpoint.Path, timestamp)\n\n\tq := endpoint.Query()\n\tq.Set(\"apiuserid\", c.APIUserID)\n\tq.Set(\"timestamp\", timestamp)\n\tq.Set(\"hash\", hash)\n\tendpoint.RawQuery = q.Encode()\n\n\treturn c.BaseURL.ResolveReference(endpoint)\n}", "func UrlFromPost(r *http.Request, usr *User) *Url {\n\t// TODO: Validate Source url format (http[s]://), trim values\n\tsrc := strings.TrimSpace(r.PostFormValue(\"source\"))\n\n\treturn &Url{\n\t\tPath: RandomPath(),\n\t\tSource: formatUrl(src),\n\t\tDateCreated: time.Now(),\n\t\tOwner: usr,\n\t\tCreatorIP: ipAddr(r),\n\t}\n}", "func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {\n\tb := c.breakerLookup(url)\n\tif b == nil {\n\t\treturn c.client.PostForm(url, data)\n\t}\n\n\tctx := getPostFormCtx()\n\tdefer releasePostFormCtx(ctx)\n\n\tctx.Client = c.client\n\tctx.ErrorOnBadStatus = c.errOnBadStatus\n\tctx.URL = url\n\tctx.Data = data\n\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctx.Response, ctx.Error\n}", "func RequestURL(req *http.Request) model.URL {\n\tfullHost := req.Host\n\tif fullHost == \"\" {\n\t\tfullHost = req.URL.Host\n\t}\n\thost, port, err := net.SplitHostPort(fullHost)\n\tif err != nil {\n\t\thost = fullHost\n\t\tport = \"\"\n\t}\n\tout := model.URL{\n\t\tHostname: host,\n\t\tPort: port,\n\t\tPath: req.URL.Path,\n\t\tSearch: req.URL.RawQuery,\n\t\tHash: req.URL.Fragment,\n\t}\n\tif req.URL.Scheme != \"\" {\n\t\t// If the URL contains user info, remove it before formatting\n\t\t// so it doesn't make its way into the \"full\" URL, to avoid\n\t\t// leaking PII or secrets.\n\t\tuser := req.URL.User\n\t\treq.URL.User = nil\n\t\tout.Full = req.URL.String()\n\t\tout.Protocol = req.URL.Scheme\n\t\treq.URL.User = user\n\t} else {\n\t\t// Server-side, req.URL contains the\n\t\t// URI only. We synthesize the URL\n\t\t// by adding in req.Host, and the\n\t\t// scheme determined by the presence\n\t\t// of TLS configuration.\n\t\tscheme := \"http\"\n\t\tif req.TLS != nil {\n\t\t\tscheme = \"https\"\n\t\t}\n\t\tu := *req.URL\n\t\tu.Scheme = scheme\n\t\tu.User = nil\n\t\tu.Host = fullHost\n\t\tout.Full = u.String()\n\t\tout.Protocol = scheme\n\t}\n\treturn out\n}", "func (g *GitCredential) URL() (url.URL, error) {\n\turlAsString := g.Protocol + \"://\" + g.Host\n\tif g.Path != \"\" {\n\t\turlAsString = stringhelpers.UrlJoin(urlAsString, g.Path)\n\t}\n\tu, err := url.Parse(urlAsString)\n\tif err != nil {\n\t\treturn url.URL{}, errors.Wrap(err, \"unable to construct URL\")\n\t}\n\n\tu.User = url.UserPassword(g.Username, g.Password)\n\treturn *u, nil\n}", "func (a API) URL() string {\n\treturn fmt.Sprintf(\"%s://%s:%s/%s\", a.Schema, a.Host, a.Port, a.APIPrefix)\n}", "func (c *APODClient) buildURL(startDate time.Time) string {\n\tv := url.Values{}\n\tv.Add(\"api_key\", c.APIKey)\n\tv.Add(\"date\", startDate.Format(APODDateFormat))\n\treturn fmt.Sprintf(\"%s?%s\", c.URL, v.Encode())\n}", "func (c *Client) URL(path string, options ...QueryOption) url.URL {\n\tret := baseURL\n\tret.Path = path\n\n\tif len(options) > 0 {\n\t\tq := ret.Query()\n\t\tfor _, opt := range options {\n\t\t\topt(&q)\n\t\t}\n\t\tret.RawQuery = q.Encode()\n\t}\n\treturn ret\n}", "func URL(opts ...options.OptionFunc) string {\n\treturn singleFakeData(URLTag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\tu, err := i.url()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn u\n\t}, opts...).(string)\n}", "func GetURL(kind string, token string) string {\n\treturn fmt.Sprintf(\"%s%s?token=%s\", \"https://api.clubhouse.io/api/v2/\", kind, token)\n}", "func (s *HTTPSet) PostForm(url string, data url.Values) (*http.Response, error) {\n\turl, err := s.replaceHost(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.HTTPClient.PostForm(url, data)\n}", "func (t *Target) URL() *url.URL {\n\tparams := url.Values{}\n\n\tfor k, v := range t.params {\n\t\tparams[k] = make([]string, len(v))\n\t\tcopy(params[k], v)\n\t}\n\tt.labels.Range(func(l labels.Label) {\n\t\tif !strings.HasPrefix(l.Name, model.ParamLabelPrefix) {\n\t\t\treturn\n\t\t}\n\t\tks := l.Name[len(model.ParamLabelPrefix):]\n\n\t\tif len(params[ks]) > 0 {\n\t\t\tparams[ks][0] = l.Value\n\t\t} else {\n\t\t\tparams[ks] = []string{l.Value}\n\t\t}\n\t})\n\n\treturn &url.URL{\n\t\tScheme: t.labels.Get(model.SchemeLabel),\n\t\tHost: t.labels.Get(model.AddressLabel),\n\t\tPath: t.labels.Get(model.MetricsPathLabel),\n\t\tRawQuery: params.Encode(),\n\t}\n}", "func GenerateURL(base, fileName, value string) (string, error) {\n\tu, err := url.Parse(base)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tq := u.Query()\n\tq.Set(\"filename\", fileName)\n\tq.Set(\"value\", value)\n\tu.RawQuery = q.Encode()\n\n\treturn u.String(), nil\n}", "func (t *Toon) URL() string {\n\treturn fmt.Sprintf(\"%s/%d/%d/%d\", \"https://starcraft2.com/en-us/en/profile\", t.RegionID(), t.RealmID(), t.ID())\n}", "func apiURL(cmd, path string, args []string) string {\n\tif len(args) > 0 {\n\t\tvar arglist string\n\t\tfor i := 0; i < len(args); i++ {\n\t\t\targlist += fmt.Sprintf(\"&%s\", args[i])\n\t\t}\n\t\treturn fmt.Sprintf(\"http://%s/api/v0/%s?arg=%s&%s\", defaultIPFSHost, cmd, path, arglist)\n\t}\n\treturn fmt.Sprintf(\"http://%s/api/v0/%s?arg=%s\", defaultIPFSHost, cmd, path)\n}", "func (client *HTTPClient) PostFormAsString(url string, data url.Values, opts *RequestOptions) (result string, req *http.Request, err error) {\n\tresp, req, err := client.PostForm(url, data, opts)\n\tif err != nil {\n\t\treturn \"\", req, err\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", req, err\n\t}\n\treturn string(bytes), req, nil\n}", "func BuildURL(baseURL string, q *Parameters) string {\n\tqueryParams := q.Encode()\n\tif queryParams == \"\" {\n\t\treturn baseURL\n\t}\n\treturn baseURL + \"?\" + queryParams\n}", "func WebAuthnURL(_ *http.Request, authenticateURL *url.URL, key []byte, values url.Values) string {\n\tu := authenticateURL.ResolveReference(&url.URL{\n\t\tPath: WebAuthnURLPath,\n\t\tRawQuery: buildURLValues(values, url.Values{\n\t\t\tQueryDeviceType: {DefaultDeviceType},\n\t\t\tQueryEnrollmentToken: nil,\n\t\t\tQueryRedirectURI: {authenticateURL.ResolveReference(&url.URL{\n\t\t\t\tPath: DeviceEnrolledPath,\n\t\t\t}).String()},\n\t\t}).Encode(),\n\t})\n\treturn NewSignedURL(key, u).Sign().String()\n}", "func (r *Request) url() (*url.URL, error) {\n\n\turlString := stewstrings.MergeStrings(r.session.host(), common.PathSeparator, r.path)\n\n\ttheURL, urlErr := url.Parse(urlString)\n\n\tif urlErr != nil {\n\t\treturn nil, urlErr\n\t}\n\n\t// set the query values\n\ttheURL.RawQuery = r.queryValues.Encode()\n\n\turlString = theURL.String()\n\n\tif strings.Contains(urlString, \"?\") {\n\t\turlString = stewstrings.MergeStrings(urlString, \"&\", common.ParameterAPIKey, \"=\", r.session.apiKey)\n\t} else {\n\t\turlString = stewstrings.MergeStrings(urlString, \"?\", common.ParameterAPIKey, \"=\", r.session.apiKey)\n\t}\n\n\ttheURL, urlErr = url.Parse(urlString)\n\n\tif urlErr != nil {\n\t\treturn nil, urlErr\n\t}\n\n\treturn theURL, nil\n\n}", "func (r *BaseRequest) URL() string {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.baseURL + query\n}", "func (r *Request) URL(uri string) *Request {\n\tr.URLStruct, r.Error = url.Parse(uri)\n\treturn r\n}", "func (r CampaignRequest) URL() string {\n\treturn fmt.Sprintf(\"v3/campaigns/%d\", r.ID)\n}", "func (api *GeocodingAPI) buildURL(req *QueryByAddressRequest) (string, error) {\n\tu, err := url.Parse(fmt.Sprintf(\"%s/geocode/%s/%s.json\",\n\t\tapi.c.BaseURL(),\n\t\turl.QueryEscape(req.Index),\n\t\turl.QueryEscape(req.Query)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Add access_token as query string parameter\n\tq := u.Query()\n\tq.Set(\"access_token\", api.c.accessToken)\n\tu.RawQuery = q.Encode()\n\treturn u.String(), nil\n}", "func (v *DCHttpClient) PostForm(\n\turl string, headers map[string]string, form map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoForm(http.MethodPost,url, headers, form)\n}", "func (it IssueTracker) MakeAuthRequestURL() string {\n\t// NOTE: Need to add XSRF protection if we ever want to run this on a public\n\t// server.\n\treturn it.OAuthConfig.AuthCodeURL(it.OAuthConfig.RedirectURL)\n}", "func (v *Visualisation) URL(vo *VisualisationURLOptions) *url.URL {\n\tu, err := url.Parse(v.c.apiURL + \"/visualisation\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvalues := u.Query()\n\tvalues.Set(\"k\", v.Key)\n\tif vo != nil {\n\t\tif vo.Names != nil {\n\t\t\tfor _, n := range vo.Names {\n\t\t\t\tvalues.Add(\"name\", n)\n\t\t\t}\n\t\t}\n\t\tif vo.Avatars != nil {\n\t\t\tfor _, a := range vo.Avatars {\n\t\t\t\tvalues.Add(\"avatar\", a)\n\t\t\t}\n\t\t}\n\t\tif vo.AvatarBaseURL != \"\" {\n\t\t\tvalues.Set(\"avatarBaseUrl\", vo.AvatarBaseURL)\n\t\t}\n\t\tif !vo.FixedAspect {\n\t\t\tvalues.Set(\"fixedAspect\", \"false\")\n\t\t}\n\t\tif vo.MinimalView {\n\t\t\tvalues.Set(\"minimalView\", \"true\")\n\t\t}\n\t\tif vo.DZML != \"\" {\n\t\t\tvalues.Set(\"dzml\", vo.DZML)\n\t\t}\n\t}\n\tu.RawQuery = values.Encode()\n\treturn u\n}", "func PostURL(url string, params string) (reply []byte, err error) {\n\tcli := &http.Client{\n\t\tTimeout: RequestTimeout * time.Second,\n\t}\n\tresp, err := cli.Post(url,\n\t\t\"application/x-www-form-urlencoded\",\n\t\tstrings.NewReader(params))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\treply, err = ioutil.ReadAll(resp.Body)\n\treturn\n}", "func (gar *GetCarrierRequest) URL() string {\n\treturn fmt.Sprintf(`/v1/carriers/%v`, gar.ID)\n}", "func (c *Client) makeUrl(baseUrl string, params map[string]interface{}) *string {\n\tindex := 0\n\tqueries := make([]string, len(params))\n\tfor k, v := range params {\n\t\tqueries[index] = fmt.Sprintf(\"%s=%s\", k, url.QueryEscape(fmt.Sprintf(\"%v\", v)))\n\t\tindex++\n\t}\n\n\turl := baseUrl\n\tif len(params) > 0 {\n\t\turl = url + \"?\" + strings.Join(queries, \"&\")\n\t}\n\n\treturn &url\n}", "func (req JourneyRequest) toURL() (url.Values, error) {\n\tparams := url.Values{}\n\n\t// Define a few useful functions\n\taddUint := func(key string, amount uint64) {\n\t\tif amount != 0 {\n\t\t\tstr := strconv.FormatUint(amount, 10)\n\t\t\tparams.Add(key, str)\n\t\t}\n\t}\n\taddInt := func(key string, amount int64) {\n\t\tif amount != 0 {\n\t\t\tstr := strconv.FormatInt(amount, 10)\n\t\t\tparams.Add(key, str)\n\t\t}\n\t}\n\taddString := func(key string, str string) {\n\t\tif str != \"\" {\n\t\t\tparams.Add(key, str)\n\t\t}\n\t}\n\taddIDSlice := func(key string, ids []types.ID) {\n\t\tif len(ids) != 0 {\n\t\t\tfor _, id := range ids {\n\t\t\t\tparams.Add(key, string(id))\n\t\t\t}\n\t\t}\n\t}\n\taddModes := func(key string, modes []string) {\n\t\tif len(modes) != 0 {\n\t\t\tfor _, mode := range modes {\n\t\t\t\tparams.Add(key, mode)\n\t\t\t}\n\t\t}\n\t}\n\taddFloat := func(key string, amount float64) {\n\t\tif amount != 0 {\n\t\t\tspeedStr := strconv.FormatFloat(amount, 'f', 3, 64)\n\t\t\tparams.Add(key, speedStr)\n\t\t}\n\t}\n\n\t// Encode the from and to\n\tif from := req.From; from != \"\" {\n\t\tparams.Add(\"from\", string(from))\n\t}\n\tif to := req.To; to != \"\" {\n\t\tparams.Add(\"to\", string(to))\n\t}\n\n\tif datetime := req.Date; !datetime.IsZero() {\n\t\tstr := datetime.Format(types.DateTimeFormat)\n\t\tparams.Add(\"datetime\", str)\n\t\tif req.DateIsArrival {\n\t\t\tparams.Add(\"datetime_represents\", \"arrival\")\n\t\t}\n\t}\n\n\taddString(\"traveler_type\", string(req.Traveler))\n\n\taddString(\"data_freshness\", string(req.Freshness))\n\n\taddIDSlice(\"forbidden_uris[]\", req.Forbidden)\n\n\taddIDSlice(\"allowed_id[]\", req.Allowed)\n\n\taddModes(\"first_section_mode[]\", req.FirstSectionModes)\n\n\taddModes(\"last_section_mode[]\", req.LastSectionModes)\n\n\t// max_duration_to_pt\n\taddInt(\"max_duration_to_pt\", int64(req.MaxDurationToPT/time.Second))\n\n\t// walking_speed, bike_speed, bss_speed & car_speed\n\taddFloat(\"walking_speed\", req.WalkingSpeed)\n\taddFloat(\"bike_speed\", req.BikeSpeed)\n\taddFloat(\"bss_speed\", req.BikeShareSpeed)\n\taddFloat(\"car_speed\", req.CarSpeed)\n\n\t// If count is defined don't bother with the minimimal and maximum amount of items to return\n\tif count := req.Count; count != 0 {\n\t\taddUint(\"count\", uint64(count))\n\t} else {\n\t\taddUint(\"min_nb_journeys\", uint64(req.MinJourneys))\n\t\taddUint(\"max_nb_journeys\", uint64(req.MaxJourneys))\n\t}\n\n\t// max_nb_transfers\n\taddUint(\"max_nb_transfers\", uint64(req.MaxTransfers))\n\n\t// max_duration\n\taddInt(\"max_duration\", int64(req.MaxDuration/time.Second))\n\n\t// wheelchair\n\tif req.Wheelchair {\n\t\tparams.Add(\"wheelchair\", \"true\")\n\t}\n\n\treturn params, nil\n}", "func (r *RestFulUpload) URLPatterns() []rf.Route {\n\treturn []rf.Route{\n\t\t{Method: http.MethodPost, Path: \"/uploadfile\", ResourceFunc: r.UploadFile},\n\t\t{Method: http.MethodPost, Path: \"/uploadform\", ResourceFunc: r.UploadForm},\n\t}\n}", "func (moo *JsonApiUrl) String() string {\n\tvar u *url.URL\n\tvar err error\n\n\tassert.NotEmpty(moo.T, moo.BaseUrl, \"error generating a JsonAPI URL from %v: %s\", moo, \"base url must not be empty\")\n\tassert.NotEmpty(moo.T, moo.DrupalEntity, \"error generating a JsonAPI URL from %v: %s\", moo, \"drupal entity must not be empty\")\n\tassert.NotEmpty(moo.T, moo.DrupalBundle, \"error generating a JsonAPI URL from %v: %s\", moo, \"drupal bundle must not be empty\")\n\n\tbaseUrl := env.BaseUrlOr(moo.BaseUrl)\n\tif strings.HasSuffix(baseUrl, \"/\") {\n\t\tbaseUrl = baseUrl[:len(baseUrl) - 1]\n\t}\n\tu, err = url.Parse(fmt.Sprintf(\"%s\", strings.Join([]string{baseUrl, \"jsonapi\", moo.DrupalEntity, moo.DrupalBundle}, \"/\")))\n\tassert.Nil(moo.T, err, \"error generating a JsonAPI URL from %v: %s\", moo, err)\n\n\t// If a raw filter is supplied, use it as-is, otherwise use the .Filter and .Value\n\tif moo.RawFilter != \"\" {\n\t\tu, err = url.Parse(fmt.Sprintf(\"%s?%s\", u.String(), moo.RawFilter))\n\t} else if moo.Filter != \"\" {\n\t\tu, err = url.Parse(fmt.Sprintf(\"%s?filter[%s]=%s\", u.String(), moo.Filter, moo.Value))\n\t}\n\n\tassert.Nil(moo.T, err, \"error generating a JsonAPI URL from %v: %s\", moo, err)\n\treturn u.String()\n}", "func makeCHPLURL(path string, queryArgs map[string]string, pageSize int, pageNumber int) (*url.URL, error) {\n\tqueryArgsToSend := url.Values{}\n\tchplURL, err := url.Parse(chplDomain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiKey := viper.GetString(\"chplapikey\")\n\tif apiKey == \"\" {\n\t\treturn nil, fmt.Errorf(\"the CHPL API Key is not set\")\n\t}\n\tqueryArgsToSend.Set(\"api_key\", apiKey)\n\tfor k, v := range queryArgs {\n\t\tqueryArgsToSend.Set(k, v)\n\t}\n\tif pageSize != -1 && pageNumber != -1 {\n\t\tqueryArgsToSend.Set(\"pageSize\", strconv.Itoa(pageSize))\n\t\tqueryArgsToSend.Set(\"pageNumber\", strconv.Itoa(pageNumber))\n\t}\n\n\tchplURL.RawQuery = queryArgsToSend.Encode()\n\tchplURL.Path = chplAPIPath + path\n\n\treturn chplURL, nil\n}", "func (r *Request) URL(url string) *Request {\n\tr.url = url\n\treturn r\n}", "func (r *Request) URL(url string) *Request {\n\tr.url = url\n\treturn r\n}", "func (s *ValidateService) buildURL() (string, url.Values, error) {\n\tvar err error\n\tvar path string\n\t// Build URL\n\tif len(s.index) > 0 && len(s.typ) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/{type}/_validate/query\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t\t\"type\": strings.Join(s.typ, \",\"),\n\t\t})\n\t} else if len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_validate/query\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else {\n\t\tpath, err = uritemplates.Expand(\"/_validate/query\", map[string]string{\n\t\t\t\"type\": strings.Join(s.typ, \",\"),\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif v := s.pretty; v != nil {\n\t\tparams.Set(\"pretty\", fmt.Sprint(*v))\n\t}\n\tif v := s.human; v != nil {\n\t\tparams.Set(\"human\", fmt.Sprint(*v))\n\t}\n\tif v := s.errorTrace; v != nil {\n\t\tparams.Set(\"error_trace\", fmt.Sprint(*v))\n\t}\n\tif len(s.filterPath) > 0 {\n\t\tparams.Set(\"filter_path\", strings.Join(s.filterPath, \",\"))\n\t}\n\tif s.explain != nil {\n\t\tparams.Set(\"explain\", fmt.Sprintf(\"%v\", *s.explain))\n\t}\n\tif s.rewrite != nil {\n\t\tparams.Set(\"rewrite\", fmt.Sprintf(\"%v\", *s.rewrite))\n\t}\n\tif s.allShards != nil {\n\t\tparams.Set(\"all_shards\", fmt.Sprintf(\"%v\", *s.allShards))\n\t}\n\tif s.defaultOperator != \"\" {\n\t\tparams.Set(\"default_operator\", s.defaultOperator)\n\t}\n\tif v := s.lenient; v != nil {\n\t\tparams.Set(\"lenient\", fmt.Sprint(*v))\n\t}\n\tif s.q != \"\" {\n\t\tparams.Set(\"q\", s.q)\n\t}\n\tif v := s.analyzeWildcard; v != nil {\n\t\tparams.Set(\"analyze_wildcard\", fmt.Sprint(*v))\n\t}\n\tif s.analyzer != \"\" {\n\t\tparams.Set(\"analyzer\", s.analyzer)\n\t}\n\tif s.df != \"\" {\n\t\tparams.Set(\"df\", s.df)\n\t}\n\tif v := s.allowNoIndices; v != nil {\n\t\tparams.Set(\"allow_no_indices\", fmt.Sprint(*v))\n\t}\n\tif s.expandWildcards != \"\" {\n\t\tparams.Set(\"expand_wildcards\", s.expandWildcards)\n\t}\n\tif v := s.ignoreUnavailable; v != nil {\n\t\tparams.Set(\"ignore_unavailable\", fmt.Sprint(*v))\n\t}\n\treturn path, params, nil\n}", "func FormatURL(url string) string {\n\turl = strings.TrimSpace(url)\n\tif strings.Contains(url, \"\\\\\") {\n\t\turl = strings.ReplaceAll(url, \"\\\\\", \"/\")\n\t}\n\turl = strings.TrimRight(url, \"#/?\")\n\treturn url\n}", "func (cl Client) buildURL(verb, col string, opts ...URLOption) string {\n\treturn BuildURL(cl.ServiceID, verb, cl.Game, col, opts...).String()\n}", "func AuthenticateToURLValues(auth Authenticate) url.Values {\n\tvalues := url.Values{}\n\tvalues.Set(\"name\", auth.Name)\n\tvalues.Set(\"password\", auth.Password)\n\tvalues.Set(\"seed\", auth.Seed)\n\treturn values\n}", "func (c *Client) URL() (url string) {\n\turl = c.url // + \"/\" + c.version\n\treturn\n}", "func URLFormat(urlFormat string) Opt {\n\treturn func(c *HTTP) {\n\t\tc.manifestURLFmt = urlFormat\n\t}\n}", "func (a API) AuthUrl(state string, redirect_url string) (url string) {\r\n\treturn \"https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=\" + a.oauth_key +\r\n\t\t\"&state=\" + state + \"&redirect_uri=\" + redirect_url\r\n}", "func buildURL(gateway, rpath, function string) string {\n\tu, _ := url.Parse(gateway)\n\tu.Path = path.Join(u.Path, rpath+\"/\"+function)\n\treturn u.String()\n}", "func ConstructUnitURL(fullPath, modulePath, requestedVersion string) string {\n\tif requestedVersion == version.Latest {\n\t\treturn \"/\" + fullPath\n\t}\n\tv := LinkVersion(modulePath, requestedVersion, requestedVersion)\n\tif fullPath == modulePath || modulePath == stdlib.ModulePath {\n\t\treturn fmt.Sprintf(\"/%s@%s\", fullPath, v)\n\t}\n\treturn fmt.Sprintf(\"/%s@%s/%s\", modulePath, v, strings.TrimPrefix(fullPath, modulePath+\"/\"))\n}", "func buildApiURL(sig, protocol string) string {\n\treturn protocol + API_HOST + API_ENDPOIT + SIG_GET_KEY + sig\n}", "func (cfg *Config) SetFromURL(url *url.URL) error {\n\tkmsKeyNameParamString := url.Query().Get(kmsKeyName)\n\tif len(kmsKeyNameParamString) > 0 {\n\t\tcfg.KMSKeyName = kmsKeyNameParamString\n\t}\n\n\tendpointParamString := url.Query().Get(endpointPropertyKey)\n\tif len(endpointParamString) > 0 {\n\t\tcfg.Endpoint = endpointParamString\n\t}\n\n\tpathParamString := url.Query().Get(pathPropertyKey)\n\tif len(pathParamString) > 0 {\n\t\tcfg.Path = pathParamString\n\t}\n\n\tcredentialsPathParamString := url.Query().Get(credentialsPath)\n\tif len(credentialsPathParamString) > 0 {\n\t\tcfg.CredentialsPath = credentialsPathParamString\n\t}\n\n\tprojectIDParamString := url.Query().Get(projectID)\n\tif projectIDParamString == \"\" {\n\t\treturn trace.BadParameter(\"parameter %s with value '%s' is invalid\",\n\t\t\tprojectID, projectIDParamString)\n\t}\n\tcfg.ProjectID = projectIDParamString\n\n\tif url.Host == \"\" {\n\t\treturn trace.BadParameter(\"host should be set to the bucket name for recording storage\")\n\t}\n\tcfg.Bucket = url.Host\n\n\treturn nil\n}", "func CreateURL(baseURL, urlPath, urlQuery string) *url.URL {\n\tparsedURL, err := url.Parse(baseURL)\n\tif err != nil {\n\t\tPrintMessageAndExit(\"Unable to parse DC/OS Cluster URL '%s': %s\", baseURL, err)\n\t}\n\tparsedURL.Path = urlPath\n\tparsedURL.RawQuery = urlQuery\n\treturn parsedURL\n}", "func (f *Fs) url(remote string) string {\n\treturn f.endpointURL + rest.URLPathEscape(remote)\n}", "func (bucket Bucket) SignURL(objectKey string, method HTTPMethod, expiredInSec int64, options ...Option) (string, error) {\n\tif expiredInSec < 0 {\n\t\treturn \"\", fmt.Errorf(\"invalid expires: %d, expires must bigger than 0\", expiredInSec)\n\t}\n\texpiration := time.Now().Unix() + expiredInSec\n\n\tparams, err := getRawParams(options)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\theaders := make(map[string]string)\n\terr = handleOptions(headers, options)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn bucket.Client.Conn.signURL(method, bucket.BucketName, objectKey, expiration, params, headers), nil\n}", "func ValidateURL(baseURL, apiURL string) string {\n\n\tcmpltURL := baseURL + apiURL\n\n\tu, err := url.ParseRequestURI(cmpltURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"AlertManager API URL is not valid, error:%v\", err)\n\t}\n\n\treturn u.String()\n}", "func newAccountsURL(address string, query map[string]string) url.URL {\n\tu, _ := url.Parse(fmt.Sprintf(\"/accounts/%s\", address))\n\tif query == nil {\n\t\tquery = map[string]string{}\n\t}\n\tquery[\"expand\"] = \"keys,contracts\"\n\n\treturn addQuery(u, query)\n}", "func URL(r *http.Request, data interface{}) error {\n\tq := r.URL.Query()\n\tv := reflect.ValueOf(data)\n\tt := v.Elem().Type()\n\tfor i := 0; i < v.Elem().NumField(); i++ {\n\t\tft := t.Field(i)\n\t\tfv := v.Elem().Field(i)\n\t\tif tv, exist := ft.Tag.Lookup(paramTag); exist {\n\t\t\tval := fmt.Sprintf(\"%v\", fv)\n\t\t\tif !(len(val) == 0 && strings.Contains(tv, omitEmpty)) {\n\t\t\t\tq.Add(strings.SplitN(tv, \",\", 2)[0], val)\n\t\t\t}\n\t\t}\n\t}\n\tr.URL.RawQuery = q.Encode()\n\treturn nil\n}", "func (promCli *prometheusStorageClient) buildURL(path string, params map[string]interface{}) url.URL {\n\tpromURL := *promCli.url\n\t// treat federate special\n\tif path == \"/federate\" {\n\t\tpromURL = *promCli.federateURL\n\t}\n\n\t// change original request to point to our backing Prometheus\n\tpromURL.Path += path\n\tqueryParams := url.Values{}\n\tfor k, v := range params {\n\t\tif s, ok := v.(string); ok {\n\t\t\tif s != \"\" {\n\t\t\t\tqueryParams.Add(k, s)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, s := range v.([]string) {\n\t\t\t\tqueryParams.Add(k, s)\n\t\t\t}\n\t\t}\n\t}\n\tpromURL.RawQuery = queryParams.Encode()\n\n\treturn promURL\n}", "func (cb *ClientBuilder) URL(url string) *ClientBuilder {\n\tcb.client.url = url\n\treturn cb\n}", "func (cb *ClientBuilder) URL(url string) *ClientBuilder {\n\tcb.client.url = url\n\treturn cb\n}", "func (c *Client) CliURL(nut ssp.Nut, can string) string {\n\tparams := make(url.Values)\n\tif nut != \"\" {\n\t\tparams.Add(\"nut\", string(nut))\n\t}\n\tif can != \"\" {\n\t\tparams.Add(\"can\", can)\n\t}\n\tu := c.baseURL()\n\tu.Path = c.Qry\n\tif len(params) > 0 {\n\t\tu.RawQuery = params.Encode()\n\t}\n\treturn u.String()\n}", "func (s *Service) generateUrl(apiMethod string, arguments map[string]string) string {\n\tvalues := url.Values{}\n\tfor key, value := range arguments {\n\t\tvalues.Set(key, value)\n\t}\n\tvalues.Set(\"api_key\", s.ApiKey)\n\ttimestamp := fmt.Sprintf(\"%d\", time.Now().Unix())\n\tvalues.Set(\"ts\", timestamp)\n\thash := sha1.New()\n\tio.WriteString(hash, s.SharedSecret+timestamp)\n\tvalues.Set(\"hash\", fmt.Sprintf(\"%x\", hash.Sum(nil)))\n\treturn apiUrl + \"/\" + apiMethod + \"?\" + values.Encode()\n}", "func MakeUrl(address string) string {\n\n params := url.Values{}\n params.Add(\"near\", address)\n\n uri := fmt.Sprintf(\"%s?%s\", URL, params.Encode())\n\n return uri\n}", "func generatePostForm(nextNMonth int) url.Values {\n\n\tformData := url.Values{}\n\tformData.Set(\"apptDetails.apptType\", apptType)\n\tformData.Set(\"apptDetails.identifier1\", *nric)\n\tformData.Set(\"apptDetails.identifier2\", \"1\")\n\tformData.Set(\"apptDetails.changeLimitFlg\", \"N\")\n\tformData.Set(\"apptDetails.latestValidityStartDt\", currentDate())\n\tformData.Set(\"apptDetails.earliestValidityEndDt\", expireDate)\n\tformData.Set(\"apptDetails.applicantType\", applicantType)\n\tformData.Set(\"calendar.previousCalDate\", nextNMonthDateStr(nextNMonth-1))\n\tformData.Set(\"calendar.startDate\", nextNMonthDateStr(nextNMonth))\n\tformData.Set(\"calendar.nextCalDate\", nextNMonthDateStr(nextNMonth+1))\n\tformData.Set(\"calendar.calendarYearStr\", strconv.Itoa(nextNMonthDate(nextNMonth).Year()))\n\tformData.Set(\"calendar.calendarMonthStr\", strconv.Itoa(int(nextNMonthDate(nextNMonth).Month())-1))\n\n\treturn formData\n}", "func AuthURL(urlStr string, sid string, tokenP1 string, tokenP2 string) (string, error) {\n\turlObj, err := url.ParseRequestURI(urlStr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttokenP3 := GenRandStr(16, \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\ttoken := tokenP1 + tokenP2 + tokenP3\n\tts := time.Now().Unix() + 4200\n\tpath := urlObj.RequestURI()\n\tsep := map[bool]string{true: \"&\", false: \"?\"}[strings.Contains(urlStr, \"?\")]\n\n\tplaintext := fmt.Sprintf(\"%s%ssid=%s%d%s\", path, sep, sid, ts, tokenP3)\n\tplaintextBytes := padPkcs7([]byte(plaintext))\n\tkey := hashStr(token)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmode := cipher.NewCBCEncrypter(block, make([]byte, aes.BlockSize))\n\tciphertext := make([]byte, len(plaintextBytes))\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\n\tciphertextEncoded := base64.StdEncoding.EncodeToString([]byte(ciphertext))\n\taccessKey := fmt.Sprintf(\"%d_%s_%s\", ts, tokenP3, ciphertextEncoded)\n\taccessKeyEncoded := url.QueryEscape(accessKey)\n\tfinal := fmt.Sprintf(`%s%ssid=%s&accessKey=%s`, urlStr, sep, sid, accessKeyEncoded)\n\n\treturn final, nil\n}", "func GenerateURL(username string, issuer string) (URI string, secret string, err error) {\n\tsecret, err = generateSecretKey()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tconfig := configuration(secret)\n\treturn config.ProvisionURIWithIssuer(username, issuer), secret, nil\n}", "func URL(data ValidationData) error {\n\tv, err := helper.ToString(data.Value)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a string\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tparsed, err := url.Parse(v)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a valid URL\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Scheme != \"http\" && parsed.Scheme != \"https\" {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid scheme '%s'\", parsed.Scheme),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Host == \"\" || strings.IndexRune(parsed.Host, '\\\\') > 0 {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid host ('%s')\", parsed.Host),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\treturn nil\n}", "func SubmitLoginForm(\n\tt *testing.T,\n\tisAPI bool,\n\thc *http.Client,\n\tpublicTS *httptest.Server,\n\twithValues func(v url.Values),\n\tmethod identity.CredentialsType,\n\tforced bool,\n\texpectedStatusCode int,\n\texpectedURL string,\n) string {\n\tif hc == nil {\n\t\thc = new(http.Client)\n\t\tif !isAPI {\n\t\t\thc = NewClientWithCookies(t)\n\t\t}\n\t}\n\n\thc.Transport = NewTransportWithLogger(hc.Transport, t)\n\tvar f *models.LoginFlow\n\tif isAPI {\n\t\tf = InitializeLoginFlowViaAPI(t, hc, publicTS, forced).Payload\n\t} else {\n\t\tf = InitializeLoginFlowViaBrowser(t, hc, publicTS, forced).Payload\n\t}\n\n\ttime.Sleep(time.Millisecond) // add a bit of delay to allow `1ns` to time out.\n\n\tconfig := GetLoginFlowMethodConfig(t, f, method.String())\n\n\tpayload := SDKFormFieldsToURLValues(config.Fields)\n\twithValues(payload)\n\tb, res := LoginMakeRequest(t, isAPI, config, hc, EncodeFormAsJSON(t, isAPI, payload))\n\tassert.EqualValues(t, expectedStatusCode, res.StatusCode, \"%s\", b)\n\tassert.Contains(t, res.Request.URL.String(), expectedURL, \"%+v\\n\\t%s\", res.Request, b)\n\n\treturn b\n}", "func (req *CreateServerInput) ToURLValues() url.Values {\n\tval := url.Values{}\n\tval.Set(\"DCID\", strconv.Itoa(req.DCID))\n\tval.Set(\"VPSPLANID\", strconv.Itoa(req.VPSPLANID))\n\tval.Set(\"OSID\", strconv.Itoa(req.OSID))\n\tval.Set(\"enable_ipv6\", formatBool(req.EnableIPv6))\n\tval.Set(\"enable_private_network\", formatBool(req.EnablePrivateNetwork))\n\tval.Set(\"auto_backups\", formatBool(req.AutoBackups))\n\tval.Set(\"notify_activate\", formatBool(req.NotifyActivate))\n\tval.Set(\"ddos_protection\", formatBool(req.DdosProtection))\n\tif req.Label != \"\" {\n\t\tval.Set(\"label\", req.Label)\n\t}\n\treturn val\n}" ]
[ "0.66246676", "0.6007513", "0.59628695", "0.5916297", "0.5916297", "0.58256966", "0.5766045", "0.5760121", "0.571929", "0.56557834", "0.5648642", "0.5600497", "0.55815196", "0.5578678", "0.55533004", "0.5527532", "0.54867375", "0.5465737", "0.5420745", "0.5400873", "0.53743595", "0.53643817", "0.5356086", "0.53463423", "0.5333876", "0.5298906", "0.5280811", "0.5279349", "0.526164", "0.52608925", "0.52413505", "0.52307564", "0.5224198", "0.5217567", "0.5202395", "0.5200772", "0.51899326", "0.5178084", "0.5178013", "0.51723343", "0.5170102", "0.51698864", "0.51182187", "0.51015306", "0.5098893", "0.5085736", "0.5082389", "0.5069423", "0.5061015", "0.5059442", "0.5055636", "0.50470525", "0.50376284", "0.5018281", "0.50133836", "0.50131404", "0.50043416", "0.49870104", "0.49834317", "0.49783126", "0.497532", "0.49723157", "0.49709746", "0.49657318", "0.49505475", "0.49386814", "0.493842", "0.4937008", "0.49268946", "0.49212694", "0.49212694", "0.4920941", "0.4912331", "0.49091268", "0.48991957", "0.48939756", "0.48931652", "0.48838475", "0.48835602", "0.48814535", "0.48800308", "0.48799086", "0.48798308", "0.48785746", "0.48767084", "0.48740545", "0.48703903", "0.48692548", "0.48594755", "0.48510697", "0.48510697", "0.4851049", "0.48406756", "0.48361176", "0.48346215", "0.4833794", "0.48308408", "0.4829996", "0.482004", "0.48166555" ]
0.771264
0
/ Get will issue a HTTP request using the GET verb.
func GetMethod(method string, args map[string]string, unmarshal func([]byte) error) error { requestURL := FormURL(rootURL, method, args) resp, err := myClient.Get(requestURL.String()) if err != nil { return err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } var prettyJSON bytes.Buffer err = json.Indent(&prettyJSON, body, "", "\t") if err != nil { return err } log.Debugf("RTM API response: %s", string(prettyJSON.Bytes())) var errorMessage RTMAPIError if err := json.Unmarshal(body, &errorMessage); err != nil { log.WithFields(log.Fields{ "error": err, }).Fatal("Failed to unmarshal api response.") return err } if errorMessage.Rsp.Stat == "fail" { return &errorMessage } if err := unmarshal(body); err != nil { log.WithFields(log.Fields{ "error": err, }).Fatal("Failed to unmarshal api response.") return err } log.Debug("Completed API request.") return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\n}", "func (e *Expect) GET(path string, pathargs ...interface{}) *Request {\n\treturn e.Request(http.MethodGet, path, pathargs...)\n}", "func Get (url string, args map[string]string) (*http.Response, error) {\n\t// create a client\n\tclient, req, _ := GetHttpClient(url)\n\t// build the query\n\tif len(args) > 0 {\n\t\treq = buildQuery(req, args)\n\t}\n\t// execute the request\n\t//fmt.Println(req.URL.String())\n\treturn client.Do(req)\n}", "func (r *Request) Get(url string) *Request {\n\tr.method = http.MethodGet\n\tr.url = url\n\treturn r\n}", "func (r *Request) Get(path string) *Request {\n\treturn r.method(\"GET\", path)\n}", "func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\r\n\treturn client.Request(\"GET\", action, params, header, nil)\r\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn do(\"GET\", url, nil)\n}", "func GET(t *testing.T, path string) *httpexpect.Request {\n\tu, err := url.Parse(path)\n\trequire.Nil(t, err)\n\treturn newAPI(t).\n\t\tGET(u.Path).\n\t\tWithQueryString(u.RawQuery)\n}", "func Get(opts ...Option) ([]byte, error) {\n\treturn request(\"GET\", opts...)\n}", "func (rb *RequestBuilder) Get(url string) *Response {\n\treturn rb.DoRequest(http.MethodGet, url, nil)\n}", "func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\n}", "func (c *baseClient) Get(path string) *baseClient {\n\tc.method = \"GET\"\n\treturn c.Path(path)\n}", "func Get(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"GET\", url, data...)\n}", "func (c clientType) Get(path string) (*resty.Response, error) {\n\treturn c.execute(http.MethodGet, path, nil)\n}", "func (tr *Transport) GET(\n\turi string,\n\tfn Handler,\n\toptions ...HandlerOption,\n) {\n\ttr.mux.Handler(\n\t\tnet_http.MethodGet,\n\t\turi,\n\t\tnewHandler(fn, append(tr.options, options...)...),\n\t)\n}", "func HTTPGet(params *HTTPRequest) (*http.Response, error) {\n\tparams.Method = \"GET\"\n\tprintHTTPRequest(params)\n\n\tu, err := url.Parse(params.URL)\n\tif err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\tif len(params.Query) > 0 {\n\t\tu.RawQuery = params.Query.Encode()\n\t}\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := printHTTPResponse(params.URL, resp); err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (client *Client) Get(path string) Response {\n\treturn client.processRequest(path, \"GET\")\n}", "func (conn Connection) Get(cmd string, result interface{}) (resp *http.Response, err error) {\n\treturn conn.Send(http.MethodGet, cmd, nil, result)\n}", "func Get(h http.Handler) http.Handler {\n\treturn HTTP(h, GET)\n}", "func (session *Session) Get(path string, params Params) (response []byte, err error) {\n\turlStr := session.getUrl(path, params)\n\tlog.Println(urlStr)\n\tresponse, err = session.sendGetRequest(urlStr)\n\treturn\n\n\t//res, err = MakeResult(response)\n\t//return\n\n}", "func (c *Case) GET(p string) *RequestBuilder {\n\treturn &RequestBuilder{\n\t\tmethod: http.MethodGet,\n\t\tpath: p,\n\t\tcas: c,\n\t\tfail: c.fail,\n\t}\n}", "func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {\n return c.doRequest(\"GET\", route, queryValues, nil)\n}", "func (a *APITest) Get(url string) *Request {\n\ta.request.method = http.MethodGet\n\ta.request.url = url\n\treturn a.request\n}", "func (req *Req) Get(u string) ([]byte, error) {\n\treturn req.request(\"GET\", u)\n}", "func Get(options RequestOptions) error {\n\thost, path := uriToHostAndPath(options.Uri)\n\toptions.Headers[\"Host\"] = host\n\trequest := fmt.Sprintf(\"GET %s HTTP/1.0\", path)\n\tprotocol := fmt.Sprintf(\"%s\\r\\n%s\\r\\n\", request, options.Headers)\n\treturn send(host, protocol, options)\n}", "func Get(ctx context.Context, url string, options ...RequestOption) (*Response, error) {\n\tr, err := newRequest(ctx, http.MethodGet, url, nil, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn doRequest(http.DefaultClient, r)\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}", "func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}", "func (s *Nap) Get(pathURL string) *Nap {\n\ts.method = MethodGet\n\treturn s.Path(pathURL)\n}", "func (r *Router) GET(path string, handler RequestHandler) {\n\tr.setPath(httpGET, path, handler)\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\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: &GetReader{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.(*GetOK), nil\n\n}", "func (F *Frisby) Get(url string) *Frisby {\n\tF.Method = \"GET\"\n\tF.Url = url\n\treturn F\n}", "func Get(config *HTTPConfig) (*HTTPResult, error) {\n\treturn HandleRequest(\"GET\", config)\n}", "func (c *Client) Get(path string) (f interface{}, err error) {\n\treturn c.do(\"GET\", path, nil)\n}", "func (g *Github) Get(url string) (*http.Response, error) {\n\treturn g.Do(http.MethodGet, url, http.NoBody)\n}", "func (r *Request) Get(path string, params ...url.Values) {\n\tcontentType := \"text/html\"\n\n\tif len(params) == 0 {\n\t\tr.Send(\"GET\", path, contentType)\n\t} else {\n\t\tr.Send(\"GET\", path, contentType, params[0])\n\t}\n}", "func (cl *Client) Get(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodGet, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}", "func (r *Router) GET(path string, handle Handle) {\n\tr.Handle(http.MethodGet, path, handle)\n}", "func (v *DCHttpClient) Get(url string, headers map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoWithoutContent(http.MethodGet, url, headers)\n}", "func (c *Client) Get() *Request {\n\treturn NewRequest(c.httpClient, c.base, \"GET\", c.version, c.authstring, c.userAgent)\n}", "func (c *Client) Get(URL string) (resp *Response, err error) {\n\turlObj, err := url.ParseRequestURI(URL)\n\tif err != nil {\n\t\treturn\n\t}\n\theader := make(map[string]string)\n\theader[HeaderContentLength] = \"0\"\n\theader[HeaderHost] = urlObj.Host\n\treq := &Request{\n\t\tMethod: MethodGet,\n\t\tURL: urlObj,\n\t\tProto: HTTPVersion,\n\t\tHeader: header,\n\t\tContentLength: 0,\n\t\tBody: strings.NewReader(\"\"),\n\t}\n\tresp, err = c.Send(req)\n\treturn\n}", "func (api *Api) Get(path string, endpoint http.HandlerFunc, queries ...string) {\n\tapi.Router.HandleFunc(path, endpoint).Methods(\"GET\").Queries(queries...)\n}", "func (conn Connection) Get(cmd string, result interface{}) (effect *SideEffect, resp *http.Response, err error) {\n\treturn conn.Send(http.MethodGet, cmd, nil, result)\n}", "func (client *Client) Get(c context.Context, uri string, params interface{}, res interface{}) (err error) {\n\treq, err := client.NewRequest(xhttp.MethodGet, uri, params)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn client.client.Do(c, req, res)\n}", "func (s *DefaultClient) Get(endpoint string) ([]byte, *http.Response, error) {\n\treturn s.http(http.MethodGet, endpoint, nil)\n}", "func (c *Client) Get(route string) (io.ReadCloser, error) {\n\t// Prepare HTTP request\n\treq, err := http.NewRequest(\"GET\", c.url+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do the request over the default client\n\treturn c.performRequest(req)\n}", "func (serv *Server) GET(url string, handlers ...Handler) {\n\tserv.Handle(\"GET\", url, handlers...)\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn DefaultClient.Get(url)\n}", "func Get(url string, data ...interface{}) (*Response, error) {\n\tr := NewRequest()\n\treturn r.Get(url, data...)\n}", "func Get(url string) (*http.Response, error) {\n\treturn DefaultClient.Get(url)\n}", "func (APIResourceBase) Get(session *Session, url string, queries url.Values, body io.Reader) (APIStatus, interface{}) {\n\treturn FailSimple(http.StatusMethodNotAllowed), nil\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\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: &GetReader{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.(*GetOK)\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 get: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (e *Engine) GET(path string, handler Handler) {\n\te.registerRoute(http.MethodGet, path, handler)\n}", "func (s *Server) Get(ctx context.Context, req *gnmipb.GetRequest) (*gnmipb.GetResponse, error) {\n\tseq := s.rpcSequence()\n\tif glog.V(11) {\n\t\tglog.Infof(\"get.request[%d]=%v\", seq, req)\n\t}\n\tresp, err := s.get(ctx, req)\n\tif err != nil {\n\t\tif glog.V(11) {\n\t\t\tglog.Errorf(\"get.response[%d]=%v\", seq, status.FromError(err))\n\t\t}\n\t} else {\n\t\tif glog.V(11) {\n\t\t\tglog.Infof(\"get.response[%d]=%v\", seq, resp)\n\t\t}\n\t}\n\treturn resp, err\n}", "func (r *Router) GET(path string, h HandlerFunc) {\n\tr.router.GET(path, r.handle(h, r.getValidationForPath(path, \"GET\")))\n}", "func (session *Session) Get(path string, params Params) (res Result, err error) {\n\turlStr := session.app.BaseEndPoint + session.getRequestUrl(path, params)\n\n\tvar response []byte\n\tresponse, err = session.SendGetRequest(urlStr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err = MakeResult(response)\n\treturn\n}", "func (r *Router) GET(url string, viewFn View) *Path {\n\treturn r.Path(fasthttp.MethodGet, url, viewFn)\n}", "func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\n\tfinalURL := c.baseURL + url\n\tr, err := http.NewRequest(\"GET\", finalURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %v\", err)\n\t}\n\n\treturn c.performRequest(r, headers, params)\n}", "func (s *Server) Get(ctx context.Context, message *todopb.GetRequest) (*todopb.GetResponse, error) {\n\tctx = context.WithValue(ctx, goa.MethodKey, \"get\")\n\tctx = context.WithValue(ctx, goa.ServiceKey, \"todo\")\n\tresp, err := s.GetH.Handle(ctx, message)\n\tif err != nil {\n\t\treturn nil, goagrpc.EncodeError(err)\n\t}\n\treturn resp.(*todopb.GetResponse), nil\n}", "func (b *Builder) Get(url string) *Builder {\n\tb.Url = url\n\tb.Method = http.MethodGet\n\treturn b\n}", "func (tr *Transport) Get(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodGet, url, encapsulate(fn, tr.options, options))\n}", "func Get(query string) (*client.Response, error) {\n\tresponse, err := client.Get(APIBaseURL+query).Header(\"Accept\", acceptType).End()\n\treturn response, err\n}", "func (app *App) GET(url string, handler ...Handler) *App {\n\tapp.routeANY = false\n\tapp.AppendReqAndResp(url, \"get\", handler)\n\treturn app\n}", "func (s *Server) GET(path string, handle http.HandlerFunc) {\n\ts.router.GET(path, s.wrapHandler(handle))\n}", "func Get(targetURL string, params map[string]string, authHeader string) ([]byte, error) {\n\tlog.Debugf(\"GET targetURL=%s, params=%+v, auth=%s\", targetURL, params, authHeader)\n\n\treq, _ := http.NewRequest(\"GET\", targetURL, nil)\n\treq.URL.RawQuery = convertToValues(params).Encode()\n\tif authHeader != \"\" {\n\t\treq.Header.Add(\"Authorization\", authHeader)\n\t}\n\treturn doRequest(req)\n}", "func (its *Request) Get() ([]byte, error) {\n\trequest, err := http.NewRequest(\"GET\", its.IsHTTPS+\"://\"+its.Host+its.Path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add BearToken auth\n\tif its.BearToken != \"\" {\n\t\trequest.Header.Add(\"Authorization\", \"Bearer \"+its.BearToken)\n\t}\n\n\tclient := http.Client{}\n\t// add InsecureSkipVerify\n\tif its.IsHTTPS == \"https\" {\n\t\tclient.Transport = tr\n\t}\n\n\t// execute this request\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get,read and return\n\tdefer resp.Body.Close()\n\ttmp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tmp, nil\n}", "func (client *HTTPClient) Get(url string, opts *RequestOptions) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tresp, err = client.Do(req, opts)\n\treturn\n}", "func (c *Client) Get(path string, out interface{}) error {\n\treturn c.Send(\"GET\", path, nil, out)\n}", "func (a *API) Get(path string) (resp *http.Response, err error) {\n\tu, err := url.ParseRequestURI(a.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu.Path = path\n\n\treturn a.Client.Get(u.String())\n}", "func (g *RouterGroup) GET(url string, handler ...Handler) *RouterGroup {\n\tg.app.routeANY = false\n\tg.AppendReqAndResp(url, \"get\", handler)\n\treturn g\n}", "func (r *Router) GET(path string, handler Handle) {\n\tr.Handle(\"GET\", path, handler)\n}", "func (s *Server) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {\n\ts.Router.HandleFunc(path, f).Methods(\"GET\")\n}", "func (s *Sender) SimpleGet() (*http.Response, error) {\n\treturn http.Get(s.URL)\n}", "func (f *Fastglue) GET(path string, h FastRequestHandler) {\n\tf.Router.GET(path, f.handler(h))\n}", "func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"GET\", url, headers, nil)\n}", "func (cli *Client) Get(targetURL *url.URL) {\n\tvar resp *resty.Response\n\tvar err error\n\n\tif cli.Config.Oauth2Enabled {\n\t\tresp, err = resty.R().\n\t\t\tSetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", cli.AccessToken)).\n\t\t\tGet(targetURL.String())\n\t} else {\n\t\tresp, err = resty.R().Get(targetURL.String())\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"ERR: Could not GET request, caused by: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Print(resp)\n}", "func Get(path string, f func(http.ResponseWriter, *http.Request)) *Route {\n\treturn NewRoute().Path(path).Method(HttpGet).HandlerFunc(f)\n}", "func (c Client) get(path string, params url.Values, holder interface{}) error {\n\treturn c.request(\"GET\", path, params, &holder)\n}", "func get(resource string) ([]byte, error) {\n\thttpParams := &HTTPParams{\n\t\tResource: resource,\n\t\tVerb: \"GET\",\n\t}\n\treturn processRequest(httpParams)\n}", "func (c *Client) Get(path string, resource, options interface{}) error {\n\treturn c.CreateAndDo(\"GET\", path, nil, options, nil, resource)\n}", "func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\n\n\t// add parameters to the url\n\tv := url.Values{}\n\tfor key, value := range queryParams {\n\t\tv.Add(key, value)\n\t}\n\turi, err := url.Parse(c.baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi.RawQuery = v.Encode()\n\tc.baseURL = uri.String()\n\n\t// create a new get request\n\trequest, err := http.NewRequest(\"GET\", c.baseURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add headers to the request\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := c.sendRequestWithRetry(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if response is an error (not a 200)\n\tif response.StatusCode > 299 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\t// read the body as an array of bytes\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\treturn responseBody, err\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 (g *Getter) Get(url string) (*http.Response, error) {\n\treturn g.Client.Get(url)\n}", "func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\tinfoMutex.Lock()\n\trecord(\"GET\", path)\n\tr.Get(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\n\tinfoMutex.Unlock()\n}", "func (c *httpClient) Get(url string,\n\theaders http.Header) (*Response, error) {\n\treturn c.do(http.MethodGet, url, headers, nil)\n}", "func (app *App) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {\n\tapp.Router.HandleFunc(path, f).Methods(\"GET\")\n}", "func NewGet(url string) *Request { return NewRequest(\"GET\", url) }", "func Get(path string, handler http.Handler) Route {\n\treturn NewRoute(\"GET\", path, handler)\n}", "func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"GET\", path)\n\n\tinfoMutex.Lock()\n\tr.GET(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}", "func Get(url, authToken string) (*http.Response, error) {\n\treturn get(url, authToken, 1)\n}", "func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}", "func sendGet(method string, uri string, args ...interface{}) (responseBody []byte, statusCode int, err error) {\n\tclient := &http.Client{}\n\n\treq, _ := http.NewRequest(method, uri, nil)\n\n\tfor _, arg := range args {\n\t\tswitch val := arg.(type) {\n\t\tcase url.Values:\n\t\t\t// Assign http query to the request URL\n\t\t\treq.URL.RawQuery = val.Encode()\n\n\t\tcase http.Header:\n\t\t\t// Assign request header\n\t\t\treq.Header = val\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Response error. Error: %+v\\n\", err.Error())\n\t\treturn nil, 500, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\t// Read response body\n\tstatusCode = resp.StatusCode\n\n\tresult, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error when converting response body to []byte: %+v\\n\", err.Error())\n\t\treturn nil, statusCode, err\n\t}\n\n\treturn result, statusCode, nil\n}", "func GetRequest(host, path string) (*http.Response, error) {\n\tfmt.Println(\"GET\", \"/\"+path)\n\tresp, err := http.Get(host + \"/\" + path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (req *Request) Get() *ResultSet {\n\treturn req.do(http.MethodGet)\n}", "func HTTPGET(url string, auth bool, authToken string) (int, []byte, error) {\n\treturn httpRequest(\"GET\", url, auth, authToken, nil)\n}", "func (h *Client) Get(url string, values url.Values) (body []byte, statusCode int, err error) {\n\tif values != nil {\n\t\turl += \"?\" + values.Encode()\n\t}\n\tvar req *http.Request\n\treq, err = http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn h.do(req)\n}", "func (r *Router) Get(path, title string, fn Handle) {\n\tr.addRoute(\"GET\", path, title, fn)\n}", "func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}", "func (router *Router) GET(relativePath string, handler Handler, decorators ...Decorator) {\n\trouter.createRouter(http.MethodGet, relativePath, handler, \"\", decorators...)\n}", "func (t transporter) Get(path string) (*http.Response, error) {\n\tresp, err := t.client.Get(t.scheme + path)\n\treturn resp, err\n}", "func (r *Router) GET(path string, handle HandlerFunc, middleware ...MiddlewareFunc) {\n\tr.Handle(\"GET\", path, handle, middleware...)\n}" ]
[ "0.78753054", "0.78579533", "0.7827149", "0.7813404", "0.77999794", "0.7761369", "0.7639451", "0.7599825", "0.7589636", "0.7552103", "0.75378567", "0.74897224", "0.7464658", "0.74478674", "0.7400398", "0.73652476", "0.7360117", "0.7359701", "0.73462594", "0.7337866", "0.7321429", "0.7316015", "0.72820604", "0.72648084", "0.7249078", "0.7247532", "0.72359586", "0.7234077", "0.72330743", "0.7222879", "0.71902573", "0.7184184", "0.71828425", "0.7130151", "0.71265787", "0.7108617", "0.71074617", "0.7103474", "0.70969725", "0.70870364", "0.7078538", "0.7072067", "0.7060083", "0.7055945", "0.7049397", "0.70367223", "0.7033892", "0.70207554", "0.7015051", "0.701304", "0.7007054", "0.7004272", "0.6999223", "0.6994516", "0.6958699", "0.6950131", "0.694766", "0.6943501", "0.6937903", "0.6937236", "0.693508", "0.692443", "0.69207376", "0.69175243", "0.69107354", "0.68942875", "0.6893384", "0.689311", "0.6887809", "0.68681514", "0.6868081", "0.68573016", "0.6855743", "0.68527806", "0.6848699", "0.68457997", "0.684004", "0.6838908", "0.68380123", "0.6836684", "0.68353474", "0.68278927", "0.6821664", "0.6817329", "0.68115073", "0.68101454", "0.68068284", "0.6773721", "0.67704606", "0.67692864", "0.6767496", "0.67579633", "0.6757953", "0.67578256", "0.6754692", "0.6746013", "0.6742587", "0.67395324", "0.6736532", "0.673529", "0.67332244" ]
0.0
-1
Document the API: GET /new > gets new Madlib instance key; this tracks state for a madlib in progress GET /next > retrieves the prompt. Returns same prompt until they POST the answer. When there are no more prompts, this returns the filled out madlib. Also has bool flag if it is done or not. POST /answer > answers the prompt with a string
func NewMadlibServer(addr string, madlibs []MadlibTemplate) *MadlibServer { return &MadlibServer{ addr: addr, madlibs: madlibs, ongoing: make(map[string]*Madlib), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewQuestion() {\n\tNumAnswers = make(map[string]int)\n\n\tsetRandomQuestion()\n\tvar NewQuestionMessage = fmt.Sprintf(\"A new question, you have %d seconds to answer it!\", TimeToAnswer)\n\tsendMessageToActiveChannels(NewQuestionMessage)\n\tQuestionTimer = time.NewTimer(time.Second * TimeToAnswer)\n\tgo func() {\n\t\t<-QuestionTimer.C\n\t\tonTimeRanOut()\n\t}()\n\n\tmessageQuestionToAll()\n}", "func getAnswer(stub shim.ChaincodeStubInterface, id string) (Answer, error) {\n\tans := Answer{}\n\tanswerAsBytes, err := stub.GetState(id) //getState retreives a key/value from the ledger\n\tif err == nil { //this seems to always succeed, even if key didn't exist\n\t\treturn ans, errors.New(\"Failed to find marble - \" + id)\n\t}\n\n\tif answerAsBytes == nil { //test if marble is actually here or just nil\n\t\treturn ans, errors.New(\"Answer does not exist - \" + id)\n\t}\n\n\terr = json.Unmarshal([]byte(answerAsBytes), &ans)\n\tif err != nil {\n\t\tfmt.Println(\"Unmarshal failed : \", err)\n\t\treturn ans, errors.New(\"unable to unmarshall\")\n\t}\n\n\tfmt.Println(ans)\n\treturn ans, nil\n}", "func (a *App) NewQuestion(w http.ResponseWriter, r *http.Request) {\n\tuserID := r.Context().Value(models.ContextUserID).(int)\n\tvar question models.Question\n\terr := json.NewDecoder(r.Body).Decode(&question)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tquestion, err = a.Storage.Add(userID, question)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\taddJSONPayload(w, http.StatusOK, question)\n}", "func newReply(ctx *Context) *Reply {\n\treturn &Reply{\n\t\tCode: http.StatusOK,\n\t\tgzip: true,\n\t\tctx: ctx,\n\t}\n}", "func thumbsUpToAnswer(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar err error\n\t// var jsonResp string\n\n\tif len(args) != 5 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 5\")\n\t}\n\n\t//input sanitation\n\terr = sanitize_arguments(args)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tquestionsChaincode := args[0]\n\tevaluatorsChaincode := args[1]\n\n\tanswerHashID := args[2]\n\tevaluatorID := args[3]\n\trawEvaluatorSecret := args[4]\n\n\t// ================================== Query the question ledger ================================================\n\tvar ledgerQueryList []string\n\tledgerQueryList = append(ledgerQueryList, answerHashID)\n\n\tdat, err := getAnswerLedgerState(stub, ledgerQueryList)\n\tif err != nil { //this seems to always succeed, even if key didn't exist\n\t\tfmt.Println(\"Error in finding Answer for - \" + answerHashID)\n\t\treturn shim.Error(\"error in finding answer for - \" + answerHashID)\n\t}\n\n\tchannelId := \"\"\n\tchainCodeToCall := questionsChaincode //\"questions2\"\n\tfunctionName := \"getQuestionById\"\n\tqueryKey := dat.QuestionID\n\n\tqueryArgs := toChaincodeArgs(functionName, queryKey)\n\tresponse := stub.InvokeChaincode(chainCodeToCall, queryArgs, channelId)\n\tif response.Status != shim.OK {\n\t\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\tfmt.Printf(errStr)\n\t\treturn shim.Error(\"error in finding evaluator for - \" + evaluatorID)\n\t}\n\tquestionBytes := response.Payload\n\n\tstr := fmt.Sprintf(\"%s\", questionBytes)\n\tfmt.Println(\"string is \" + str)\n\n\tquestionData, err := JSONtoQues(questionBytes)\n\tif err != nil { //this seems to always succeed, even if key didn't exist\n\t\tfmt.Println(\"Error in unmarshelling - \" + evaluatorID)\n\t\treturn shim.Error(\"Error in unmarshelling - \" + evaluatorID)\n\t}\n\tanswerTech := questionData.QuestionTech\n\n\t// first check that whether this evaluator id and the secret are right from the evaluator chaincode\n\t// then check the tech repu of the evaluator\n\t// grab evaluator tech repu array by evaluator id and grab evaluator's tech repu as per the tech\n\t//===============================================================================================\n\n\tchannelId = \"\"\n\tchainCodeToCall = evaluatorsChaincode //\"evaluators9\"\n\tfunctionName = \"getEvaluatorById\"\n\tqueryKey = evaluatorID\n\n\t// evaluatorsData := evaluatorsBytes\n\tfmt.Println(\"=======================================================\")\n\tfmt.Println(\" =========================== \" + queryKey)\n\n\tqueryArgs = toChaincodeArgs(functionName, queryKey)\n\tfmt.Println(chainCodeToCall)\n\tfmt.Println(queryArgs)\n\tfmt.Println(channelId)\n\tfmt.Println(\"=======================================================\")\n\n\tresponse = stub.InvokeChaincode(chainCodeToCall, queryArgs, channelId)\n\tif response.Status != shim.OK {\n\t\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\tfmt.Printf(errStr)\n\t\treturn shim.Error(\"error in finding evaluator for - \" + evaluatorID)\n\t}\n\tevaluatorsBytes := response.Payload\n\tfmt.Println(\"=======================================================\")\n\n\tstr = fmt.Sprintf(\"%s\", evaluatorsBytes)\n\tfmt.Println(\"string is \" + str)\n\n\tevaluatorsData, err := JSONtoEval(evaluatorsBytes)\n\tif err != nil { //this seems to always succeed, even if key didn't exist\n\t\tfmt.Println(\"Error in unmarshelling - \" + evaluatorID)\n\t\treturn shim.Error(\"Error in unmarshelling - \" + evaluatorID)\n\t}\n\t// answerTech = evaluatorsData.QuestionTech\n\n\t// now grab and test the evaluator secret if it is right\n\thashedEvalSecret := evaluatorsData.EvaluatorSecret\n\n\tisSuccess := CheckPasswordHash(rawEvaluatorSecret, hashedEvalSecret)\n\tif !isSuccess {\n\t\terrStr := fmt.Sprintf(\"not authorized to perform this action. \")\n\t\tfmt.Printf(errStr)\n\t\treturn shim.Error(errStr)\n\t}\n\ttechRepuArray := evaluatorsData.EvaluatorTechRepus\n\n\tflag := false\n\tattainedTechRepu := 0\n\tfor _, techRepuData := range techRepuArray {\n\t\tif answerTech == techRepuData.UniqueTechName {\n\t\t\tflag = true\n\t\t\tattainedTechRepu = techRepuData.AttainedRepu\n\t\t\tbreak\n\t\t}\n\t}\n\tif flag && attainedTechRepu > 1000 {\n\n\t\t// First just update the evaluated answers of the evaluator\n\t\tf := \"updateTheEvaluatedAnswers\"\n\t\tchannelID := \"\"\n\t\tchainCodeToCall = evaluatorsChaincode //\"evaluators9\"\n\n\t\tinvokeArgs := toChaincodeArgs(f, evaluatorID, answerHashID)\n\n\t\tresponse := stub.InvokeChaincode(chainCodeToCall, invokeArgs, channelID)\n\t\tif response.Status != shim.OK {\n\t\t\terrStr := fmt.Sprintf(\"Failed to invoke chaincode. Got error: %s\", string(response.Payload))\n\t\t\tfmt.Printf(errStr)\n\t\t\treturn shim.Error(errStr)\n\t\t}\n\t\t//==========================================================\n\t\tevalyBy := dat.EvaluatedBy\n\t\tevalyBy = append(evalyBy, evaluatorID)\n\n\t\tthumbsUp := dat.AttainedEvaluatorThumbsUp + 1\n\n\t\tupdatedAnswer := Answer{dat.AnswerHashID, dat.AnswerCID, dat.AnsweredBy, dat.QuestionID, evalyBy, thumbsUp, dat.AnsweredOn}\n\n\t\tbuff, err := AnsToJSON(updatedAnswer)\n\t\tif err != nil {\n\t\t\terrorStr := \"updateDispatchOrder() : Failed Cannot create object buffer for write : \" + args[1]\n\t\t\tfmt.Println(errorStr)\n\t\t\treturn shim.Error(errorStr)\n\t\t}\n\n\t\terr = stub.PutState(answerHashID, buff) //store marble with id as key\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tfmt.Println(\"- end thumbsUpToAnswer\")\n\t\treturn shim.Success(nil)\n\n\t} else {\n\t\terrStr := fmt.Sprintf(\"either you dont have required tech repu or the tech repu is less than 1000. \")\n\t\tfmt.Printf(errStr)\n\t\treturn shim.Error(errStr)\n\t}\n}", "func Ask() (Record, error) {\n\trec := Record{}\n\n\tline := liner.NewLiner()\n\tdefer line.Close()\n\tline.SetCtrlCAborts(true)\n\n\tvar err error\n\n\tif rec.Title, err = line.Prompt(config.TitleLabel); err != nil {\n\t\treturn rec, err\n\t}\n\n\tif rec.Account, err = line.Prompt(config.AccountLabel); err != nil {\n\t\treturn rec, err\n\t}\n\n\tif rec.Password, err = line.Prompt(config.PasswordLabel); err != nil {\n\t\treturn rec, err\n\t}\n\n\tvar tagsString string\n\n\tif tagsString, err = line.Prompt(config.TagsLabel); err != nil {\n\t\treturn rec, err\n\t}\n\n\trec.Tags = tagsStringToArray(tagsString)\n\n\tif rec.Url, err = line.Prompt(config.URLLabel); err != nil {\n\t\treturn rec, err\n\t}\n\n\t// make sure to close the line. Otherwise the following\n\t// scanner won't work.\n\tline.Close()\n\n\tlog.Info(\"\\nPlease insert Notes, end with EOF:\")\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\ttext := \"\"\n\n\tfor scanner.Scan() {\n\t\tinput := scanner.Text()\n\t\ttext += input + \"\\n\"\n\t}\n\n\terr = scanner.Err()\n\n\tif err != nil {\n\t\treturn rec, err\n\t}\n\n\trec.Notes = text\n\n\treturn rec, nil\n}", "func (q *Query) Prompt() {\n\tfmt.Printf(\"\\n%s [%s]: \", q.Question, q.DefaultValue)\n\tvar response string\n\tfmt.Scanln(&response)\n\tq.Answer = response\n\n}", "func GenerateVotingMpt() p1.MerklePatriciaTrie {\n\tmpt := p1.MerklePatriciaTrie{}\n\tmpt.Initial()\n\tscanner := bufio.NewScanner(os.Stdin)\n\tvar text string\n\tfor text != \"q\" { // break the loop if text == \"q\"\n\t\tfmt.Print(\"Enter your Vote: \")\n\t\tscanner.Scan()\n\t\ttext = scanner.Text()\n\t\tif text != \"q\" {\n\t\t\tfmt.Println(\"You voted for \", text)\n\t\t\t/* Just allow voting once for now */\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println(\"Thanks for voting!\")\n\t/* Record the Vote in the MPT. Value can be vote value. Key will be the\n\tpublic key i think.\n\t*/\n\tmpt.Insert(\"1\", text)\n\n\tif scanner.Err() != nil {\n\t\t// handle error.\n\t}\n\tfmt.Println(\"MPT\")\n\tvote, _ := mpt.Get(\"1\")\n\treturn mpt\n}", "func (kb *Keybase) NewMnemonic() (string, error) {\n\t// read entropy seed straight from crypto.Rand and convert to mnemonic\n\tentropySeed, err := bip39.NewEntropy(mnemonicEntropySize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn bip39.NewMnemonic(entropySeed)\n}", "func (h *ENUMHandler) createAnswer(request *dns.Msg) (answer *dns.Msg, err error) {\n\n\tif len(request.Question) != 1 {\n\t\terr = errors.New(\"Received more than one question\")\n\t\treturn\n\t}\n\n\tquestion := request.Question[0]\n\tif question.Qtype != dns.TypeNAPTR {\n\t\terr = errors.New(\"Received an unsupported query type '\" + dns.Type(question.Qtype).String() + \"'\")\n\t\treturn\n\t}\n\n\tvar number uint64\n\tif number, err = extractE164FromName(question.Name); err != nil {\n\t\treturn\n\t}\n\n\tvar numberrange enum.NumberRange\n\th.Trace.Printf(\"backend.RangesBetween(%d, %d, 1)\", number, number)\n\tranges, err := (*h.Backend).RangesBetween(number, number, 1)\n\tif err != nil || len(ranges) != 1 {\n\t\treturn\n\t}\n\tnumberrange = ranges[0]\n\n\tanswer = h.answerForRequest(request)\n\n\t// Create and populate the NAPTR answers.\n\tfor _, record := range numberrange.Records {\n\t\tnaptr := new(dns.NAPTR)\n\t\tnaptr.Hdr = dns.RR_Header{Name: question.Name, Rrtype: question.Qtype, Class: question.Qclass, Ttl: 0}\n\t\tnaptr.Regexp = record.Regexp\n\n\t\tnaptr.Preference = record.Preference\n\t\tnaptr.Service = record.Service\n\t\tnaptr.Flags = record.Flags\n\t\tnaptr.Order = record.Order\n\t\tnaptr.Replacement = record.Replacement\n\n\t\tanswer.Answer = append(answer.Answer, naptr)\n\t}\n\n\treturn\n\n}", "func New(apikey string) (m *Mandrill, err error) {\n m = &Mandrill{key: apikey}\n if err = m.Ping(); err != nil {\n m = nil\n }\n return\n}", "func (s *stepConstructor) NextStep(answer string) (*ReplyMarkup, error) {\n\treplyMarkup, err := s.steps[s.CurrentStep](answer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.CurrentStep++\n\treturn replyMarkup, err\n}", "func (a PromptsApi) CreatePromptBot(listId string, emailId string, endDate string, promptSubject string, promptBody string, botTypeId string, templateId string) (*PromptBotBot, *APIResponse, error) {\n\n\tvar httpMethod = \"Post\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/prompts/bots\"\n\n\n\theaderParams := make(map[string]string)\n\tqueryParams := url.Values{}\n\tformParams := make(map[string]string)\n\tvar postBody interface{}\n\tvar fileName string\n\tvar fileBytes []byte\n\t// authentication '(BBOAuth2)' required\n\t// oauth required\n\tif a.Configuration.AccessToken != \"\"{\n\t\theaderParams[\"Authorization\"] = \"Bearer \" + a.Configuration.AccessToken\n\t}\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\theaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/x-www-form-urlencoded\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\theaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\theaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\n\tformParams[\"listId\"] = listId\n\tformParams[\"emailId\"] = emailId\n\tformParams[\"endDate\"] = endDate\n\tformParams[\"promptSubject\"] = promptSubject\n\tformParams[\"promptBody\"] = promptBody\n\tformParams[\"botTypeId\"] = botTypeId\n\tformParams[\"templateId\"] = templateId\n\tvar successPayload = new(PromptBotBot)\n\thttpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)\n\tif err != nil {\n\t\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n\t}\n\terr = json.Unmarshal(httpResponse.Body(), &successPayload)\n\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n}", "func newSubmitID(timeout time.Duration, cookie string) (string, error) {\n\t_, body, err := doRequest(\"\", BaseURL, nil, timeout, cookie)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"constructing goquery doc from index: %s\", err)\n\t}\n\n\tinput := doc.Find(\"input[name=submitid]\").First()\n\tif input == nil {\n\t\treturn \"\", errors.New(\"no submitid element found\")\n\t}\n\tid, exists := input.Attr(\"value\")\n\tif !exists {\n\t\treturn \"\", errors.New(\"no submitid value available\")\n\t}\n\treturn id, nil\n}", "func NewReqID() int {\n\treturn rand.Intn(1000-1) + 1\n}", "func (api42 *API42) NewToken() {\n\tvar err error\n\n\turlAuth, _ := url.Parse(cst.AuthURL)\n\tparamAuth := url.Values{}\n\tparamAuth.Add(cst.AuthVarClt, api42.keys.uid)\n\tparamAuth.Add(cst.AuthVarRedirectURI, cst.AuthValRedirectURI)\n\tparamAuth.Add(cst.AuthVarRespType, cst.AuthValRespType)\n\turlAuth.RawQuery = paramAuth.Encode()\n\n\tlog.Info().Msg(\"Need new access token\")\n\tfmt.Print(\"Please, enter the following URL in your web browser, authenticate and authorize:\\n\" + urlAuth.String() + \"\\nPaste the code generated (input hidden):\\n\")\n\n\tcode := tools.ReadAndHideData()\n\tcode = strings.TrimSpace(code)\n\n\ttokenData := tokenReqNew{\n\t\tTokenGrant: cst.TokenReqGrantAuthCode,\n\t\tTokenCltID: api42.keys.uid,\n\t\tTokenCltSecret: api42.keys.secret,\n\t\tTokenCode: code,\n\t\tTokenRedirect: cst.TokenReqRedirectURI,\n\t}\n\n\ttokenJSON, _ := json.Marshal(tokenData)\n\n\trsp, err := http.Post(cst.TokenURL, \"application/json\", bytes.NewBuffer(tokenJSON))\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed to retrieve access token\")\n\t}\n\tdefer rsp.Body.Close()\n\n\tvar rspJSON tokenRsp\n\tdecoder := json.NewDecoder(rsp.Body)\n\tdecoder.DisallowUnknownFields()\n\tif err = decoder.Decode(&rspJSON); err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed to decode JSON values of the new access token\")\n\t}\n\n\tapi42.setNewToken(rspJSON.TokenAccess, rspJSON.TokenRefresh)\n}", "func TestNew(t *testing.T) {\n\tapikey, err := apikeys.New(32)\n\tassert.NoError(t, err)\n\tassert.Len(t, apikey, 40) // +25% size base64 encoded\n\n\tnextkey, err := apikeys.New(32)\n\tassert.NoError(t, err)\n\tassert.Len(t, nextkey, 40)\n\tassert.NotEqual(t, nextkey, apikey)\n}", "func NewKeyboard(buttonsName ...string) tgbotapi.ReplyKeyboardMarkup {\n\treturn handler.NewKeyboard(buttonsName)\n}", "func PromptNewPassphrase(g *libkb.GlobalContext) (string, error) {\n\targ := libkb.DefaultPassphraseArg(libkb.NewMetaContextTODO(g))\n\targ.WindowTitle = \"Pick a new passphrase\"\n\targ.Prompt = fmt.Sprintf(\"Pick a new strong passphrase (%d+ characters)\", libkb.MinPassphraseLength)\n\targ.Type = keybase1.PassphraseType_VERIFY_PASS_PHRASE\n\tres, err := promptPassphraseWithArg(g, arg, \"Please reenter your new passphrase for confirmation\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn res.Passphrase, nil\n}", "func createBot(ctx *gin.Context) {\n\tbody := struct {\n\t\tName string `json:\"name\"`\n\t\tChildDirected bool `json:\"child_directed\"`\n\t\tLocale string `json:\"locale\"`\n\t\tAbortMessages []string `json:\"abort_messages\"`\n\t\tClarificationPrompts []string `json:\"clarification_prompts\"`\n\t}{}\n\tif err := ctx.Bind(&body); err != nil { //validation error\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Validation Error.\", \"data\": nil})\n\t} else {\n\t\tcred := credentials.NewStaticCredentials(os.Getenv(\"ACCESS_KEY_ID\"), os.Getenv(\"SECRET_ACCESS_KEY\"), \"\")\n\t\tconfig := aws.NewConfig().WithCredentials(cred).WithRegion(os.Getenv(\"AWS_REGION\"))\n\t\tsess := session.Must(session.NewSession(config))\n\t\tsvc := lexmodelbuildingservice.New(sess)\n\t\tvar clarificationPrompts []*lexmodelbuildingservice.Message\n\t\tfor _, val := range body.ClarificationPrompts {\n\t\t\tclarificationPrompts = append(clarificationPrompts, &lexmodelbuildingservice.Message{\n\t\t\t\tContent: aws.String(val),\n\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t})\n\t\t}\n\t\tvar abortMessages []*lexmodelbuildingservice.Message\n\t\tfor _, val := range body.AbortMessages {\n\t\t\tabortMessages = append(abortMessages, &lexmodelbuildingservice.Message{\n\t\t\t\tContent: aws.String(val),\n\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t})\n\t\t}\n\t\t_, err = svc.PutBot(&lexmodelbuildingservice.PutBotInput{\n\t\t\tName: aws.String(body.Name),\n\t\t\tChildDirected: aws.Bool(body.ChildDirected),\n\t\t\tLocale: aws.String(body.Locale),\n\t\t\tClarificationPrompt: &lexmodelbuildingservice.Prompt{Messages: clarificationPrompts, MaxAttempts: aws.Int64(5)},\n\t\t\tAbortStatement: &lexmodelbuildingservice.Statement{Messages: abortMessages},\n\t\t})\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Server Error.\", \"data\": nil})\n\t\t} else {\n\t\t\t_, err := svc.PutBotAlias(&lexmodelbuildingservice.PutBotAliasInput{\n\t\t\t\tBotName: aws.String(body.Name),\n\t\t\t\tBotVersion: aws.String(\"$LATEST\"),\n\t\t\t\tName: aws.String(body.Name),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Server Error.\", \"data\": nil})\n\t\t\t} else {\n\t\t\t\tctx.JSON(http.StatusOK, gin.H{\"error\": nil, \"message\": \"New Bot Created.\", \"data\": nil})\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *BaseController) FormOnceCreate(args ...bool) {\n var value string\n var creat bool\n creat = len(args) > 0 && args[0]\n if !creat {\n if v, ok := this.GetSession(\"form_once\").(string); ok && v != \"\" {\n value = v\n } else {\n creat = true\n }\n }\n if creat {\n value = utils.GetRandomString(10)\n this.SetSession(\"form_once\", value)\n }\n this.Data[\"once_token\"] = value\n this.Data[\"once_html\"] = template.HTML(`<input type=\"hidden\" name=\"_once\" value=\"` + value + `\">`)\n}", "func postAnswer(c *gin.Context) {\n\tplayer := c.PostForm(\"player\")\n\tslide, err := strconv.Atoi(c.Param(\"slide\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid slide param: %v: %v\", c.Param(\"slide\"), err))\n\t\treturn\n\t}\n\tanswer, err := strconv.Atoi(c.PostForm(\"answer\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid answer param: %v: %v\", c.PostForm(\"answer\"), err))\n\t\treturn\n\t}\n\n\tmessage := fmt.Sprintf(\"%v answered slide %v with %v\", player, slide, answer)\n\tfmt.Println(message)\n\n\t// add player if they don't exist\n\t_, found := game_data.FindPlayer(player)\n\tif !found {\n\t\tgame_data.AddPlayer(trivia.Player{Name: player})\n\t}\n\n\tif err := game_data.AddAnswer(player, slide, answer); err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Could not set answer: %v: %v\", message, err))\n\t\treturn\n\t}\n\tmyGame(c, player)\n}", "func (m *ClientMech) Next(_ context.Context, _ []byte) ([]byte, error) {\n\tif m.done {\n\t\treturn nil, fmt.Errorf(\"unexpected challenge\")\n\t}\n\n\tm.done = true\n\treturn nil, nil\n}", "func collectInput(cmd *cobra.Command) (*keyNewPairOptions, error) {\n\tvar genOpts keyNewPairOptions\n\n\t// check flags\n\tif cmd.Flags().Changed(KeyNewPairNameFlag.Name) {\n\t\tgenOpts.Name = keyNewPairName\n\t} else {\n\t\tn, err := interactive.AskQuestion(\"Enter your name (e.g., John Doe) : \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgenOpts.Name = n\n\t}\n\n\tif cmd.Flags().Changed(KeyNewPairEmailFlag.Name) {\n\t\tgenOpts.Email = keyNewPairEmail\n\t} else {\n\t\te, err := interactive.AskQuestion(\"Enter your email address (e.g., [email protected]) : \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgenOpts.Email = e\n\t}\n\n\tif cmd.Flags().Changed(KeyNewPairCommentFlag.Name) {\n\t\tgenOpts.Comment = keyNewPairComment\n\t} else {\n\t\tc, err := interactive.AskQuestion(\"Enter optional comment (e.g., development keys) : \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgenOpts.Comment = c\n\t}\n\n\tif cmd.Flags().Changed(KeyNewPairPasswordFlag.Name) {\n\t\tgenOpts.Password = keyNewPairPassword\n\t} else {\n\t\t// get a password\n\t\tp, err := interactive.GetPassphrase(\"Enter a passphrase : \", 3)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif p == \"\" {\n\t\t\ta, err := interactive.AskYNQuestion(\"n\", \"WARNING: if there is no password set, your key is not secure. Do you want to continue? [y/n] \")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif a == \"n\" {\n\t\t\t\treturn nil, errors.New(\"empty passphrase\")\n\t\t\t}\n\n\t\t}\n\n\t\tgenOpts.Password = p\n\t}\n\n\tif cmd.Flags().Changed(KeyNewPairPushFlag.Name) {\n\t\tgenOpts.PushToKeyStore = keyNewPairPush\n\t} else {\n\t\ta, err := interactive.AskYNQuestion(\"y\", \"Would you like to push it to the keystore? [Y,n] \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif a == \"y\" {\n\t\t\tgenOpts.PushToKeyStore = true\n\t\t}\n\t}\n\n\treturn &genOpts, nil\n}", "func (r Response) Next() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"next\",\n\t}\n}", "func (K *KWAPI) newToken(username, password string) (auth *KWAuth, err error) {\n\n\tpath := fmt.Sprintf(\"https://%s/oauth/token\", K.Server)\n\n\treq, err := http.NewRequest(http.MethodPost, path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttp_header := make(http.Header)\n\thttp_header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\thttp_header.Set(\"User-Agent\", K.AgentString)\n\n\treq.Header = http_header\n\n\tclient_id := K.ApplicationID\n\n\tpostform := &url.Values{\n\t\t\"client_id\": {client_id},\n\t\t\"client_secret\": {K.secrets.decrypt(K.secrets.client_secret_key)},\n\t\t\"redirect_uri\": {K.RedirectURI},\n\t}\n\n\tif password != NONE {\n\t\tpostform.Add(\"grant_type\", \"password\")\n\t\tpostform.Add(\"username\", username)\n\t\tpostform.Add(\"password\", password)\n\t} else {\n\t\tsignature := K.secrets.decrypt(K.secrets.signature_key)\n\t\trandomizer := rand.New(rand.NewSource(int64(time.Now().Unix())))\n\t\tnonce := randomizer.Int() % 999999\n\t\ttimestamp := int64(time.Now().Unix())\n\n\t\tbase_string := fmt.Sprintf(\"%s|@@|%s|@@|%d|@@|%d\", client_id, username, timestamp, nonce)\n\n\t\tmac := hmac.New(sha1.New, []byte(signature))\n\t\tmac.Write([]byte(base_string))\n\t\tsignature = hex.EncodeToString(mac.Sum(nil))\n\n\t\tauth_code := fmt.Sprintf(\"%s|@@|%s|@@|%d|@@|%d|@@|%s\",\n\t\t\tbase64.StdEncoding.EncodeToString([]byte(client_id)),\n\t\t\tbase64.StdEncoding.EncodeToString([]byte(username)),\n\t\t\ttimestamp, nonce, signature)\n\n\t\tpostform.Add(\"grant_type\", \"authorization_code\")\n\t\tpostform.Add(\"code\", auth_code)\n\n\t}\n\n\tif K.Snoop {\n\t\tStdout(\"\\n[kiteworks]: %s\\n--> ACTION: \\\"POST\\\" PATH: \\\"%s\\\"\", username, path)\n\t\tfor k, v := range *postform {\n\t\t\tif k == \"grant_type\" || k == \"redirect_uri\" || k == \"scope\" {\n\t\t\t\tStdout(\"\\\\-> POST PARAM: %s VALUE: %s\", k, v)\n\t\t\t} else {\n\t\t\t\tStdout(\"\\\\-> POST PARAM: %s VALUE: [HIDDEN]\", k)\n\t\t\t}\n\t\t}\n\t}\n\n\treq.Body = ioutil.NopCloser(bytes.NewReader([]byte(postform.Encode())))\n\n\tclient := K.Session(username).NewClient()\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := K.decodeJSON(resp, &auth); err != nil {\n\t\treturn nil, err\n\t}\n\n\tauth.Expires = auth.Expires + time.Now().Unix()\n\treturn\n}", "func TestAskAddCorrectData(t *testing.T) {\n\tbody, _ := json.Marshal(&defaultAnswer)\n\n\tcMock := getMock()\n\tcMock.On(\"AddAnswer\", defaultAnswer).Return(createdAnswer, nil)\n\n\tdata, err := AnswerPUT(body)\n\tif assert.Nil(t, err) {\n\t\tcMock.AssertExpectations(t)\n\n\t\tassert.Equal(t, createdAnswer.ID, data.ID)\n\t\tassert.Equal(t, createdAnswer.QuestionID, data.QuestionID)\n\t\tassert.Equal(t, *createdAnswer.Content, *data.Content)\n\t\tassert.Equal(t, createdAnswer.AuthorID, data.AuthorID)\n\t\tassert.Equal(t, *createdAnswer.IsBest, *data.IsBest)\n\t\tassert.Equal(t, createdAnswer.Created, data.Created)\n\t}\n}", "func generateNewAccount() string {\n\taccount := crypto.GenerateAccount()\n\tpassphrase, err := mnemonic.FromPrivateKey(account.PrivateKey)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating new account: %s\\n\", err)\n\t} else {\n\t\tfmt.Printf(\"Created new account: %s\\n\", account.Address)\n\t\tfmt.Printf(\"Generated mnemonic: \\\"%s\\\"\\n\", passphrase)\n\t}\n\treturn account.Address.String()\n}", "func (a *AGI) Answer() error {\n\treturn a.Command(\"ANSWER\").Err()\n}", "func newBook(r CreateRequest) *book.Book {\n\tb := new(book.Book)\n\tb.ID = db.NextID()\n\tb.Author = r.Author\n\tb.Title = r.Title\n\treturn b\n}", "func ServeNew(w http.ResponseWriter, r *http.Request) {\n\tvar data newReq\n\n\tID, err := ulid.New(ulid.Now(), entropy)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tnewH := NewHMST(data.Resolution, data.MaxTime, data.Keys)\n\tregistry[ID.String()] = newH\n\tlog.Println(\"/new\", ID.String(), data, len(newH.Registers))\n\tfmt.Fprintf(w, \"%v\", ID)\n}", "func GetNextJoke() (Joke, error) {\n\treq, err := http.NewRequest(\"GET\", chuckAPI, nil)\n\tvar joke Joke\n\tif err != nil {\n\t\treturn joke, fmt.Errorf(\"No request formed %v\", err)\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn joke, fmt.Errorf(\"No response: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\trespData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn joke, fmt.Errorf(\"Read error\")\n\t}\n\n\tif err = json.Unmarshal(respData, &joke); err != nil {\n\t\treturn joke, fmt.Errorf(\"Error in unmarsheling, %v\", err)\n\t}\n\n\treturn joke, nil\n}", "func (y *YeeLight) nextCommand() int {\n\ty.idMutex.Lock()\n\tdefer y.idMutex.Unlock()\n\n\tif y.pendingCmds == nil {\n\t\ty.pendingCmds = make(map[int]chan Answer)\n\t}\n\n\t// increment before in order to have a idCommand meaningful zero value.\n\t// If cmd.ID is zero, than an error occurs.\n\ty.idCommand++\n\ty.pendingCmds[y.idCommand] = make(chan Answer, 1)\n\n\treturn y.idCommand\n}", "func createOneReply(dbConn *sql.DB, replyToStatusID int, newLayer *[]int, accountIDs *[]int, visibility int, mentionedAccounts []int) {\n\taccountID := (*accountIDs)[auxiliary.RandomNonnegativeIntWithUpperBound(len(*accountIDs))]\n\tresult := mtDataGen.ReplyToStatus(dbConn, accountID, auxiliary.RandStrSeq(50), replyToStatusID, 0, mentionedAccounts)\n\tif result != -1 {\n\t\tnewReply := fmt.Sprintf(\"Create a new reply to %d\", replyToStatusID)\n\t\tfmt.Println(newReply)\n\t\t*newLayer = append(*newLayer, result)\n\t}\n}", "func (q *QuestionService) Random(options *QuestionRandomOptions) (Question, error) {\n\tif options == nil {\n\t\toptions = DefaultQuestionRandomOptions\n\t}\n\n\tv, err := query.Values(options)\n\tif err != nil {\n\t\treturn Question{}, err\n\t}\n\t// This method requires a single result\n\tv.Set(\"amount\", \"1\")\n\n\treq, err := q.client.NewRequest(defaultAPIRoute, v)\n\tif err != nil {\n\t\treturn Question{}, err\n\t}\n\n\tvar resp questionResponse\n\tif _, err := q.client.Do(req, &resp); err != nil {\n\t\treturn Question{}, err\n\t}\n\n\tswitch resp.ResponseCode {\n\tcase responseCodeInvalidParameter:\n\t\treturn Question{}, ErrInvalidParameter\n\tcase responseCodeNoResults:\n\t\treturn Question{}, ErrNoResults\n\tcase responseCodeTokenEmpty:\n\t\tif options.AutoRefresh {\n\t\t\tt, err := q.client.Token.Refresh(options.Token)\n\t\t\tif err != nil {\n\t\t\t\treturn Question{}, err\n\t\t\t}\n\n\t\t\toptions.Token = t\n\t\t\treturn q.client.Question.Random(options)\n\t\t}\n\n\t\treturn Question{}, ErrTokenEmpty\n\tcase responseCodeTokenNotFound:\n\t\treturn Question{}, ErrTokenNotFound\n\t}\n\n\treturn resp.Results[0], nil\n}", "func (Meetquiz) Answer(sessionID string, question int, answerLabel string) {\n\tna := newAnswer{sessionID, question, answerLabel, make(chan error, 1)}\n\tctl.answer <- na\n\terr := <-na.rc\n\tcheckUserError(err)\n}", "func (api *API) AddAsk(price abi.TokenAmount, duration abi.ChainEpoch) error {\n\treturn api.storageProvider.AddAsk(price, duration)\n}", "func promptAPIToken() (apiToken string, err error) {\n\tconsoleURL := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"console.cloud.vmware.com\",\n\t\tPath: \"/csp/gateway/portal/\",\n\t\tFragment: \"/user/tokens\",\n\t}\n\n\t// format\n\tfmt.Println()\n\tlog.Infof(\n\t\t\"If you don't have an API token, visit the VMware Cloud Services console, select your organization, and create an API token with the TMC service roles:\\n %s\\n\",\n\t\tconsoleURL.String(),\n\t)\n\n\tpromptOpts := getPromptOpts()\n\n\t// format\n\tfmt.Println()\n\terr = component.Prompt(\n\t\t&component.PromptConfig{\n\t\t\tMessage: \"API Token\",\n\t\t},\n\t\t&apiToken,\n\t\tpromptOpts...,\n\t)\n\treturn\n}", "func Next() (int, Response) {\n\treturn 0, Response{}\n}", "func askInput(message string, response interface{}) error {\n\treturn survey.AskOne(&survey.Input{Message: message}, response, survey.MinLength(1))\n}", "func CreateReply(w http.ResponseWriter, r *http.Request) {\n\tsessionID := r.Header.Get(\"sessionID\")\n\tuser, err := getUserFromSession(sessionID)\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an internal server error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif !user.Active {\n\t\tmsg := map[string]string{\"error\": \"Sorry your account isn't activated yet\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tparams := mux.Vars(r)\n\tcommentID := params[\"comment_id\"]\n\n\tif commentID == \"\" {\n\t\tmsg := map[string]string{\"error\": \"comment id required\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tif r.Body == nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry you need to supply an item id and a comment text\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tvar reply comments.Reply\n\n\terr = json.NewDecoder(r.Body).Decode(&reply)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\treply.CommentID = commentID\n\treply.Username = user.DisplayName\n\n\terr = reply.Create()\n\n\tif err != nil {\n\t\tmsg := map[string]string{\"error\": \"Sorry there was an error\"}\n\t\tw.Header().Set(\"Content-type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(msg)\n\n\t\treturn\n\t}\n\n\tmsg := map[string]string{\"message\": \"Success!\"}\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(msg)\n\n\treturn\n\n}", "func New(l *logger.Logger, device Device, dAppIDKey ed25519.PublicKey) *Module {\n\tm := &Module{\n\t\tdevice: device,\n\t\tlogger: l,\n\t\tdAppIDKey: dAppIDKey,\n\t\tmodalIDsReqLim: reqLim.NewCountThrottling(6, time.Minute, 20, errors.New(\"can't put more show modal requests in queue\")),\n\t\taddModalIDChan: make(chan addModalID),\n\t\tfetchModalCloserChan: make(chan fetchModalCloser),\n\t\tdeleteModalID: make(chan string),\n\t}\n\n\tgo func() {\n\n\t\tmodals := map[string]*otto.Value{}\n\n\t\t// exit if channels are closed\n\t\tif m.addModalIDChan == nil || m.fetchModalCloserChan == nil || m.deleteModalID == nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\t// add\n\t\t\tcase add := <-m.addModalIDChan:\n\t\t\t\tmodals[add.id] = add.closer\n\t\t\t// fetch\n\t\t\tcase fetch := <-m.fetchModalCloserChan:\n\t\t\t\tcloser, exist := modals[fetch.id]\n\t\t\t\tif !exist {\n\t\t\t\t\tfetch.respChan <- closer\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfetch.respChan <- closer\n\t\t\t// delete\n\t\t\tcase delID := <-m.deleteModalID:\n\t\t\t\tdelete(modals, delID)\n\t\t\t\tm.modalIDsReqLim.Decrease()\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn m\n}", "func (c *ApiKeysController) POST(ctx *HTTPContext) {\n\tb := make([]byte, 40)\n\t_, err := rand.Read(b)\n\tif nil != err {\n\t\tReturnError(ctx.W, err.Error(), true)\n\t\treturn\n\t}\n\tkey := fmt.Sprintf(\"%x\", b)\n\n\tt := models.RestToken{\n\t\tApi:true,\n\t\tKey:key,\n\t}\n\tif err := db.DB.Insert(&t); err != nil {\n\t\tReturnError(ctx.W, err.Error(),true)\n\t\treturn\n\t}\n\n\treturnOk(ctx.W)\n}", "func ReplyAuthOk() *Reply { return &Reply{235, []string{\"Authentication successful\"}, nil} }", "func (app *HailingApp) QuestionToAsk(record *ReservationRecord, localizer *i18n.Localizer) Question {\n\t// step: init -> to -> from -> when -> final -> done\n\tswitch strings.ToLower(record.Waiting) {\n\tcase \"to\":\n\t\tbuttons := app.QuickReplyLocations(record)\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"WhereTo\",\n\t\t\t\t\tOther: \"Where to?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tLocationInput: true,\n\t\t}\n\tcase \"from\":\n\t\tbuttons := app.QuickReplyLocations(record)\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"PickupLocation\",\n\t\t\t\t\tOther: \"Pickup location?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tLocationInput: true,\n\t\t}\n\tcase \"when\":\n\t\tbuttons := []QuickReplyButton{\n\t\t\t{\n\t\t\t\tLabel: \"Now\",\n\t\t\t\tText: \"now\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\t\tID: \"InXMin\",\n\t\t\t\t\t\tOther: \"In {{.Min}} mins\",\n\t\t\t\t\t},\n\t\t\t\t\tTemplateData: map[string]string{\n\t\t\t\t\t\t\"Min\": \"15\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tText: \"+15min\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\t\tID: \"InXMin\",\n\t\t\t\t\t\tOther: \"In {{.Min}} mins\",\n\t\t\t\t\t},\n\t\t\t\t\tTemplateData: map[string]string{\n\t\t\t\t\t\t\"Min\": \"30\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tText: \"+30min\",\n\t\t\t},\n\t\t}\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"When\",\n\t\t\t\t\tOther: \"When?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tDatetimeInput: true,\n\t\t}\n\tcase \"num_of_passengers\":\n\t\tbuttons := []QuickReplyButton{\n\t\t\t{\n\t\t\t\tLabel: \"1\",\n\t\t\t\tText: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"2\",\n\t\t\t\tText: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"3\",\n\t\t\t\tText: \"3\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"4\",\n\t\t\t\tText: \"4\",\n\t\t\t},\n\t\t}\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"HowManyPassengers\",\n\t\t\t\t\tOther: \"How many passengers?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t}\n\tcase \"final\":\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"Confirm\",\n\t\t\t\t\tOther: \"Confirm\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tYesInput: true,\n\t\t}\n\t}\n\treturn Question{\n\t\tText: \"n/a\",\n\t}\n}", "func RevealAnswer(problem, secret string) string {\n\tciphertext, err := hex.DecodeString(secret)\n\tFatalOnError(err, \"hex.DecodeString\")\n\tgcm := getAnswerCipher()\n\tnonce := makeNonce(problem)\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tFatalOnError(err, \"gcm.Open\")\n\treturn string(plaintext)\n}", "func (c *ReplyController) CreateReply() {\n\tr := ReqReply{}\n\tif err := c.ParseForm(&r); err != nil {\n\t\tc.Data[\"json\"] = BasicResp{\n\t\t\tStatusCode: 400,\n\t\t\tMessage: \"parse form data Err: \" + err.Error(),\n\t\t}\n\t} else {\n\t\trr := convert2DBReply(r)\n\t\tif err := models.RecordReply(rr); err != nil {\n\t\t\tc.Data[\"json\"] = BasicResp{\n\t\t\t\tStatusCode: 400,\n\t\t\t\tMessage: err.Error(),\n\t\t\t}\n\t\t} else {\n\t\t\tc.Data[\"json\"] = BasicResp{\n\t\t\t\tStatusCode: 0,\n\t\t\t}\n\t\t}\n\t}\n\tc.ServeJSON()\n}", "func AskAquestion() {\n\tanswerService := answer.NewAnswerService(os.Getenv(\"MICRO_API_TOKEN\"))\n\trsp, err := answerService.Question(&answer.QuestionRequest{\n\t\tQuery: \"microsoft\",\n\t})\n\tfmt.Println(rsp, err)\n}", "func newFirstMima() *Mima {\n\tm := new(Mima)\n\tkey := randomKey()\n\tm.Username = RandomString64()\n\tm.Password = util.Base64Encode(key[:])\n\tm.CreatedAt = util.TimeNow()\n\treturn m\n}", "func handle(\n\tpc net.PacketConn,\n\taddr net.Addr,\n\tqbuf []byte,\n\tdir string,\n\tttl uint32,\n\tfb byte, /* First byte in replies */\n) {\n\t/* Answer resource */\n\tvar a dnsmessage.AResource\n\ta.A = errorResource.A\n\n\t/* Unmarshal packet */\n\tvar m dnsmessage.Message\n\tif err := m.Unpack(qbuf); nil != err {\n\t\tlog.Printf(\"[%v] Invalid packet: %v\", addr, err)\n\t\treturn\n\t}\n\n\t/* Make sure we have at least one question */\n\tif 0 == len(m.Questions) {\n\t\tlog.Printf(\"[%v] No questions\", addr)\n\t\treturn\n\t}\n\n\ttag := fmt.Sprintf(\"[%v (%v)]\", m.Questions[0].Name, addr)\n\n\t/* Make sure a reply is sent */\n\tdefer func() {\n\t\tvar err error\n\t\t/* Make sure we know we're sending a response */\n\t\tm.Header.Response = true\n\n\t\t/* Add in the answer */\n\t\tm.Answers = append(m.Answers, dnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: m.Questions[0].Name,\n\t\t\t\tType: dnsmessage.TypeA,\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: ttl,\n\t\t\t},\n\t\t\tBody: &a,\n\t\t})\n\n\t\t/* Roll the reply */\n\t\trbuf := pool.Get().([]byte)\n\t\tdefer pool.Put(rbuf)\n\t\tif rbuf, err = m.AppendPack(rbuf[:0]); nil != err {\n\t\t\tlog.Printf(\"%v Unable to roll reply: %v\", tag, err)\n\t\t\treturn\n\t\t}\n\n\t\t/* Send it back */\n\t\tif _, err := pc.WriteTo(rbuf, addr); nil != err {\n\t\t\tlog.Printf(\"%v Error sending reply: %v\", tag, err)\n\t\t\treturn\n\t\t}\n\n\t\t/* Only log if we sent something meaningful */\n\t\tif a.A != errorResource.A {\n\t\t\tlog.Printf(\n\t\t\t\t\"%v %v\",\n\t\t\t\ttag,\n\t\t\t\tnet.IP(m.Answers[0].Body.(*dnsmessage.AResource).A[:]),\n\t\t\t)\n\t\t}\n\t}()\n\n\t/* Get the offset and file name */\n\tparts := strings.SplitN(m.Questions[0].Name.String(), \".\", 3)\n\tif 3 != len(parts) {\n\t\tlog.Printf(\"%v Not enough labels\", tag)\n\t\treturn\n\t}\n\n\tpu, err := strconv.ParseUint(parts[0], 16, 32)\n\toffset := uint32(pu)\n\tif nil != err {\n\t\tlog.Printf(\"%v Unparsable offset %q: %v\", tag, parts[0], err)\n\t\treturn\n\t}\n\tfname := strings.ToLower(parts[1])\n\n\t/* Make sure we have this file */\n\tif err := ensureFile(dir, fname, fb); nil != err {\n\t\tlog.Printf(\"%v Unpossible file %q\", tag, fname)\n\t\treturn\n\t}\n\n\t/* Get the chunk or the file size */\n\tif 0xFFFFFF == offset {\n\t\t/* Request for size */\n\t\ta.A = getSize(fname)\n\t} else {\n\t\tvar ok bool\n\t\ta.A, ok = getOffset(fname, offset, fb)\n\t\tif !ok {\n\t\t\tlog.Printf(\"%v Too-large offset %v\", tag, offset)\n\t\t\treturn\n\t\t}\n\t}\n}", "func generateMnemonic(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusMethodNotAllowed, \"\")\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tif r.Header.Get(\"Content-Type\") != ContentTypeJSON {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusUnsupportedMediaType, \"\")\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tvar req GenerateMnemonicRequest\n\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\tresp := NewHTTPErrorResponse(http.StatusBadRequest, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\t\tdefer r.Body.Close()\n\n\t\tif req.WordCount != 12 && req.WordCount != 24 {\n\t\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\t\tresp := NewHTTPErrorResponse(http.StatusUnprocessableEntity, \"word count must be 12 or 24\")\n\t\t\t\twriteHTTPResponse(w, resp)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// for integration tests\n\t\tif autoPressEmulatorButtons {\n\t\t\terr := gateway.SetAutoPressButton(true, skyWallet.ButtonRight)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"generateMnemonic failed: %s\", err.Error())\n\t\t\t\tresp := NewHTTPErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t\t\twriteHTTPResponse(w, resp)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tmsg, err := gateway.GenerateMnemonic(req.WordCount, req.UsePassphrase)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"generateMnemonic failed: %s\", err.Error())\n\t\t\tresp := NewHTTPErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t\twriteHTTPResponse(w, resp)\n\t\t\treturn\n\t\t}\n\n\t\tHandleFirmwareResponseMessages(w, gateway, msg)\n\t}\n}", "func NewKademlia(nw *Network) *Kademlia {\n\tkademlia := &Kademlia{}\n\tkademlia.asked = make(map[KademliaID]bool)\n\tkademlia.network = *nw\n\tkademlia.rt = kademlia.network.node.rt\n\tkademlia.numberOfIdenticalAnswersInRow = 0\n\tkademlia.threadCount = 0\n\tkademlia.k = 3\n\trand.Seed(time.Now().UnixNano())\n\treturn kademlia\n}", "func NewState() (string, error) {\n\tconf := config.GetConfiguration()\n\treturn encrypt([]byte(conf.MachineKey), conf.OAuthServer.Callback)\n}", "func (c Client) newGameRequest() {\n\terr := c.Encoder.Encode(messages.PlayerReq{Action: game.NewGame})\n\tif err != nil {\n\t\tfmt.Fprintf(c.Output, \"unexpected error: %v \\n\", err)\n\t}\n\n\tvar resp messages.GameStateResp\n\terr = c.decodeResponse(&resp)\n\tif err != nil {\n\t\tfmt.Fprintf(c.Output, \"unexpected error: %s \\n\", err)\n\t}\n\n\tif resp.Error != nil {\n\t\tfmt.Fprintln(c.Output, resp.Error)\n\t} else {\n\t\tfmt.Fprintf(c.Output, \"Guess the hero: %s \\n\", resp.State.WordToGuess)\n\t\tfmt.Fprintln(c.Output, drawing.Display[len(resp.State.CharsTried)])\n\t\tfmt.Fprintf(c.Output, \"Characters tried: %s \\n\", strings.Join(resp.State.CharsTried, \" - \"))\n\t}\n}", "func (kademlia *Kademlia) AskNextNode(target *KademliaID, destination *Contact, findData bool, returnChannel chan interface{}) {\n\tif findData {\n\t\tgo kademlia.network.SendFindDataMessage(target.String(), destination, returnChannel)\n\t} else {\n\t\tgo kademlia.network.SendFindContactMessage(target, destination, returnChannel)\n\t}\n}", "func NewQuestion(answers []string, max int, min int, question string, resultType string, shortName string) (*Question, error) {\n\tif max < 0 || min < 0 || min > max {\n\t\treturn nil, errors.New(\"invalid question min and max\")\n\t}\n\n\tif resultType != \"absolute\" && resultType != \"relative\" {\n\t\treturn nil, errors.New(\"invalid result type\")\n\t}\n\n\tansURLs := make([]string, len(answers))\n\tans := make([]string, len(answers))\n\tcopy(ans, answers)\n\n\t// The only possible choice type is \"approval\", and the only possible\n\t// tally type is \"homomorphic\".\n\treturn &Question{ansURLs, ans, \"approval\", max, min, question, resultType, shortName, \"homomorphic\"}, nil\n}", "func NextAvailableInstance(appName string) (*InstanceInfo, error) {\n\treq, err := http.NewRequest(http.MethodGet, \"http://localhost:8761/eureka/apps/\"+appName, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\tvar jsonResponse model.EurekaResponse\n\terr = json.NewDecoder(res.Body).Decode(&jsonResponse)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprintln(jsonResponse.Application.Name)\n\ttarget := jsonResponse.Application.Instance[rand.Int()%len(jsonResponse.Application.Instance)]\n\treturn &InstanceInfo{Hostname: target.HostName, Port: target.Port.Value, InstanceID: target.InstanceID}, nil\n}", "func NewMnemonic() (string, error) {\n\tvar mnemonic string\n\tentropy, err := bip39.NewEntropy(256)\n\tif err == nil {\n\t\tmnemonic, err = bip39.NewMnemonic(entropy)\n\t}\n\treturn mnemonic, err\n}", "func (pc *PeerConnection) createAnswer() (sdp.Session, error) {\n\ts := sdp.Session{\n\t\tVersion: 0,\n\t\tOrigin: sdp.Origin{\n\t\t\tUsername: sdpUsername,\n\t\t\tSessionId: strconv.FormatInt(time.Now().UnixNano(), 10),\n\t\t\tSessionVersion: 2,\n\t\t\tNetworkType: \"IN\",\n\t\t\tAddressType: \"IP4\",\n\t\t\tAddress: \"127.0.0.1\",\n\t\t},\n\t\tName: \"-\",\n\t\tTime: []sdp.Time{\n\t\t\t{nil, nil},\n\t\t},\n\t\tAttributes: []sdp.Attribute{\n\t\t\t{\"group\", pc.remoteDescription.GetAttr(\"group\")},\n\t\t},\n\t}\n\n\tfor _, remoteMedia := range pc.remoteDescription.Media {\n\n\t\ttype payloadTypeAttributes struct {\n\t\t\tnack bool\n\t\t\tpli bool\n\t\t\tfmtp string\n\t\t\tcodec string\n\t\t\treject bool\n\t\t}\n\n\t\tsupportedPayloadTypes := make(map[int]*payloadTypeAttributes)\n\n\t\t// Search attributes for supported codecs\n\t\tfor _, attr := range remoteMedia.Attributes {\n\t\t\tvar pt int\n\t\t\tvar text string\n\n\t\t\t// Parse payload type from attribute. Will bin by payload type.\n\t\t\tpt = -1\n\t\t\tswitch attr.Key {\n\t\t\tcase \"fmtp\", \"rtcp-fb\", \"rtpmap\":\n\t\t\t\tif _, err := fmt.Sscanf(\n\t\t\t\t\tattr.Value, \"%3d %s\", &pt, &text,\n\t\t\t\t); err != nil {\n\t\t\t\t\tlog.Warn(fmt.Sprintf(\"malformed %s\", attr.Key))\n\t\t\t\t\tbreak // switch\n\t\t\t\t}\n\t\t\t}\n\t\t\tif pt < 0 {\n\t\t\t\tcontinue // Ignore unsupported attributes\n\t\t\t}\n\n\t\t\tif _, ok := supportedPayloadTypes[pt]; !ok {\n\t\t\t\tsupportedPayloadTypes[pt] = &payloadTypeAttributes{}\n\t\t\t}\n\t\t\tswitch attr.Key {\n\t\t\tcase \"rtpmap\":\n\t\t\t\tswitch text {\n\t\t\t\tcase \"H264/90000\":\n\t\t\t\t\tsupportedPayloadTypes[pt].codec = text\n\t\t\t\t}\n\t\t\tcase \"rtcp-fb\":\n\t\t\t\tswitch text {\n\t\t\t\tcase \"nack\":\n\t\t\t\t\tsupportedPayloadTypes[pt].nack = true\n\t\t\t\t}\n\t\t\tcase \"fmtp\":\n\t\t\t\tsupportedPayloadTypes[pt].fmtp = text\n\t\t\t\tif !strings.Contains(text, \"packetization-mode=1\") {\n\t\t\t\t\tsupportedPayloadTypes[pt].reject = true\n\t\t\t\t}\n\t\t\t\tif !strings.Contains(text, \"profile-level-id=42\") {\n\t\t\t\t\tsupportedPayloadTypes[pt].reject = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Require 24 and 128 bits of randomness for ufrag and pwd, respectively\n\t\trnd := make([]byte, 3+16)\n\t\tif _, err := rand.Read(rnd); err != nil {\n\t\t\treturn sdp.Session{}, err\n\t\t}\n\n\t\t// Base64 encode ice-ufrag and ice-pwd\n\t\tufrag := base64.StdEncoding.EncodeToString(rnd[0:3])\n\t\tpwd := base64.StdEncoding.EncodeToString(rnd[3:])\n\n\t\t// Media description with first part of attributes\n\t\tm := sdp.Media{\n\t\t\tType: \"video\",\n\t\t\tPort: 9,\n\t\t\tProto: \"UDP/TLS/RTP/SAVPF\",\n\t\t\tConnection: &sdp.Connection{\n\t\t\t\tNetworkType: \"IN\",\n\t\t\t\tAddressType: \"IP4\",\n\t\t\t\tAddress: \"0.0.0.0\",\n\t\t\t},\n\t\t\tAttributes: []sdp.Attribute{\n\t\t\t\t{\"mid\", remoteMedia.GetAttr(\"mid\")},\n\t\t\t\t{\"rtcp\", \"9 IN IP4 0.0.0.0\"},\n\t\t\t\t{\"ice-ufrag\", ufrag},\n\t\t\t\t{\"ice-pwd\", pwd},\n\t\t\t\t{\"ice-options\", \"trickle\"},\n\t\t\t\t{\"ice-options\", \"ice2\"},\n\t\t\t\t{\"fingerprint\", \"sha-256 \" + strings.ToUpper(pc.fingerprint)},\n\t\t\t\t{\"setup\", \"active\"},\n\t\t\t\t{\"sendonly\", \"\"},\n\t\t\t\t{\"rtcp-mux\", \"\"},\n\t\t\t\t{\"rtcp-rsize\", \"\"},\n\t\t\t},\n\t\t}\n\n\t\t// Additional attributes per payload type\n\t\tfor pt, a := range supportedPayloadTypes {\n\t\t\tswitch {\n\t\t\tcase \"H264/90000\" == a.codec && \"\" != a.fmtp && !a.reject:\n\t\t\t\tm.Attributes = append(\n\t\t\t\t\tm.Attributes,\n\t\t\t\t\tsdp.Attribute{\"rtpmap\", fmt.Sprintf(\"%d %s\", pt, a.codec)},\n\t\t\t\t)\n\n\t\t\t\tif a.nack {\n\t\t\t\t\tm.Attributes = append(\n\t\t\t\t\t\tm.Attributes,\n\t\t\t\t\t\tsdp.Attribute{\"rtcp-fb\", fmt.Sprintf(\"%d nack\", pt)},\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tm.Attributes = append(\n\t\t\t\t\tm.Attributes,\n\t\t\t\t\tsdp.Attribute{\"fmtp\", fmt.Sprintf(\"%d %s\", pt, a.fmtp)},\n\t\t\t\t)\n\t\t\t\tm.Format = append(m.Format, strconv.Itoa(pt))\n\n\t\t\t\t// TODO [chris] Fix payload type selection. Currently we're\n\t\t\t\t// rejecting essentially all but one payload type, assigned\n\t\t\t\t// here. However, we should be prepared to receive RTP flows\n\t\t\t\t// for each accepted payload type.\n\t\t\t\tpc.DynamicType = uint8(pt)\n\t\t\t}\n\t\t}\n\n\t\t// Final attributes\n\t\tm.Attributes = append(\n\t\t\tm.Attributes,\n\t\t\t[]sdp.Attribute{\n\t\t\t\t{\"ssrc\", \"2541098696 cname:cYhx/N8U7h7+3GW3\"},\n\t\t\t\t{\"ssrc\", \"2541098696 msid:SdWLKyaNRoUSWQ7BzkKGcbCWcuV7rScYxCAv e9b60276-a415-4a66-8395-28a893918d4c\"},\n\t\t\t\t{\"ssrc\", \"2541098696 mslabel:SdWLKyaNRoUSWQ7BzkKGcbCWcuV7rScYxCAv\"},\n\t\t\t\t{\"ssrc\", \"2541098696 label:e9b60276-a415-4a66-8395-28a893918d4c\"},\n\t\t\t}...,\n\t\t)\n\n\t\ts.Media = append(s.Media, m)\n\t}\n\n\tpc.localDescription = s\n\treturn s, nil\n}", "func (c *DeviceController) NextPrime(w http.ResponseWriter, r *http.Request) {\n\tvals := r.URL.Query()\n\tcurs, ok := vals[\"cur\"]\n\tcur, err := strconv.ParseInt(curs[0], 10, 64)\n\tfmt.Println(\"Getting next prime on from: \" + strconv.Itoa(int(cur)))\n\tres := int64(0)\n\tif ok && err == nil {\n\t\tres = prime.GetNextPrime(cur)\n\t}\n\tc.SendJSON(\n\t\tw,\n\t\tr,\n\t\tres,\n\t\thttp.StatusOK,\n\t)\n}", "func NewMediaPrompt()(*MediaPrompt) {\n m := &MediaPrompt{\n Prompt: *NewPrompt(),\n }\n odataTypeValue := \"#microsoft.graph.mediaPrompt\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func GetNewButton(c Doer, text string) Button {\n\treq := newButton(text)\n\tc <- req\n\treturn (<-req.resp).(Button)\n}", "func (pn *paxosNode) GetNextProposalNumber(args *paxosrpc.ProposalNumberArgs, reply *paxosrpc.ProposalNumberReply) error {\n\t// Will just give the Max([Nh/k]*k + id , )\n\tkey := args.Key\n\tpxi := pn.getInstance(key)\n\n\tpxi.mu.RLock()\n\tdefer pxi.mu.RUnlock()\n\n\treplyN := (pxi.Nh/pn.numNodes+1)*pn.numNodes + pn.id\n\treply.N = replyN\n\n\treturn nil\n}", "func CreateAnswer(form AnswerForm) {\n\ta := Answer{}\n\ta.Username = form.Username\n\tintQuestionID, _ := strconv.Atoi(form.QuestionID)\n\ta.QuestionID = intQuestionID\n\ta.Description = form.Description\n\ta.Rank = 0\n\tdb.Create(&a)\n}", "func prompNewPort() (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"Please enter a new port: \")\n\treturn reader.ReadString('\\n')\n}", "func askPass(message string, response interface{}) error {\n\treturn survey.AskOne(&survey.Password{Message: message}, response, survey.MinLength(1))\n}", "func (t *T) GetNew() (*Problem, error) {\n\tvar p Problem\n\trows, err := t.conn.QueryContext(context.Background(), `\n\t\tSELECT id, question, answer\n\t\tFROM probs\n\t\tWHERE ID NOT IN (SELECT probid FROM learning)\n\t\tORDER BY id\n\t\tLIMIT 1`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tif !rows.Next() {\n\t\treturn nil, nil\n\t}\n\n\terr = rows.Scan(&p.id, &p.Question, &p.Answer)\n\n\tp.Next = t.now()\n\tp.Interval = 5 * time.Second\n\n\treturn &p, nil\n}", "func (l *LNCChallenger) NewChallenge(price int64) (string, lntypes.Hash,\n\terror) {\n\n\treturn l.lndChallenger.NewChallenge(price)\n}", "func (a *App) VoiceReq(c *gin.Context) {\n\tctx, cancel := context.WithTimeout(c, time.Second*60)\n\tdefer cancel()\n\tmsg := models.AppReq{}\n\tif err := c.BindJSON(&msg); err != nil {\n\t\tlog.Errorf(\"app.go, ERROR UNMARSHALLING APP REQUEST: %v\", err)\n\t\tc.JSON(http.StatusBadRequest, \"Bad request\")\n\t\treturn\n\t}\n\n\tlog.Infof(\"app.go,incoming nlp request: %v\", msg)\n\tenTxt := translate(ctx, msg.Msg, msg.LangCode, \"en-IN\", a.Service.GetTranslateService())\n\t// get intent responce from dialogflow service\n\tdfResp, err := a.Service.GetDFService().GetIntent(c, msg.SessionID, enTxt)\n\tif err != nil || dfResp.Intent == \"\" {\n\t\ttmp := \"Sorry I'm still learning.\\nI would like you to PLEASE REPHRASE so that I can understand it better.\\nPlease type EXIT if you want to start over again ! \"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(ctx, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\treturn\n\t}\n\n\tsrv := a.Service.GetFFService(getQueryParams(\"Param1\", *dfResp), msg.MobileNumber, msg.SessionID, msg.UserCode, *dfResp)\n\tlog.Infof(\"app.go, srv: %v\", srv)\n\tif srv == nil && dfResp.Intent == \"Fallback\" {\n\t\ttmp := \"Iyris is still learning !\\n \\nI would like you to PLEASE REPHRASE!\\n \\nI can assist you with placing an order request.\\n \\nPlease let me know how can I help you !\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\tif srv == nil && dfResp.Intent == \"EndIntent\" {\n\t\ttmp := \"Iyris is happy to help you !\\n \\nIt is my pleasure to have you on this chat today!\\n \\nI can assist you with placing an order request.\\n \\nPlease let me know how can I help you\\n \\nThank you and have a nice day!\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\tif srv == nil && dfResp.Intent == \"HowAreYouIntent\" {\n\t\ttmp := \"Hi, I am doing good. !\\n \\nIt is my pleasure to have you on this chat today!\\n \\nI can assist you with placing an order request.\\n \\nPlease let me know how can I help you.\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\tif srv == nil {\n\t\tlog.Infof(\"could not resolve ff service : %v\", dfResp)\n\t\ttmp := \"Dear Customer, Sorry I'm still learning.\\n \\nIn case I am not able to assist you, please reach us at [email protected] for further assistance.\\n\\nThanks !\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\n\t// get fulfillment service response\n\tr, err := srv.GetFFResp(ctx)\n\tlog.Infof(\"app.go, r: %v \", r)\n\tlog.Infof(\"app.go, err %v:\", err)\n\n\tif err != nil {\n\t\t// if err == sapmodel.ErrFallBack {\n\t\t// \tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t// \t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t// \treturn\n\t\t// }\n\t\tif r == \"\" {\n\t\t\ttmp := \"Dear User, I am facing problem in fetching the desired information currently. Please try after sometime or reach us at [email protected] for further assistance.\\n\\nThanks !\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrCustomerName {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrSerial {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrCustomerEmail {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackProduct {\n\t\t\tif r == \"I'm sorry but you have no product registered !\\nPlease type EXIT if you want to start over again ! \" {\n\t\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackProductType {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackRegistration {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\n\t\tif err == sapmodel.ErrFallBackIssue {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackComplaint {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackAddress {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackService {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrJobID {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrAddressLines {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrPin {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrOrderRequest {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrCreditRequest {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrWalletRequest {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrOrderConfirmCancel {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t\t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\t// if err == sapmodel.ErrOrde{\n\t\t// \tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode,\n\t\t// \t\tmsg.LangCode, a.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t// \treturn\n\t\t// }\n\t\t// if err == sapmodel.ErrEndSession {\n\t\t// \ttmp := \"You have opted not to apply for any leave, Thanks !!!\"\n\t\t// \tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t// \t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t// \treturn\n\t\t// }\n\t\tif err == sapmodel.ErrEndSessionCustomer {\n\t\t\ttmp := \"You have opted not to register yourself, Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionProduct {\n\t\t\ttmp := \"You have opted not to provide any Product Serial Code, Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionCreateSR {\n\t\t\ttmp := \"You have opted not to raise any Service Request, Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrWrongAddress {\n\t\t\ttmp := \"Dear Customer, We are not able to raise a service request for the address option selected. Please try to raise the service request again !\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionAddressAdd {\n\t\t\ttmp := \"You have opted not to add any new address, Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionAddressUpdate {\n\t\t\ttmp := \"You have opted not to update any new address, Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndJobStatus {\n\t\t\ttmp := \"You have opted out of Job Status, Please visit again. Thanks !!!\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndRephrase {\n\t\t\ttmp := \"Sorry I'm still learning.\\nI would like you to PLEASE REPHRASE and provide all the information !\\nPlease type EXIT if you want to start over again ! \"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: msg.SessionID})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionService {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionOrder {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionCredit {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrEndSessionWallet {\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\t\tif err == sapmodel.ErrFallBackIndex {\n\t\t\ttmp := \"You've entered INVALID INDEX NUMBER. Please try to raise the Service Request again.\"\n\t\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r), msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\tif r == nil || r == \"\" {\n\t\ttmp := \"Dear Customer, Sorry I'm still learning.\\n\\nIn case I am not able to assist you, please reach us at [email protected] for further assistance.\\n\\nThanks !\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\tif r == \"\" {\n\t\ttmp := \"Dear Customer, Sorry I'm still learning.\\n\\nIn case I am not able to assist you, please reach us at [email protected] for further assistance.\\n\\nThanks !\"\n\t\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, tmp, msg.LangCode, msg.LangCode,\n\t\t\ta.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, &models.AppResp{Data: translate(c, fmt.Sprintf(\"%v\", r),\n\t\tmsg.LangCode, msg.LangCode, a.Service.GetTranslateService()), SessionID: getSessionID(msg.UserCode)})\n\treturn\n}", "func New(apiKey, apiSecret string) *Hbdm {\n\tclient := NewHttpClient(apiKey, apiSecret)\n\treturn &Hbdm{client, sync.Mutex{}}\n}", "func (c *authnClient) mfa(r *result) (*result, error) {\n\tchoice := make([]Choice, 0, len(r.Embedded.Factors))\n\tvar others []string\n\tfor _, f := range r.Embedded.Factors {\n\t\tif d := f.driver(); d.supported() {\n\t\t\tchoice = append(choice, f)\n\t\t} else {\n\t\t\tothers = append(others, d.name())\n\t\t}\n\t}\n\tif len(choice) == 0 {\n\t\treturn nil, fmt.Errorf(\"okta: no supported MFA methods (offered: %s)\",\n\t\t\tstrings.Join(others, \", \"))\n\t}\n\tf, err := c.Select(choice)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err = f.(*Factor).driver().run(f.(*Factor), c, r)\n\tif err == nil && r.Status == \"MFA_CHALLENGE\" {\n\t\tin := response{StateToken: r.StateToken}\n\t\tr, err = c.nav(r.Links.Prev, &in)\n\t}\n\treturn r, err\n}", "func (c *APIClient) SetNewAPIToken() error {\n\turl, err := c.compileTokenURL()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Client.SetNewAPIToken(req)\n}", "func NextRequestID() int32 { return atomic.AddInt32(&globalRequestID, 1) }", "func (id *RequestID) GetNext() int64 {\n\tid.Lock()\n\tid.Value++\n\tv := id.Value\n\tid.Unlock()\n\treturn v\n}", "func (i *IMDSConfig) getNewToken() (err error) {\n\t// Create request\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(http.MethodPut, imdsBase+tokenEndpoint, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ec2macosinit: error while creating new HTTP request: %s\\n\", err)\n\t}\n\treq.Header.Set(tokenRequestTTLHeader, strconv.FormatInt(int64(imdsTokenTTL), 10))\n\n\t// Make request\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ec2macosinit: error while requesting new token: %s\\n\", err)\n\t}\n\n\t// Validate response code\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"ec2macosinit: received a non-200 status code from IMDS: %d - %s\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tresp.Status,\n\t\t)\n\t}\n\n\t// Set returned value\n\ti.token, err = ioReadCloserToString(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ec2macosinit: error reading response body: %s\\n\", err)\n\t}\n\n\treturn nil\n}", "func NewClient(c diam.Conn) {\n // Build CCR\n\n parser, _ := diamdict.NewParser()\n parser.Load(bytes.NewReader(diamdict.DefaultXML))\n parser.Load(bytes.NewReader(diamdict.CreditControlXML))\n\n m := diam.NewRequest(257, 0, parser)\n // Add AVPs\n m.NewAVP(\"Origin-Host\", 0x40, 0x00, Identity)\n m.NewAVP(\"Origin-Realm\", 0x40, 0x00, Realm)\n m.NewAVP(\"Origin-State-Id\", 0x40, 0x00, diamtype.Unsigned32(rand.Uint32()))\n m.NewAVP(\"Auth-Application-Id\", 0x40, 0x00, AuthApplicationId)\n laddr := c.LocalAddr()\n ip, _, _ := net.SplitHostPort(laddr.String())\n m.NewAVP(\"Host-IP-Address\", 0x40, 0x0, diamtype.Address(net.ParseIP(ip)))\n m.NewAVP(\"Vendor-Id\", 0x40, 0x0, VendorId)\n m.NewAVP(\"Product-Name\", 0x00, 0x0, ProductName)\n\n log.Printf(\"Sending message to %s\", c.RemoteAddr().String())\n log.Println(m.String())\n // Send message to the connection\n if _, err := m.WriteTo(c); err != nil {\n log.Fatal(\"Write failed:\", err)\n }\n\n m = diam.NewRequest(272, 4, parser)\n // Add AVPs\n m.NewAVP(\"Session-Id\", 0x40, 0x00, diamtype.UTF8String(fmt.Sprintf(\"%v\", rand.Uint32())))\n m.NewAVP(\"Origin-Host\", 0x40, 0x00, Identity)\n m.NewAVP(\"Origin-Realm\", 0x40, 0x00, Realm)\n m.NewAVP(\"Destination-Realm\", 0x40, 0x00, DestinationRealm)\n m.NewAVP(\"Auth-Application-Id\", 0x40, 0x0, AuthApplicationId)\n m.NewAVP(\"CC-Request-Type\", 0x40, 0x0, CCRequestType)\n m.NewAVP(\"Service-Context-Id\", 0x40, 0x0, ServiceContextId)\n m.NewAVP(\"Service-Identifier\", 0x40, 0x0, ServiceIdentifier)\n m.NewAVP(\"CC-Request-Number\", 0x40, 0x0, CCRequestNumber)\n m.NewAVP(\"Requested-Action\", 0x40, 0x0, RequestedAction)\n m.NewAVP(\"Subscription-Id\", 0x40, 0x00, &diam.Grouped{\n AVP: []*diam.AVP{\n // Subscription-Id-Type\n diam.NewAVP(450, 0x40, 0x0, SubscriptionIdType),\n // Subscription-Id-Data\n diam.NewAVP(444, 0x40, 0x0, SubscriptionIdData),\n },\n })\n m.NewAVP(\"Service-Parameter-Info\", 0x40, 0x00, &diam.Grouped{\n AVP: []*diam.AVP{\n // Service-Parameter-Type\n diam.NewAVP(441, 0x40, 0x0, ServiceParameterType1),\n // Service-Parameter-Value\n diam.NewAVP(442, 0x40, 0x0, ServiceParameterValue1),\n },\n })\n m.NewAVP(\"Service-Parameter-Info\", 0x40, 0x00, &diam.Grouped{\n AVP: []*diam.AVP{\n // Service-Parameter-Type\n diam.NewAVP(441, 0x40, 0x0, ServiceParameterType2),\n // Service-Parameter-Value\n diam.NewAVP(442, 0x40, 0x0, ServiceParameterValue2),\n },\n })\n\n log.Printf(\"Sending message to %s\", c.RemoteAddr().String())\n log.Println(m.String())\n // Send message to the connection\n if _, err := m.WriteTo(c); err != nil {\n log.Fatal(\"Write failed:\", err)\n }\n}", "func NewKeyMan(masterSecret []byte, benchmarking bool) *KeyMan {\n\tlistenIP := tpAddrToKeyServerAddr(config.TPAddr)\n\tkm := &KeyMan{\n\t\tkeyLength: config.KeyLength,\n\t\tkeyTTL: config.KeyTTL,\n\t\tms: \t\t\tmasterSecret,\n\t\tlistenIP: \tlistenIP,\n\t\tlistenPort: \tconfig.ServerPort,\n\t}\n\terr := km.RefreshL0()\n\tif err!=nil{\n\t\tlog.Println(logPrefix+\"ERROR: Did not refresh L0\")\n\t}\t\n\tegressL1Keys = make(map[string]KeyPld)\n\tingressL1Keys = make(map[string]KeyPld)\n\tif benchmarking==false{\n\t\tkm.serveL1()\n\t}\n\t\n\treturn km\n}", "func (gen *Generator) Prompt() error {\n\tfor _, q := range gen.Template.Questions {\n\t\tres, err := gen.Ask(*q)\n\t\tLog.Info(\"prompt\", fmt.Sprintf(\"%s: %q\\n\", q.Name, res))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Controller) renderNew(ctx context.Context, w http.ResponseWriter, authApp *database.AuthorizedApp) {\n\tm := controller.TemplateMapFromContext(ctx)\n\tm.Title(\"New API key\")\n\tm[\"authApp\"] = authApp\n\tm[\"typeAdmin\"] = database.APIKeyTypeAdmin\n\tm[\"typeDevice\"] = database.APIKeyTypeDevice\n\tm[\"typeStats\"] = database.APIKeyTypeStats\n\tc.h.RenderHTML(w, \"apikeys/new\", m)\n}", "func (c *Client) NextId() *Id {\n\tval := atomic.AddInt64(&c.requestCounter, 1)\n\treturn NewIdAsInt(val)\n}", "func makeAccount(){\n\toperatorSecret, err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\tsecretKey, _ := hedera.GenerateSecretKey()\n\tpublic := secretKey.Public()\n\n\tfmt.Printf(\"secret = %v\\n\", secretKey)\n\tfmt.Printf(\"public = %v\\n\", public)\n\n\tclient, err := hedera.Dial(server)\n\tif err !=nil{\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tnodeAccountID := hedera.AccountID{Account: 3}\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\ttime.Sleep(2* time.Second)\n\tresponse, err := client.CreateAccount().Key(public).InitialBalance(0).Operator(operatorAccountID).Node(nodeAccountID).Memo(\"Test make Account\").Sign(operatorSecret).Execute()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\ttransactionID := response.ID\n\tfmt.Printf(\"Created account; transaction = %v\\n\", transactionID)\n\ttime.Sleep(2* time.Second)\n \n\treceipt,err := client.Transaction(*transactionID).Receipt().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Account = %v\\n\", *receipt.AccountID)\n\n}", "func CreateAnswerObject(args []string) (Answer, error) {\n\tvar myAnswer Answer\n\n\tstrArr := []string{}\n\t// Check there are 10 Arguments provided as per the the struct\n\tif len(args) != 4 {\n\t\tfmt.Println(\"CreateAnswerObject(): Incorrect number of arguments. Expecting 4\")\n\t\treturn myAnswer, errors.New(\"CreateAnswerObject(): Incorrect number of arguments. Expecting 4\")\n\t}\n\n\tmyAnswer = Answer{args[0], args[1], args[2], args[3], strArr, 0, time.Now().Format(\"20060102150405\")}\n\treturn myAnswer, nil\n}", "func NewFulfillment() {\n\t\n}", "func (module *Crawler) Prompt(what string) {\n}", "func FBInit(g *gocui.Gui, q *questions.Question, count string) (err error) {\n\t//The Answers\n\tas := q.Answers\n\n\t//Highlight the selected view and make it green\n\tg.Highlight = true\n\tg.SelFgColor = gocui.ColorGreen\n\n\t//Add content to gui\n\tquestionFrame := gui.NewQuestionFrame(\"questionFrame\")\n\tquestion := gui.NewQuestion(\"question\", count, q.Question)\n\tanswerBlank := gui.NewAnswer(gui.BoxBlank, gui.BoxBlank, as.Answers[0].Answer)\n\tinfoBar := gui.NewInfoBar(gui.InfoBarName, gui.InfoBarFillInBlank)\n\n\tg.SetManager(questionFrame, question, answerBlank, infoBar)\n\n\t//Add keybindings\n\tif err := g.SetKeybinding(\"\", gocui.KeyCtrlC, gocui.ModNone, gui.Quit); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tif err := g.SetKeybinding(\"\", gocui.KeyEnter, gocui.ModNone, FillInAnswer); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\treturn nil\n}", "func NewPlayPromptPostRequestBody()(*PlayPromptPostRequestBody) {\n m := &PlayPromptPostRequestBody{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func getAnswerCipher() cipher.AEAD {\n\tblock, err := aes.NewCipher([]byte(\"HideEulerAnswer!\"))\n\tFatalOnError(err, \"aes.NewCipher\")\n\tgcm, err := cipher.NewGCM(block)\n\tFatalOnError(err, \"cipher.NewGCM\")\n\treturn gcm\n}", "func NewReply(name string, value int64) *commands.Message {\n\treturn &commands.Message{Msg: [](*commands.Data){&commands.Data{Name: name, Value: value}}}\n}", "func (fs *FakeSession) GetNext(oids []string) (*gosnmp.SnmpPacket, error) {\n\tvars, err := fs.getNexts(oids, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &gosnmp.SnmpPacket{\n\t\tVariables: vars,\n\t}, nil\n}", "func (s *session) newID() (interface{}, error) {\n\tvar b [32]byte\n\t_, err := rand.Read(b[:])\n\treturn hex.EncodeToString(b[:]), err\n}", "func createNode() (int, error) {\n\tvar n int\n\tfmt.Println(\"Enter an integer value for keypair creation : \")\n\t_, err := fmt.Scanf(\"%d\", &n)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tif n > 20000 {\n\t\tfmt.Println(\"please enter below 15\")\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Println(\"You have entered : \", n)\n\treturn n, nil\n}", "func (app *HailingApp) NextStep(userID string) (*ReservationRecord, string) {\n\trec, err := app.FindOrCreateRecord(userID)\n\tif err != nil {\n\t\treturn nil, \"-\"\n\t}\n\tnextStep := rec.WhatsNext()\n\trec.Waiting = nextStep\n\n\terr = app.SaveRecordToRedis(rec)\n\tif err != nil {\n\t\treturn nil, \"-\"\n\t}\n\treturn rec, nextStep\n}", "func (resp *ListEnterprisesResponse) GetNextNextDocid() (*string, error) {\n\tif core.IsNil(resp.NextURL) {\n\t\treturn nil, nil\n\t}\n\tnext_docid, err := core.GetQueryParam(resp.NextURL, \"next_docid\")\n\tif err != nil || next_docid == nil {\n\t\treturn nil, err\n\t}\n\treturn next_docid, nil\n}", "func (f *DMAClient) Create(obj *dm.M4DApplication) (*dm.M4DApplication, error) {\n\tvar result dm.M4DApplication\n\terr := f.client.Post().\n\t\tNamespace(f.namespace).Resource(f.plural).\n\t\tBody(obj).Do(context.Background()).Into(&result)\n\treturn &result, err\n}", "func (h Response) Ask(prompt, reprompt string) {\n\th.emit(\":ask\", prompt, reprompt)\n}", "func (_Quiz *QuizSession) Answer() ([32]byte, error) {\n\treturn _Quiz.Contract.Answer(&_Quiz.CallOpts)\n}", "func Answer(question string) string {\n\n\tswitch question {\n\tcase \"ping\":\n\t\treturn \"pong\"\n\tdefault:\n\t\treturn random()\n\t}\n\n}", "func Ask(prompt string) (password string, err error) {\n\treturn FAsk(os.Stdout, prompt)\n}", "func NewKeyboard() *pb.Keyboard {\r\n\tkb := &pb.Keyboard{\r\n\t\tLayout: randomKeyBoardLayout(),\r\n\t\tBacklit: randomBool(),\r\n\t}\r\n\treturn *&kb\r\n}", "func (testSuite *MainTestSuite) newgamePost() uuid.UUID {\n\tresp, err := testSuite.client.Post(testSuite.server.URL+\"/newgame\", \"text/json\", nil)\n\t_ = err // silence warning about using defer before checking err\n\tdefer resp.Body.Close()\n\tcheckResponse(testSuite.T(), resp, err)\n\n\t// pull out the gameStateID\n\ttype Response struct {\n\t\tGameStateID uuid.UUID\n\t}\n\tvar response Response\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tassert.Nil(testSuite.T(), err)\n\treturn response.GameStateID\n}", "func askOpt() bool {\n\tvar userOpt string\n\tfmt.Print(\"\\nWould you like to add more? \\n('y' or 'Y'): \")\n\tfmt.Scan(&userOpt)\n\tfmt.Print(\"\\n\")\n\tif userOpt == \"y\" || userOpt == \"Y\" {\n\t\treturn true\n\t}\n\treturn false\n}" ]
[ "0.46312624", "0.45138684", "0.4507138", "0.43851736", "0.4359447", "0.42989373", "0.42974252", "0.42900527", "0.428464", "0.42529526", "0.4235715", "0.42216453", "0.4219072", "0.4216278", "0.42030713", "0.4199196", "0.41739607", "0.41704628", "0.41687834", "0.41605356", "0.41500637", "0.41473567", "0.41217196", "0.4119905", "0.41161495", "0.41160494", "0.41119727", "0.410979", "0.410079", "0.4092868", "0.40928552", "0.4088064", "0.40742522", "0.40695053", "0.4063415", "0.40531224", "0.40427357", "0.40384075", "0.40311098", "0.4017878", "0.40156218", "0.4011499", "0.40099669", "0.4002008", "0.399958", "0.3997143", "0.39832878", "0.39749247", "0.3974258", "0.39714694", "0.3970964", "0.39660463", "0.39502168", "0.39483413", "0.394089", "0.393689", "0.39319625", "0.3923167", "0.39114028", "0.39086965", "0.39038742", "0.39030337", "0.3898881", "0.38983905", "0.38980222", "0.3893479", "0.389216", "0.38893512", "0.38845837", "0.38839573", "0.38799754", "0.38742432", "0.3866526", "0.38578898", "0.38545215", "0.38493055", "0.38478285", "0.38453054", "0.38438526", "0.38392672", "0.3837267", "0.3836893", "0.38350105", "0.38312846", "0.38285336", "0.3827584", "0.38260096", "0.38257617", "0.38232625", "0.38142288", "0.3812944", "0.381113", "0.38048664", "0.38028675", "0.38027006", "0.37919626", "0.37893862", "0.37869564", "0.3786116", "0.37860757", "0.37842536" ]
0.0
-1
Given an array of positive integers target and an array initial of same size with all zeros. Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation: Choose any subarray from initial and increment each value by one. The answer is guaranteed to fit within the range of a 32bit signed integer. Example 1: Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: Input: target = [3,1,1,2] Output: 4 Explanation: (initial)[0,0,0,0] > [1,1,1,1] > [1,1,1,2] > [2,1,1,2] > [3,1,1,2] (target). Example 3: Input: target = [3,1,5,4,2] Output: 7 Explanation: (initial)[0,0,0,0,0] > [1,1,1,1,1] > [2,1,1,1,1] > [3,1,1,1,1] > [3,1,2,2,2] > [3,1,3,3,2] > [3,1,4,4,2] > [3,1,5,4,2] (target). Example 4: Input: target = [1,1,1,1] Output: 1 Constraints: 1 <= target.length <= 10^5 1 <= target[i] <= 10^5 simple O(n) solution:
func minNumberOperationsOn(target []int) int { sum := target[0] for i:=1; i<len(target); i++ { // it's easy to understand: // every larger number than prev need to increase by its own // every smaller number than prev can be covered by prev larger number if target[i]>target[i-1] { sum += target[i]-target[i-1] } } return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func closestToTarget(arr []int, target int) int {\n\tmin := math.MaxInt32\n\tsize := len(arr)\n\n\tandProducts := make([]int, 0)\n\n\tfor r := 0; r < size; r++ {\n\t\tfor i := 0; i < len(andProducts); i++ {\n\t\t\tandProducts[i] &= arr[r]\n\t\t}\n\t\tandProducts = append(andProducts, arr[r])\n\t\tsort.Ints(andProducts)\n\t\tandProducts = dedup(andProducts)\n\n\t\tfor _, ap := range andProducts {\n\t\t\tdiff := myAbs(ap - target)\n\t\t\tif diff == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\t\tif min > diff {\n\t\t\t\tmin = diff\n\t\t\t} else if ap > target {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn min\n}", "func findTargetSumWays(nums []int, S int) int {\n\t// let c[i, j] be the number of ways to get sum j for nums[0...i]\n\t// then c[i, j] = c[i-1, j+nums[i]] + c[i-1, j-nums[i]]\n\t// base case c[0, ±nums[0]] = 1, c[x, 0] = 0\n\tsum := 0\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t}\n\tif S > sum || S < -sum {\n\t\treturn 0\n\t}\n\tc0 := make([]int, 2*sum+1)\n\tc1 := make([]int, 2*sum+1)\n\tif nums[0] != 0 {\n\t\tc0[nums[0]+sum] = 1\n\t\tc0[-nums[0]+sum] = 1\n\t} else {\n\t\tc0[sum] = 2\n\t}\n\tfmt.Println(c0)\n\tfor i := 1; i < len(nums); i++ {\n\t\tfor j := -sum; j <= sum; j++ {\n\t\t\tc1[j+sum] = 0 // clear c1\n\t\t\tif j+nums[i] <= sum {\n\t\t\t\tc1[j+sum] += c0[j+nums[i]+sum]\n\t\t\t}\n\t\t\tif j-nums[i] >= -sum {\n\t\t\t\tc1[j+sum] += c0[j-nums[i]+sum]\n\t\t\t}\n\t\t}\n\t\tfmt.Println(c1)\n\t\tc0, c1 = c1, c0\n\t}\n\treturn c0[S+sum]\n}", "func subsetSum(nums []int, target int) int {\n\t dp := make([]int, target+1)\n\t dp[0] = 1\n\t for _, n := range nums {\n\t\t for i := target; i >= n; i-- {\n\t\t\t dp[i] += dp[i - n]\n\t\t }\n\t }\n\t return dp[target]\n}", "func minSizeSubArraySum(input []int, targetSum int) int {\n\n\t// check for entry conditions\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\n\t// Return value should be MIN, so by default set to Max\n\tresult := len(input)\n\n\t// start two pointers starts and end \n\tleftIndex := 0\n\tvalueSum := 0\n\t\n\t// loop on the input array\n\tfor i:=0; i< len(input); i++{\n\n\t\tvalueSum += input[i]\n\n\t\tfor valueSum >= targetSum{\n\t\n\t\t\tresult = min(result, i + 1 - leftIndex )\n\t\t\t\n\t\t\tvalueSum -= input[leftIndex]\n\t\t\tleftIndex++\n\t\t}\t\n\t}\n\n\tif result != len(input){\n\t\treturn result\n\t}\n\treturn 0\n}", "func bestSum(target int, numbers []int) []int {\n\tdp := make([][]int, target+1)\n\tfor i := 1; i <= target; i++ {\n\t\tvar smallestCombination []int\n\t\tfor _, number := range numbers {\n\t\t\tcandidate := i - number\n\t\t\tif candidate < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif candidate == 0 {\n\t\t\t\tdp[i] = []int{number}\n\t\t\t\tsmallestCombination = dp[i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif len(dp[candidate]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(smallestCombination) == 0 || len(dp[candidate])+1 < len(smallestCombination) {\n\t\t\t\tsmallestCombination = append(dp[candidate], number)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tdp[i] = smallestCombination\n\t}\n\treturn dp[target]\n}", "func findTargetSumWays(nums []int, S int) int {\n if len(nums) == 0 {\n if S == 0 {\n return 1\n } else {\n return 0\n }\n }\n\n return findTargetSumWays(nums[:len(nums)-1], S + nums[len(nums)-1]) + findTargetSumWays(nums[:len(nums)-1], S - nums[len(nums)-1])\n}", "func sol1(nums []int, target int) []int {\n\tfor i, n := range nums {\n\t\tfor j, m := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif n+m == target {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func part1(arr []int) int {\n\tvar i, j int\n\tn := len(arr)\n\n\ti = 0\n\tj = n - 1\n\n\tfor i < n && j >= 0 {\n\t\tif arr[i]+arr[j] == target {\n\t\t\tbreak\n\t\t}\n\t\tif arr[i]+arr[j] < target {\n\t\t\ti++\n\t\t} else {\n\t\t\tj--\n\t\t}\n\t}\n\treturn arr[i] * arr[j]\n}", "func sol2(nums []int, target int) []int {\n\tmemo := make(map[int]int)\n\tfor i, n := range nums {\n\t\tmemo[n] = i\n\t}\n\tfor i, n := range nums {\n\t\tif _, ok := memo[target-n]; ok && i != memo[target-n] {\n\t\t\treturn []int{i, memo[target-n]}\n\t\t}\n\t}\n\treturn nil\n}", "func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}", "func fourSum(nums []int, target int) [][]int {\n\tif len(nums) < 4 {\n\t\treturn nil\n\t}\n\tif len(nums) == 4 {\n\t\tif sum(nums) == target {\n\t\t\treturn [][]int{nums}\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsort(nums)\n\n\tvar (\n\t\ta, b int\n\t\tlength = len(nums)\n\t\tc, d = 2, length - 1\n\t\tdp = make([][]int, length)\n\t)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, length)\n\t}\n\tfor ; c < d; c++ {\n\t\tfor ; d > c; d-- {\n\t\t\tdp[c][d] = nums[c] + nums[d]\n\t\t}\n\t\td = length - 1\n\t}\n\tfmt.Println(\"dp: \", dp)\n\n\tvar (\n\t\ttemp1, temp2 int\n\t\tresult = make([][]int, 0, 20)\n\t)\n\tfor ; a < length-3; a++ {\n\t\ttemp1 = target - nums[a]\n\t\tfor b = a + 1; b < length-2; b++ {\n\t\t\ttemp2 = temp1 - nums[b]\n\t\t\tfor c = b + 1; c < d; c++ {\n\t\t\t\tfor ; d > c; d-- {\n\t\t\t\t\tif dp[c][d] == temp2 {\n\t\t\t\t\t\tresult = append(result, []int{nums[a], nums[b], nums[c], nums[d]})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td = length - 1\n\t\t\t\tfor c < d && nums[c] == nums[c+1] {\n\t\t\t\t\tc++\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor b < length-2 && nums[b] == nums[b+1] {\n\t\t\t\tb++\n\t\t\t}\n\t\t}\n\t\tfor a < length-3 && nums[a] == nums[a+1] {\n\t\t\ta++\n\t\t}\n\t}\n\n\treturn result\n}", "func twosum(arr []int, target int) [][]int {\n\tl := len(arr)\n\tif l < 2 {\n\t\treturn [][]int{}\n\t}\n\tdp := map[int]bool{}\n\tfor _, v := range arr {\n\t\tdp[v] = true\n\t}\n\tres := [][]int{}\n\tfor i := 1; i < target; i++ {\n\t\tspec := target - i\n\n\t\tfor j := 0; j < l; j++ {\n\t\t\tif _, ok := dp[spec-arr[j]]; ok {\n\t\t\t\tdelete(dp, arr[j])\n\t\t\t\ttemp := []int{arr[j], spec - arr[j]}\n\t\t\t\tres = append(res, temp)\n\t\t\t}\n\t\t}\n\t\tif len(res) > 0 {\n\t\t\treturn res\n\t\t}\n\t}\n\treturn [][]int{}\n\n}", "func fourSum(nums []int, target int) [][]int {\n\tif len(nums) < 4 {\n\t\treturn [][]int{}\n\t}\n\tres := make([][]int, 0)\n\tsort.Ints(nums)\n\n\tfor l := 0; l < len(nums)-3; l++ {\n\t\tfor l > 0 && l < len(nums) && nums[l] == nums[l-1] {\n\t\t\tl++\n\t\t}\n\t\tfor i := l + 1; i < len(nums)-2; i++ {\n\t\t\tfor i > l+1 && i < len(nums) && nums[i] == nums[i-1] {\n\t\t\t\ti++\n\t\t\t}\n\n\t\t\tfor left, rig := i+1, len(nums)-1; left < rig; {\n\t\t\t\ttmp := nums[l] + nums[i] + nums[left] + nums[rig]\n\t\t\t\tif tmp == target {\n\t\t\t\t\tres = append(res, []int{nums[l], nums[i], nums[left], nums[rig]})\n\t\t\t\t\tleft++\n\t\t\t\t\tfor left < len(nums) && nums[left] == nums[left-1] {\n\t\t\t\t\t\tleft++\n\t\t\t\t\t}\n\t\t\t\t\trig--\n\t\t\t\t\tfor rig >= 0 && nums[rig] == nums[rig+1] {\n\t\t\t\t\t\trig--\n\t\t\t\t\t}\n\t\t\t\t} else if tmp < target {\n\t\t\t\t\tleft++\n\t\t\t\t} else {\n\t\t\t\t\trig--\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\treturn res\n}", "func fourSum(nums []int, target int) [][]int {\n\tvar result [][]int\n\tn := len(nums)\n\tif n < 4 {\n\t\treturn result\n\t}\n\tsort.Ints(nums)\n\tif nums[0]+nums[1]+nums[2]+nums[3] > target {\n\t\treturn result\n\t}\n\tfor i := 0; i < n-3; i++ {\n\t\tif i > 0 && nums[i] == nums[i-1] {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := i + 1; j < n-2; j++ {\n\t\t\tif j > i+1 && nums[j] == nums[j-1] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tleft, right := j+1, n-1\n\t\t\tfor left < right {\n\t\t\t\t//fmt.Printf(\"i: %d j: %d left: %d right: %d\\n\", i, j, left, right)\n\t\t\t\tsum := nums[i] + nums[j] + nums[left] + nums[right]\n\t\t\t\tif sum == target {\n\t\t\t\t\tresult = append(result, []int{nums[i], nums[j], nums[left], nums[right]})\n\t\t\t\t\tfor left < right && nums[left] == nums[left+1] {\n\t\t\t\t\t\tleft++\n\t\t\t\t\t}\n\t\t\t\t\tfor left < right && nums[right] == nums[right-1] {\n\t\t\t\t\t\tright--\n\t\t\t\t\t}\n\t\t\t\t\tleft++\n\t\t\t\t\tright--\n\t\t\t\t} else if sum < target {\n\t\t\t\t\tleft++\n\t\t\t\t} else {\n\t\t\t\t\tright--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func minimumSwaps(arr []int) int {\n\tvar changeRequest bool = true\n\tvar changes int\n\tvar newArr []int = arr\n\n\tfor changeRequest == true {\n\t\tchangeRequest = false\n\n\t\tfor idx, elem := range arr {\n\t\t\tif idx+1 != elem {\n\t\t\t\tchangeRequest = true\n\n\t\t\t\tnewArr[idx] = idx + 1 // the correct value\n\n\t\t\t\ttargetIdx, _ := findIndex(arr, idx+1)\n\t\t\t\tnewArr[targetIdx] = elem\n\t\t\t\tchanges++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tarr = newArr\n\t}\n\treturn changes\n}", "func fourSum(nums []int, target int) [][]int {\n\tresult := make([][]int, 0)\n\n\t// Here is the tricky part, sort the array before working on it!\n\tsort.Ints(nums)\n\n\tfor left := 0; left < len(nums)-3; left++ {\n\t\tif left > 0 && nums[left] == nums[left-1] {\n\t\t\t// Move left to the right position to avoid duplicating the same result.\n\t\t\tcontinue\n\t\t}\n\n\t\tfor mid1 := left + 1; mid1 < len(nums)-2; mid1++ {\n\t\t\tif mid1 > left+1 && nums[mid1] == nums[mid1-1] {\n\t\t\t\t// Move mid1 to the right position to avoid duplicating the same result.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmid2, right := left+1, len(nums)-1\n\n\t\t\tfor mid2 < right {\n\t\t\t\tsum := nums[left] + nums[mid1] + nums[mid2] + nums[right]\n\t\t\t\tif sum < target {\n\t\t\t\t\tmid2++\n\t\t\t\t} else if sum > target {\n\t\t\t\t\tright--\n\t\t\t\t} else {\n\t\t\t\t\tresult = append(result, []int{nums[left], nums[mid1], nums[mid2], nums[right]})\n\t\t\t\t\tmid2, right = next(nums, mid2, right)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn result\n}", "func minimumSwaps(arr []int32) int32 {\n\n\tvar trackArray []visit\n\tfor _, v := range arr {\n\t\ttrackArray = append(trackArray, visit{int(v), false})\n\t}\n\t// traversing through array finding cycles\n\tvar swapCount int\n\tfor i, v := range trackArray {\n\t\tif v.seen {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark this number as seen (note that we have to access the original array rather than v)\n\t\ttrackArray[i].seen = true\n\n\t\tif i == v.val {\n\t\t\t// Number already in correct place\n\t\t\tcontinue\n\t\t}\n\t\t// Start tracking a cycle\n\t\t// Check the number sitting in v's \"home\"\n\t\tcurrent := v\n\t\tfor {\n\t\t\tnext := trackArray[current.val-1]\n\n\t\t\t// Mark next as seen (have to update original array)\n\t\t\ttrackArray[current.val-1].seen = true\n\n\t\t\tif next.val == v.val {\n\t\t\t\t// End of the cycle\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Necessary swaps is (length of cycle) - 1\n\t\t\tswapCount++\n\t\t\tcurrent = next\n\t\t}\n\t}\n\n\treturn int32(swapCount)\n\n}", "func combinationSum(candidates []int, target int) [][]int {\n var res [][]int\n for i, val := range candidates {\n diff := target - val\n if diff > 0 {\n for _, arr := range combinationSum(candidates[i:], diff) {\n\t\t\t\t// Adding dots after second slice can let you pass multiple arguments to a variadic function from a slice\n tmp := append([]int{val}, arr...)\n res = append(res, tmp)\n } \n } else if diff == 0 {\n res = append(res, []int{val})\n }\n }\n \n return res\n}", "func minimumSize(nums []int, maxOperations int) int {\n\tmaxe := 0\n\tfor _, v := range nums {\n\t\tif v > maxe {\n\t\t\tmaxe = v\n\t\t}\n\t}\n\tl, r := 1, maxe\n\tfor l < r {\n\t\tmid := (l + r) / 2\n\t\tall := 0\n\t\t// count how many ops we need to make the max number of balls as mid\n\t\t// to divide x balls into some parts where each part <= t,\n\t\t// we need ceiling(x/t)-1 = (x-1)/t times of divide.\n\t\tfor _, v := range nums {\n\t\t\tall += (v - 1) / mid\n\t\t}\n\t\tif all > maxOperations {\n\t\t\tl = mid + 1\n\t\t} else {\n\t\t\tr = mid\n\t\t}\n\t}\n\treturn l\n}", "func IsPossible(arr []int, target int) bool {\n\t// No number to check - we're out.\n\tif len(arr) == 0 {\n\t\treturn false\n\t}\n\t// We reached the result !\n\tif len(arr) == 1 && arr[0] == target {\n\t\treturn true\n\t}\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tnewArr := []int{}\n\t\t\tfor k := 0; k < len(arr); k++ {\n\t\t\t\tif !(k == j || k == i) {\n\t\t\t\t\tnewArr = append(newArr, arr[k])\n\t\t\t\t}\n\t\t\t}\n\t\t\telem := arr[i] + arr[j]\n\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\telem = arr[i] - arr[j]\n\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\telem = arr[j] - arr[i]\n\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\telem = arr[i] * arr[j]\n\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif arr[j] != 0 && arr[i]%arr[j] == 0 {\n\t\t\t\telem = arr[i] / arr[j]\n\t\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif arr[i] != 0 && arr[j]%arr[i] == 0 {\n\t\t\t\telem = arr[j] / arr[i]\n\t\t\t\tif IsPossible(append(newArr, elem), target) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func FindBestValue(arr []int, target int) int{\n\tsort.Ints(arr)\n\tvar l int = len(arr)\n\tif (arr[0] * l) >= target{\n\t\tres1 := target / l\n\t\tres2 := target / l + 1\n\t\tif (target - res1 * l) <= (res2 * l - target){\n\t\t\treturn res1\n\t\t} else{\n\t\t\treturn res2\n\t\t}\n\t}\n\tif (arr[l - 1] * l) <= target{\n\t\treturn arr[l - 1]\n\t}\n\tvar prefix int = 0\n\tvar cur_sum int = 0\n\tfor i := 0;i < l;i++{\n\t\tcur_sum = prefix + arr[i] * (l - i)\n\t\tif cur_sum >= target{\n\t\t\tres1 := (target - prefix)/ (l - i)\n\t\t\tres2 := res1 + 1\n\t\t\tval1 := target - prefix - res1 * (l - i)\n\t\t\tval2 := prefix + res2 * (l - i) - target\n\t\t\tif val1 <= val2{\n\t\t\t\treturn res1\n\t\t\t}else{\n\t\t\t\treturn res2\n\t\t\t}\n\t\t}\n\t\tprefix += arr[i]\n\t}\n\treturn arr[l - 1]\n}", "func minOperations1827(nums []int) int {\n\tres := 0\n\tfor i := 1; i < len(nums); i++ {\n\t\ta := nums[i-1]\n\t\tb := nums[i]\n\t\tif a >= b {\n\t\t\tres += a + 1 - b\n\t\t\tnums[i] = a + 1\n\t\t}\n\t}\n\treturn res\n}", "func Test_combinationSum(t *testing.T) {\n\ttype args struct {\n\t\tcandidates []int\n\t\ttarget int\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant [][]int\n\t}{\n\t\t{name: \"test\", args: struct {\n\t\t\tcandidates []int\n\t\t\ttarget int\n\t\t}{candidates: []int{2, 3, 6, 7}, target: 7}, want: [][]int{\n\t\t\t{7},\n\t\t\t{2, 2, 3},\n\t\t}},\n\t\t{name: \"test\", args: struct {\n\t\t\tcandidates []int\n\t\t\ttarget int\n\t\t}{candidates: []int{2, 3, 5}, target: 8}, want: [][]int{\n\t\t\t{2, 2, 2, 2},\n\t\t\t{2, 3, 3},\n\t\t\t{3, 5},\n\t\t}},\n\t\t{name: \"test\", args: struct {\n\t\t\tcandidates []int\n\t\t\ttarget int\n\t\t}{candidates: []int{7, 3, 2}, target: 18}, want: [][]int{\n\t\t\t{2, 2, 2, 2, 2, 2, 2, 2, 2},\n\t\t\t{2, 2, 2, 2, 2, 2, 3, 3},\n\t\t\t{2, 2, 2, 2, 3, 7},\n\t\t\t{2, 2, 2, 3, 3, 3, 3},\n\t\t\t{2, 2, 7, 7},\n\t\t\t{2, 3, 3, 3, 7},\n\t\t\t{3, 3, 3, 3, 3, 3},\n\t\t}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := combinationSum(tt.args.candidates, tt.args.target)\n\n\t\t\tvar less func(a, b []int) bool\n\t\t\tless = func(a, b []int) bool {\n\t\t\t\tif len(a) == 0 && len(b) == 0 {\n\t\t\t\t\treturn true\n\t\t\t\t} else if len(a) == 0 {\n\t\t\t\t\treturn true\n\t\t\t\t} else if len(b) == 0 {\n\t\t\t\t\treturn false\n\t\t\t\t} else {\n\t\t\t\t\tif a[0] != b[0] {\n\t\t\t\t\t\treturn a[0] < b[0]\n\t\t\t\t\t}\n\t\t\t\t\treturn less(a[1:], b[1:])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsortFunc := func(data [][]int) {\n\t\t\t\tfor i := 0; i < len(data); i++ {\n\t\t\t\t\tsort.Ints(data[i])\n\t\t\t\t}\n\t\t\t\tsort.Slice(data, func(i, j int) bool {\n\t\t\t\t\treturn less(data[i], data[j])\n\t\t\t\t})\n\t\t\t}\n\t\t\tsortFunc(got)\n\t\t\tsortFunc(tt.want)\n\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"combinationSum(%v) \\nres %v, \\nwant %v\", tt.args, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func NumSubmatrixSumTarget(matrix [][]int, target int) int {\n\tvar rows int = len(matrix)\n\tvar columns int = len(matrix[0])\n\tvar prefix [][]int = make([][]int,rows + 1)//prefix[i][j] = sum from 0,0 to i - 1,j - 1\n\tfor i := 0;i <= rows;i++{\n\t\tprefix[i] = make([]int,columns + 1)\n\t}\n\tfor i := 1;i <= rows;i++{\n\t\tfor j := 1;j <= columns;j++{\n\t\t\tprefix[i][j] = matrix[i - 1][j - 1] + prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1]\n\t\t}\n\t}\n\tvar res int = 0\n\tfor i := 0;i <= rows;i++{\n\t\tfor j := 0;j <= columns;j++{\n\t\t\tfor r := i + 1;r <= rows;r++{\n\t\t\t\tfor c := j + 1;c <= columns;c++{\n\t\t\t\t\tarea := prefix[r][c] - prefix[r][j] - prefix[i][c] + prefix[i][j]\n\t\t\t\t\tif area == target{\n\t\t\t\t\t\tres++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\tmax, arr, sum := int64(0), make([]int64, n), int64(0)\n\n\t// Instead of observing increases on each individual value...\n\t// We observe each beginning of range increase, and where it ends.\n\t//\n\t// For example:\n\t// n = 5, m = 3\n\t// a b k\n\t// 1 2 100 -> this will add 100 to n[1 - 1] and -100 to n[2]\n\t// 2 5 100 -> this will add 100 to n[2 - 1] and should add -100 to n[5] or none at all since it is beyond index range\n\t// 3 4 100\n\t// Expected output: 200\n\t//\n\t// Begin with: [5]int64 {0, 0, 0, 0, 0}\n\t// Then we iterate through the queries\n\t// m[0]: {100, 0, -100, 0, 0}\n\t// m[1]: {100, 100, -100, 0, 0}\n\t// m[2]: {100, 100, 0, 0, -100}\n\t//\n\t// Then we'll get sum of the whole array\n\t// while observing the peak sum as max value\n\t// (0)+100 100(+100) 200(+0) 200(+0) 100(-100)\n\n\tfor i := 0; i < len(queries); i++ {\n\t\tquery := queries[i]\n\t\ta := query[0] - 1\n\t\tb := query[1] - 1\n\t\tk := int64(query[2])\n\t\tarr[a] += k\n\t\tif b+1 < n {\n\t\t\tarr[b+1] -= k\n\t\t}\n\t}\n\tfor i := int32(0); i < n; i++ {\n\t\tif arr[i] != 0 {\n\t\t\tsum += arr[i]\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func CombinationSum4(nums []int, target int) int {\n\tdp := make([]int, target+1)\n\tdp[0] = 1\n\n\tfor i := 1; i <= target; i++ {\n\t\tfor _, num := range nums {\n\t\t\tif i-num >= 0 {\n\t\t\t\tdp[i] += dp[i-num]\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[target]\n}", "func findTargetSumWays(nums []int, S int) int {\n\tcnt := 0\n\tdfs(nums, S, &cnt)\n\treturn cnt\n}", "func combinationSum2(candidates []int, target int) [][]int {\n \n}", "func FourSum(nums []int, target int) [][]int {\n\tif len(nums) < 4 {\n\t\treturn [][]int{}\n\t}\n\n\tsort.Ints(nums)\n\tlength := len(nums)\n\tret := make([][]int, 0)\n\n\tfor first := 0; first < length-3; first++ {\n\t\tif first > 0 && nums[first] == nums[first-1] {\n\t\t\tcontinue\n\t\t}\n\t\tfor second := first+1; second < length-2; second++ {\n\t\t\tif second > first+1 && nums[second] == nums[second-1] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttmp := target - nums[first] - nums[second]\n\t\t\ti, j := second+1, length-1\n\t\t\tfor i < j {\n\t\t\t\tsum := nums[i] + nums[j]\n\t\t\t\tif sum == tmp {\n\t\t\t\t\tret = append(ret, []int{nums[first], nums[second], nums[i], nums[j]})\n\t\t\t\t\tfor i < j && nums[i] == nums[i+1] && nums[j] == nums[j-1] {\n\t\t\t\t\t\tj--\n\t\t\t\t\t\ti++\n\t\t\t\t\t}\n\t\t\t\t\tj--\n\t\t\t\t\ti++\n\t\t\t\t} else if sum > tmp {\n\t\t\t\t\tj--\n\t\t\t\t} else {\n\t\t\t\t\ti++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}", "func minIncrementForUnique(A []int) int {\n\tarr := [80000]int{}\n\tfor _, v := range A {\n\t\tarr[v]++\n\t}\n\n\tvar (\n\t\tans int\n\t\ttoken int\n\t)\n\tfor i := 0; i < 80000; i++ {\n\t\tif arr[i] > 1 {\n\t\t\ttoken += arr[i] - 1\n\t\t\tans -= i * (arr[i] - 1)\n\t\t} else if token > 0 && arr[i] == 0 {\n\t\t\ttoken--\n\t\t\tans += i\n\t\t}\n\t}\n\n\treturn ans\n}", "func firstGE(nums []int, target int) int {\n\n\tif nums[0] >= target {\n\t\treturn 0\n\t}\n\tvar start = 0\n\tvar end = len(nums)\n\tfor start+1 < end {\n\t\tvar mid = start + (end-start)/2\n\t\tif nums[mid] >= target {\n\t\t\tend = mid\n\t\t} else {\n\t\t\tstart = mid\n\t\t}\n\t}\n\treturn end\n}", "func getLongestIncrease(arr []int) (int, []int) {\n\tvar size = len(arr)\n\tvar current, saved []int\n\tvar noIncrease = true\n\n\t// fmt.Printf(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tu.Debug(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tfor m := 0; m < size-1; m++ {\n\t\tfor i := m; i < size-1; i++ {\n\t\t\tfor j := i + 1; j < size && (size-j) >= len(saved); j++ {\n\t\t\t\tvar opt = arr[i]\n\t\t\t\tvar previous = opt\n\t\t\t\tcurrent = []int{previous}\n\t\t\t\tfor k := j; k < size; k++ {\n\t\t\t\t\tif arr[k] > previous {\n\t\t\t\t\t\topt = previous\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent = append(current, previous)\n\t\t\t\t\t\tnoIncrease = false\n\t\t\t\t\t} else if arr[k] > opt {\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent[len(current)-1] = previous\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// fmt.Printf(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tu.Debug(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tif len(current) > len(saved) {\n\t\t\t\t\tsaved = current\n\t\t\t\t}\n\t\t\t\t// never true but proves how condition should work in `for j` loop\n\t\t\t\tif len(saved) > (size - j) {\n\t\t\t\t\t// fmt.Println(\"break\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif noIncrease {\n\t\treturn 0, []int{}\n\t} else if len(current) > len(saved) {\n\t\treturn len(current), current\n\t}\n\n\treturn len(saved), saved\n}", "func minIncrementForUnique(A []int) int {\n \n}", "func tugOfWarUtil(array []int, n int, current_elements []bool, num_of_selected_elements int,\n ret []bool, min_diff *int, sum int, current_sum int, current_position int) {\n if current_position == n {\n return\n }\n\n if ((n/2 - num_of_selected_elements) > (n - current_position)) {\n return\n }\n\n tugOfWarUtil(array, n, current_elements, num_of_selected_elements, ret,\n min_diff, sum, current_sum, current_position + 1)\n\n num_of_selected_elements++\n current_sum = current_sum + array[current_position]\n current_elements[current_position] = true\n\n if num_of_selected_elements == (n/2) {\n if (math.Abs(float64(sum/2) - float64(current_sum)) < float64(*min_diff)) {\n *min_diff = int(math.Abs(float64(sum/2) - float64(current_sum)))\n for i := 0; i < n; i++ {\n ret[i] = current_elements[i]\n }\n }\n } else {\n tugOfWarUtil(array, n, current_elements, num_of_selected_elements, ret,\n min_diff, sum, current_sum, current_position + 1)\n }\n\n current_elements[current_position] = false\n}", "func twoSum01(nums []int, target int) []int {\n\tnumMap := map[int]int{}\n\tfor i, v := range nums {\n\t\tnumMap[v] = i\n\t}\n\n\tfor i, v := range nums {\n\t\tif index, ok := numMap[target-v]; ok && index != i {\n\t\t\treturn []int{i, index}\n\t\t}\n\t}\n\n\treturn nil\n}", "func findTargetSumWays(nums []int, S int) int {\n\tvar fmap = make(map[int]int)\n\tfmap[0] = 1\n\tfor i := 0; i < len(nums); i++ {\n\t\tnmap := make(map[int]int)\n\t\tfor k, v := range fmap {\n\t\t\tnmap[k+nums[i]] = nmap[k+nums[i]] + v\n\t\t\tnmap[k-nums[i]] = nmap[k-nums[i]] + v\n\t\t}\n\t\tfmap = nmap\n\t}\n\treturn fmap[S]\n}", "func IntUnion(lt IntLessThan, sorted ...[]int) []int {\n\tlength := 0\n\tsourceSlices := make([][]int, 0, len(sorted))\n\tfor _, src := range sorted {\n\t\tif len(src) > 0 {\n\t\t\tlength += len(src)\n\t\t\tsourceSlices = append(sourceSlices, src)\n\t\t}\n\t}\n\tif length == 0 {\n\t\treturn nil\n\t} else if len(sourceSlices) == 1 {\n\t\treturn sourceSlices[0]\n\t}\n\tresult := make([]int, length)\n\tsourceSliceCount := len(sourceSlices)\n\tindexes := make([]int, sourceSliceCount)\n\tindex := 0\n\tfor {\n\t\tminSlice := 0\n\t\tminItem := sourceSlices[0][indexes[0]]\n\t\tfor i := 1; i < sourceSliceCount; i++ {\n\t\t\tif lt(sourceSlices[i][indexes[i]], minItem) {\n\t\t\t\tminSlice = i\n\t\t\t\tminItem = sourceSlices[i][indexes[i]]\n\t\t\t}\n\t\t}\n\t\tresult[index] = minItem\n\t\tindex++\n\t\tindexes[minSlice]++\n\t\tif indexes[minSlice] == len(sourceSlices[minSlice]) {\n\t\t\tsourceSlices = append(sourceSlices[:minSlice], sourceSlices[minSlice+1:]...)\n\t\t\tindexes = append(indexes[:minSlice], indexes[minSlice+1:]...)\n\t\t\tsourceSliceCount--\n\t\t\tif len(sourceSlices) == 1 {\n\t\t\t\tcopy(result[index:], sourceSlices[0][indexes[0]:])\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\t}\n}", "func maxSubArray(nums []int) int {\n dp := make([]int, len(nums))\n if len(nums) == 0 {\n return 0\n }\n if len(nums) == 1 {\n return nums[0]\n }\n result := nums[0]\n for i:=0; i<len(nums); i++ {\n if i == 0 {\n dp[0] = nums[0]\n continue\n }\n if dp[i-1] > 0 {\n dp[i] = dp[i-1] + nums[i]\n } else {\n dp[i] = nums[i]\n }\n if dp[i] > result {\n result = dp[i]\n }\n }\n return result\n}", "func part2(arr []int) int {\n\tvar i, j, k int\n\tn := len(arr)\n\n\tvar found bool = false\n\tfor i = 0; i < n; i++ {\n\t\tj = i + 1\n\t\tk = n - 1\n\t\tvar tempTarget int = target - arr[i]\n\t\tfor j < n && k >= 0 {\n\t\t\tif arr[j]+arr[k] == tempTarget {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif arr[j]+arr[k] < tempTarget {\n\t\t\t\tj++\n\t\t\t} else {\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn arr[i] * arr[j] * arr[k]\n}", "func WorkForTarget(target *big.Int) *big.Int {\n\tout := bn256()\n\ttarPlusOne := new(big.Int).Add(target, bigOne)\n\tout.Div(out, tarPlusOne)\n\treturn out\n}", "func Solution(A []int) int {\n\n\tN := len(A)\n\n\tsum := make([]int, N)\n\tsum[0] = A[0]\n\tfor i := 1; i < N; i++ {\n\t\tsum[i] = sum[i-1] + A[i]\n\t}\n\n\tif sum[N-1] >= 0 {\n\t\treturn N\n\t}\n\n\t// Now lets look for repitions in sum, basically the next position where a sum repeats\n\t// is indicative of non zero (especially for negative values)\n\tlower := make(map[int]int)\n\tupper := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\ts := sum[i]\n\t\t_, ok := lower[s]\n\t\tif !ok {\n\t\t\tlower[s] = i\n\t\t\tupper[s] = -1 // dummy\n\t\t} else {\n\t\t\tupper[s] = i\n\t\t}\n\t}\n\n\t// fmt.Printf(\"lower: %v\\n\", lower)\n\t// fmt.Printf(\"upper: %v\\n\", upper)\n\n\tvar sum_arr []int\n\tfor s, _ := range lower {\n\t\tsum_arr = append(sum_arr, s)\n\t}\n\n\tsort.Ints(sum_arr)\n\n\tmax_gap := 0\n\tfirst_lower := N\n\tfor i := 0; i < len(sum_arr); i++ {\n\t\ts := sum_arr[i]\n\t\tl := lower[s]\n\t\tif l < first_lower {\n\t\t\tfirst_lower = l\n\t\t\t//fmt.Printf(\"first_lower: %v\\n\", first_lower)\n\t\t}\n\n\t\tu := upper[s]\n\t\t// fmt.Printf(\"u: %v\\n\", u)\n\t\tgap := u - first_lower\n\t\tif s >= 0 {\n\t\t\t// or 0 or more the values are inclusive by 1\n\t\t\tgap++\n\t\t}\n\t\tif gap > max_gap {\n\t\t\tmax_gap = gap\n\t\t}\n\t}\n\n\treturn max_gap\n}", "func threeSumClosest(nums []int, target int) int {\n\t// sort the array\n\tsort.Ints(nums)\n\tminDiff := math.Inf(1)\n\tsum, closestSum := 0, 0\n\n\t// Optional: keep track of the optimal indices\n\tindices := make([]int, 3)\n\n\t// for each index use pivot\n\tfor i := range nums {\n\t\t// fix i and search 2 indices(j, k) such that nums[i]+ nums[j]+nums[k] ~ target\n\t\tnTarget := target - nums[i]\n\t\tj, k := i+1, len(nums)-1\n\t\t// make sure i is not counted twice\n\t\tfor j < k {\n\t\t\tsum = nums[j] + nums[k] + nums[i]\n\t\t\tdiff := math.Abs(float64(target - sum))\n\t\t\tif diff < minDiff {\n\t\t\t\tminDiff = diff\n\t\t\t\tclosestSum = sum\n\t\t\t\tindices = []int{nums[i], nums[j], nums[k]}\n\t\t\t\tfmt.Printf(\"saw a new min: %v sum: %d\\n\", minDiff, sum)\n\t\t\t}\n\n\t\t\tif nTarget > nums[j]+nums[k] {\n\t\t\t\tj++\n\t\t\t} else {\n\t\t\t\tk--\n\t\t\t}\n\n\t\t}\n\n\t}\n\tfmt.Println(\"Final set of nums: \", indices)\n\treturn closestSum\n}", "func findShortestSubArray(nums []int) int {\n \n}", "func (s *solution) SmallestUnreachable() int {\n\t// Write your code here\n\tpowerSetHelper := func (original []int) [][]int {\n\t\tpowerSetSize := int(math.Pow(2, float64(len(original))))\n\t\tresult := make([][]int, 0, powerSetSize)\n\n\t\tvar index int\n\t\tfor index < powerSetSize {\n\t\tvar subSet []int\n\n\t\tfor j, elem := range original {\n\t\tif index& (1 << uint(j)) > 0 {\n\t\tsubSet = append(subSet, elem)\n\t}\n\t}\n\t\tresult = append(result, subSet)\n\t\tindex++\n\t}\n\t\treturn result\n\t}\n\n\n\tnbills := s.GetNumBills()\n\tfmt.Println(\"number of bills\", nbills)\n\tbills := make([]int, nbills)\n\tfor i := 0; i < nbills ; i++ {\n\t\tbills[i] = s.GetBill(i)\n\t}\n\tfmt.Println(\"Bills\", bills)\n\tprice := s.GetPrice()\n\tfmt.Println(\"Price\", price)\n\tpayment := s.GetPayment()\n\tfmt.Println(\"payment\", payment)\n\tdiff := payment - price\n\tfmt.Println(\"diff\", diff)\n\n\tp := powerSetHelper(bills)\n\tmax := 0\n\tmaxIndex := -1\n\tfor i,v := range p {\n\t\tsum := 0\n\t\tfor _,b := range v {\n\t\t\tsum += b\n\t\t}\n\t\tif sum > max {\n\t\t\tmax = sum\n\t\t\tmaxIndex = i\n\t\t}\n\t}\n\tfmt.Println(p[maxIndex])\n\n\treturn diff - max\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n // slice is initialized with zeroes\n // 1-based indices + another element for the decrease\n // if upper bound == n\n arr := make([]int64, n+2)\n\n for _, row := range queries {\n var lhs, rhs, k = row[0], row[1], row[2]\n\n arr[lhs] += int64(k)\n arr[rhs+1] -= int64(k)\n }\n\n // Find maximum by adding up the changes into an accumulator.\n // all k are positive => invariant: acc >= 0.\n var acc, max int64 = 0, 0\n\n for _, val := range arr {\n acc += val\n if acc > max {\n max = acc\n }\n }\n\n return max\n}", "func minimumSwaps(arr []int32) int32 {\n fmt.Println(arr)\n // n - (i + 1)\n swaps := int32(0)\n weights, err := getArrayWeights(arr)\n if err != nil {\n return swaps\n }\n \n //fmt.Printf(\"weights: %d \\n\", weights)\n \n min, max := getMinAndMaxPositions(weights)\n //fmt.Printf(\"min: %d, max: %d\\n\", min, max)\n \n swap(arr, min, max)\n swaps++\n \n //fmt.Printf(\"%d: %d \\n\", swaps, arr)\n //fmt.Println(\"-----\")\n return swaps + minimumSwaps(arr)\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\n\tvar ret int64\n\n\t// create a slice with n amount of zeros\n\tmainSlice := []int32{}\n\tvar i int32\n\tfor i = 0; i <= n; i++ {\n\t\t// append 'n' number of 0's to slice to begin\n\t\tmainSlice = append(mainSlice, 0)\n\t}\n\n\tmainSlice = addKValsToArr(mainSlice, queries)\n\n\ttemp := mainSlice[0]\n\tfor i = 0; i <= n; i++ {\n\t\tif mainSlice[i] > temp {\n\t\t\ttemp = mainSlice[i]\n\t\t}\n\t}\n\n\tret = int64(temp)\n\n\treturn ret\n}", "func MinimumSwap(arr []int, k int) {\n\tvar smallerElement int\n\tvar ans int = 1e4\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] <= k {\n\t\t\tsmallerElement++\n\t\t}\n\t}\n\tvar presentElements int\n\tfor i := 0; i < smallerElement; i++ {\n\t\tif arr[i] <= k {\n\t\t\tpresentElements++\n\t\t}\n\t}\n\tans = min(ans, smallerElement-presentElements)\n\ti := 0\n\tfor j := smallerElement; j < len(arr); j++ {\n\t\tif arr[i] <= k {\n\t\t\tpresentElements--\n\t\t}\n\t\tif arr[j] <= k {\n\t\t\tpresentElements++\n\t\t}\n\t\tans = min(ans, smallerElement-presentElements)\n\t\ti++\n\t}\n\tfmt.Println(ans)\n}", "func Tianyun_searchRange(nums []int, target int) []int {\n\n\t//O(n)\n//\tstartIndex:=-1\n//\tcount:=0\n//\n//\tfor i:=0;i<len(nums);i++{\n//\t\tif count==0&&nums[i]==target{\n//\t\t\tstartIndex = i\n//\t\t\tcount++\n//\n//\t\t}else if nums[i]==target{\n//\t\t\tcount++\n//\t\t}\n//}\n//\n// if count==0{\n// \treturn []int{-1,-1}\n// }else{\n// \treturn []int{startIndex,startIndex+count}\n// }\n\n\n\n//O(logn)\nif len(nums)==0{\n\treturn []int{-1,-1}\n}\n startIndex:=-1\n left:=0\n right:=len(nums)-1\n\n for left +1 <right{\n \tmid:=(left+right)/2\n \tif nums[mid]>=target{\n right = mid\n\t\t}else{\n\t\t\tleft =mid+1\n\t\t}\n\t }\n\t if nums[left]==target{\n\t \tstartIndex =left\n\t }else if nums[right]==target{\n\t \tstartIndex = right\n\t }else{\n\t \treturn []int{-1,-1}\n\t }\n\n\n\tleft=0\n\tright=len(nums)-1\n\n\tfor left +1 <right{\n\t\tmid:=(left+right)/2\n\t\tif nums[mid]<=target{\n\t\t\tleft = mid\n\t\t}else{\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tif nums[right]==target{\n\t\treturn []int{startIndex,right}\n\t}else if nums[left]==target{\n\t\treturn []int{startIndex,left}\n\t}else{\n\t\treturn []int{-1,-1}\n\t}\n}", "func func1(nums []int) int {\n\tn := len(nums);\n\tlength := make([]int, n);\n\tcount := make([]int, n);\n\n\tfor i := 0; i < n; i++ {\n\t\tlength[i] = 1;\n\t\tcount[i] = 1;\n\t}\n\n\tmaxLen := 1;\n\tfor i := n-1; i >= 0; i-- {\n\t\tfor j := i+1; j < n; j++ {\n\t\t\tif nums[i] < nums[j] {\n\t\t\t\tif length[j]+1 > length[i] {\n\t\t\t\t\tlength[i] = length[j]+1;\n\t\t\t\t\tcount[i] = count[j];\n\t\t\t\t} else if length[j]+1 == length[i] {\n\t\t\t\t\tcount[i] += count[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// fmt.Printf(\"i=%d, length=%d, count=%d\\n\", i, length[i], count[i]);\n\t\tif length[i] > maxLen {\n\t\t\tmaxLen = length[i];\n\t\t}\n\t}\n\n\tret := 0;\n\tfor i := 0; i < n; i++ {\n\t\tif length[i] == maxLen {\n\t\t\tret += count[i];\n\t\t}\n\t}\n\n\treturn ret;\n}", "func threeSumClosest(nums []int, target int) int {\n\tres := 0\n\tif len(nums) < 3 {\n\t\treturn res\n\t}\n\tsort.Ints(nums)\n\tres = nums[0] + nums[1] + nums[2]\n\tfor i := 0; i < len(nums)-2; i++ {\n\t\tfix := nums[i]\n\n\t\tif i > 0 && nums[i] == nums[i-1] {\n\t\t\tcontinue\n\t\t}\n\t\tleft := i + 1\n\t\trig := len(nums) - 1\n\t\tfor left < rig {\n\t\t\ttmp := fix + nums[left] + nums[rig]\n\n\t\t\t//for left < rig && nums[left] == nums[left+1] {\n\t\t\t//\tleft++\n\t\t\t//}\n\t\t\t//for left < rig && nums[rig] == nums[rig-1] {\n\t\t\t//\trig--\n\t\t\t//}\n\t\t\tif math.Abs(float64(tmp-target)) < math.Abs(float64(res-target)) {\n\t\t\t\tres = tmp\n\t\t\t}\n\t\t\tif tmp < target {\n\t\t\t\tleft++\n\t\t\t} else if tmp > target {\n\t\t\t\trig--\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t}\n\treturn res\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsorted := MergeSort(A)\n\tcounter := 0\n\tvar initial int\n\tfor k := 0; k < len(sorted); k++ {\n\t\tif k == 0 {\n\t\t\tinitial = sorted[k]\n\t\t\tcounter++\n\t\t} else {\n\t\t\tif sorted[k] != initial {\n\t\t\t\tinitial = sorted[k]\n\t\t\t\tcounter++\n\t\t\t}\n\t\t}\n\t}\n\treturn counter\n}", "func twoSumEfficient(arr []int, target int) []int {\n\tm := make(map[int]int)\n\tfor i := 0; i < len(arr); i++ {\n\t\tcompliment := target - arr[i]\n\t\tif _, ok := m[compliment]; ok {\n\t\t\treturn []int{m[compliment], i}\n\t\t}\n\t\tm[arr[i]] = i\n\t}\n\treturn []int{}\n}", "func computeTargetBuckets(numPeers int) (int, int) {\n\ttargetBuckets := 1\n\tdefensiveTargetBuckets := 1\n\tbufferWidth := numPeers/10 - 1\n\n\tif numPeers > 0 {\n\t\tfor t := (numPeers - 1) >> 9; t != 0; t = t >> 1 {\n\t\t\ttargetBuckets = targetBuckets * 2\n\t\t}\n\t\tfor t := (numPeers + bufferWidth) >> 9; t != 0; t = t >> 1 {\n\t\t\tdefensiveTargetBuckets = defensiveTargetBuckets * 2\n\t\t}\n\t}\n\n\treturn targetBuckets, defensiveTargetBuckets\n}", "func computeMinimumCopyLength(start_cost float32, nodes []zopfliNode, num_bytes uint, pos uint) uint {\n\tvar min_cost float32 = start_cost\n\tvar len uint = 2\n\tvar next_len_bucket uint = 4\n\t/* Compute the minimum possible cost of reaching any future position. */\n\n\tvar next_len_offset uint = 10\n\tfor pos+len <= num_bytes && nodes[pos+len].u.cost <= min_cost {\n\t\t/* We already reached (pos + len) with no more cost than the minimum\n\t\t possible cost of reaching anything from this pos, so there is no point in\n\t\t looking for lengths <= len. */\n\t\tlen++\n\n\t\tif len == next_len_offset {\n\t\t\t/* We reached the next copy length code bucket, so we add one more\n\t\t\t extra bit to the minimum cost. */\n\t\t\tmin_cost += 1.0\n\n\t\t\tnext_len_offset += next_len_bucket\n\t\t\tnext_len_bucket *= 2\n\t\t}\n\t}\n\n\treturn uint(len)\n}", "func minimumSwaps(arr []int32) int32 {\n\tswap := int32(0)\n\tfor i := int32(0); i < int32(len(arr)); i++ {\n\t\tif (i + 1) != arr[i] {\n\t\t\tt := i\n\t\t\tfor arr[t] != i+1 {\n\t\t\t\tt++\n\t\t\t}\n\t\t\ttemp := arr[t]\n\t\t\tarr[t] = arr[i]\n\t\t\tarr[i] = temp\n\t\t\tswap++\n\t\t}\n\t}\n\treturn swap\n}", "func FindVulnerability(data []int, target int) (int, bool) {\n\tif len(data) < 2 {\n\t\treturn 0, false\n\t}\n\tfor size := 2; size < len(data); size++ {\n\t\tfor start := 0; start+size-1 < len(data); start++ {\n\t\t\tsubset := data[start : start+size]\n\t\t\tsum := 0\n\t\t\tfor _, v := range subset {\n\t\t\t\tsum += v\n\t\t\t}\n\t\t\tif sum == target {\n\t\t\t\tvar clone = make([]int, size)\n\t\t\t\tcopy(clone, subset)\n\t\t\t\tsort.Ints(clone)\n\t\t\t\treturn clone[0] + clone[size-1], true\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, false\n}", "func maxSubArray(nums []int) int {\n if len(nums) == 0 {\n return 0\n }\n result := nums[0]\n preSum := nums[0]\n for i:=1; i<len(nums); i++ {\n if preSum < 0 {\n preSum = nums[i]\n } else {\n preSum += nums[i]\n }\n result = max(result, preSum)\n }\n return result\n}", "func threeSumClosest16(nums []int, target int) int {\n\tn := len(nums)\n\tsort.Ints(nums)\n\tres := nums[0] + nums[1] + nums[n-1]\n\n\tfor i := 0; i < n-2; i++ {\n\t\tif i > 0 && nums[i] == nums[i-1] {\n\t\t\tcontinue\n\t\t}\n\t\tl, r := i+1, n-1\n\t\tfor l < r {\n\t\t\tval := nums[i] + nums[l] + nums[r]\n\t\t\tvalDistance := int(math.Abs(float64(target) - float64(val)))\n\t\t\tresDistance := int(math.Abs(float64(target) - float64(res)))\n\t\t\tif valDistance < resDistance {\n\t\t\t\tres = val\n\t\t\t}\n\t\t\tif val == target {\n\t\t\t\treturn target\n\t\t\t} else if val < target {\n\t\t\t\tl++\n\t\t\t} else {\n\t\t\t\tr--\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func main() {\n\tnumbers1 := []int{6, 10, 2}\n\tfmt.Println(solution(numbers1))\n\tnumbers2 := []int{3, 30, 34, 5, 9}\n\tfmt.Println(solution(numbers2))\n\tnumbers3 := []int{0, 0, 0, 0}\n\tfmt.Println(solution(numbers3))\n\n}", "func menageatrois(arr []int) {\n sort.Ints( arr )\n\n for outer := 0; outer < len(arr); outer++ {\n var a = arr[outer]\n var start = outer+1\n var end = len(arr)-1\n\n for ; start < end ; {\n var b = arr[start]\n var c = arr[end]\n\n switch {\n case a+b+c == 0:\n fmt.Println(a, b, c)\n end -=1\n case a+b+c > 0:\n end -=1\n default:\n start += 1\n }\n }\n }\n}", "func optimalUtilizationBruteForce(a, b [][]int, target int) [][]int {\n\tcurrBest := math.MinInt64\n\tvar output [][]int\n\tfor i := 0; i < len(a); i++ {\n\t\tfor j := 0; j < len(b); j++ {\n\t\t\tsum := a[i][1] + b[j][1]\n\t\t\tif sum > target {\n\t\t\t\tcontinue\n\t\t\t} else if sum > currBest {\n\t\t\t\tcurrBest = sum\n\t\t\t\toutput = [][]int{\n\t\t\t\t\t{a[i][0], b[j][0]},\n\t\t\t\t}\n\t\t\t} else if sum == currBest {\n\t\t\t\toutput = append(output, []int{a[i][0], b[j][0]})\n\t\t\t}\n\t\t}\n\t}\n\treturn output\n}", "func oneBasedToZeroBased(inputNumbers []int) []int {\n\t// TODO: write this function\n\n\t// loop through the list of input numbers and\n\t// build a new list by subtracting one from each.\n\treturn []int{0, 3, 2}\n}", "func sol2(nums1 []int, nums2 []int, k int) [][]int {\n if len(nums1) == 0 || len(nums2) == 0 {\n return nil\n }\n\n cursors := make([]int, len(nums1))\n var res [][]int\n for len(res) < k && len(res) < len(nums1) * len(nums2) {\n min := nums1[len(nums1)-1] + nums2[len(nums2)-1] + 1\n next := -1\n for i, j := range cursors {\n if j >= len(nums2) {\n continue\n }\n t := nums1[i] + nums2[j]\n if min > t {\n min = t\n next = i\n }\n // todo: skip condition\n }\n res = append(res, []int{nums1[next], nums2[cursors[next]]})\n cursors[next]++\n }\n\n return res\n}", "func Apply(op Op, data sort.Interface, pivots []int) (size int) {\n\tswitch len(pivots) {\n\tcase 0:\n\t\treturn 0\n\tcase 1:\n\t\treturn pivots[0]\n\tcase 2:\n\t\treturn op(data, pivots[0])\n\t}\n\n\tspans := make([]span, 0, len(pivots)+1)\n\n\t// convert pivots into spans (index intervals that represent sets)\n\ti := 0\n\tfor _, j := range pivots {\n\t\tspans = append(spans, span{i, j})\n\t\ti = j\n\t}\n\n\tn := len(spans) // original number of spans\n\tm := n / 2 // original number of span pairs (rounded down)\n\n\t// true if the span is being used\n\tinuse := make([]bool, n)\n\n\tch := make(chan span, m)\n\n\t// reverse iterate over every other span, starting with the last;\n\t// concurrent algo (further below) will pick available pairs operate on\n\tfor i := range spans[:m] {\n\t\ti = len(spans) - 1 - i*2\n\t\tch <- spans[i]\n\t}\n\n\tfor s := range ch {\n\t\tif len(spans) == 1 {\n\t\t\tif s.i != 0 {\n\t\t\t\tpanic(\"impossible final span\")\n\t\t\t}\n\t\t\t// this was the last operation\n\t\t\treturn s.j\n\t\t}\n\n\t\t// locate the span we received (match on start of span only)\n\t\ti := sort.Search(len(spans), func(i int) bool { return spans[i].i >= s.i })\n\n\t\t// store the result (this may change field j but not field i)\n\t\tspans[i] = s\n\n\t\t// mark the span as available for use\n\t\tinuse[i] = false\n\n\t\t// check the immediate neighbors for availability (prefer left)\n\t\tj, k := i-1, i+1\n\t\tswitch {\n\t\tcase j >= 0 && !inuse[j]:\n\t\t\ti, j = j, i\n\t\tcase k < len(spans) && !inuse[k]:\n\t\t\tj = k\n\t\tdefault:\n\t\t\t// nothing to do right now. wait for something else to finish\n\t\t\tcontinue\n\t\t}\n\n\t\ts, t := spans[i], spans[j]\n\n\t\tgo func(s, t span) {\n\t\t\t// sizes of the respective sets\n\t\t\tk, l := s.j-s.i, t.j-t.i\n\n\t\t\t// shift the right-hand span to be adjacent to the left\n\t\t\tslide(data, s.j, t.i, l)\n\n\t\t\t// prepare a view of the data (abs -> rel indices)\n\t\t\tb := boundspan{data, span{s.i, s.j + l}}\n\n\t\t\t// store result of op, adjusting for view (rel -> abs)\n\t\t\ts.j = s.i + op(b, k)\n\n\t\t\t// send the result back to the coordinating goroutine\n\t\t\tch <- s\n\t\t}(s, t)\n\n\t\t// account for the spawn merging that will occur\n\t\ts.j += t.j - t.i\n\n\t\tk = j + 1\n\n\t\t// shrink the lists to account for the merger\n\t\tspans = append(append(spans[:i], s), spans[k:]...)\n\n\t\t// (and the merged span is now in use as well)\n\t\tinuse = append(append(inuse[:i], true), inuse[k:]...)\n\t}\n\tpanic(\"unreachable\")\n}", "func findBestValue(arr []int, target int) int {\n\tmaxv := 0\n\tsum := 0\n\tfor _, v := range arr {\n\t\tsum += v\n\t\tif v>maxv {\n\t\t\tmaxv = v\n\t\t}\n\t}\n\tif target>=sum {\n\t\treturn maxv // can't be more larger\n\t}\n\tmindiff := sum-target // base line diff\n\tminvalue := maxv // base line value\n l, r := 0, maxv\n for l<=r {\n \tmid := (l+r)/2\n\n \t// get current sum\n \tsum = 0\n \tfor _, v := range arr {\n \t\tif v>mid {\n \t\t\tsum += mid\n \t\t} else {\n \t\t\tsum += v\n \t\t}\n \t}\n\n \tif sum > target {\n \t\tr = mid-1\n \t\tif sum-target < mindiff {\n \t\t\tmindiff = sum-target\n \t\t\tminvalue = mid\n \t\t} else if sum-target == mindiff && mid<minvalue { // tie\n \t\t\tminvalue = mid\n \t\t}\n \t} else if sum < target {\n \t\tl = mid+1\n \t\tif target-sum < mindiff {\n \t\t\tmindiff = target-sum\n \t\t\tminvalue = mid\n \t\t} else if target-sum == mindiff && mid<minvalue { // tie\n \t\t\tminvalue = mid\n \t\t}\n \t} else {\n \t\tminvalue = mid // find the value that make sum==target\n \t\tbreak\n \t}\n }\n return minvalue\n}", "func allPathsSourceTarget(graph [][]int) [][]int {\n ans := make([][]int, 0)\n bfs := make([][]int, 0)\n bfs = append(bfs, []int{0})\n\n for ; len(bfs) > 0 ; {\n cur := bfs[0]\n if cur[len(cur) - 1] == len(graph) - 1 {\n ans = append(ans, cur)\n }\n for _, val := range graph[cur[len(cur) - 1] ] {\n x := make([]int,len(cur))\n copy(x,cur)\n x = append(x, val)\n bfs = append(bfs, x)\n }\n bfs = bfs[1:]\n }\n return ans\n}", "func main() {\n\tarr := []int{1, 2, 3, 4, 6}\n\tts := 6\n\tres := pairWithTargetSum(arr, ts)\n\tfmt.Printf(\"Pair with target sum %d are %v\\n\", ts, res)\n\n\tarr = []int{2, 5, 9, 11}\n\tts = 11\n\tres = pairWithTargetSum(arr, ts)\n\tfmt.Printf(\"Pair with target sum %d are %v\\n\", ts, res)\n}", "func jump(nums []int) int {\n\tif len(nums) <= 1 {\n\t\treturn 0\n\t}\n\tdp := make([]int, len(nums), len(nums))\n\tdp[0] = 0\n\tfor i := 1; i < len(dp); i++ {\n\t\tdp[i] = math.MaxInt64 // assume 64 bit server\n\t}\n\n\tfor i := 1; i < len(nums); i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif dp[j] != math.MaxInt64 && nums[j] + j >= i {\n\t\t\t\tdp[i] = utils.Min(dp[i], dp[j]+1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(dp)-1]\n}", "func Solution(a []int) int {\n\tpassingCars := 0\n\tcarsMovingWest := prefixSums(a)\n\ttotalCarsMovingWest := carsMovingWest[len(a)]\n\tfor i, item := range a {\n\t\tif item == 0 {\n\t\t\tpassingCars += totalCarsMovingWest - carsMovingWest[i]\n\t\t}\n\t}\n\tif passingCars > maxPassingCarsCount {\n\t\treturn tooManyPassingCars\n\t}\n\treturn passingCars\n}", "func TestCanAllocate(t *testing.T) {\n\tvar cases = []struct {\n\t\ta Money\n\t\tratios []uint\n\t\twant []Money\n\t}{\n\t\t{0, []uint{1, 1, 1}, []Money{0, 0, 0}},\n\t\t{1, []uint{1, 1, 1}, []Money{1, 0, 0}},\n\t\t{2, []uint{1, 1, 1}, []Money{1, 1, 0}},\n\t\t{3, []uint{1, 1, 1}, []Money{1, 1, 1}},\n\t\t{4, []uint{1, 1, 1}, []Money{2, 1, 1}},\n\t\t{5, []uint{1, 1, 1}, []Money{2, 2, 1}},\n\t\t{100, []uint{0, 1, 0}, []Money{0, 100, 0}},\n\t\t{3, []uint{0, 5, 0}, []Money{0, 3, 0}},\n\t\t{300, []uint{1, 1, 1}, []Money{100, 100, 100}},\n\t\t{100, []uint{1, 1, 1}, []Money{34, 33, 33}},\n\t\t{3, []uint{0, 5, 0}, []Money{0, 3, 0}},\n\t\t{3, []uint{0, 4, 2}, []Money{0, 2, 1}},\n\n\t\t// Allocate spare pennies and skip zero weighting.\n\t\t{7, []uint{0, 1, 1}, []Money{0, 4, 3}},\n\n\t\t// Copied from MoneyTest.php\n\t\t{105, []uint{3, 7}, []Money{32, 73}},\n\t\t{5, []uint{1, 1}, []Money{3, 2}},\n\t\t{30000, []uint{122, 878}, []Money{3660, 26340}},\n\t\t{30000, []uint{122, 0, 878}, []Money{3660, 0, 26340}},\n\t\t{12000, []uint{20, 100}, []Money{2000, 10000}},\n\n\t\t// If weightings are equal, the amount will be shared.\n\t\t{30000, []uint{0}, []Money{30000}},\n\t\t{30000, []uint{0, 0, 0}, []Money{10000, 10000, 10000}},\n\n\t\t// Repeat all of the above with negatives.\n\t\t{-0, []uint{1, 1, 1}, []Money{0, 0, 0}},\n\t\t{-1, []uint{1, 1, 1}, []Money{-1, 0, 0}},\n\t\t{-2, []uint{1, 1, 1}, []Money{-1, -1, 0}},\n\t\t{-3, []uint{1, 1, 1}, []Money{-1, -1, -1}},\n\t\t{-4, []uint{1, 1, 1}, []Money{-2, -1, -1}},\n\t\t{-5, []uint{1, 1, 1}, []Money{-2, -2, -1}},\n\t\t{-100, []uint{0, 1, 0}, []Money{0, -100, 0}},\n\t\t{-3, []uint{0, 5, 0}, []Money{0, -3, 0}},\n\t\t{-300, []uint{1, 1, 1}, []Money{-100, -100, -100}},\n\t\t{-100, []uint{1, 1, 1}, []Money{-34, -33, -33}},\n\t\t{-3, []uint{0, 5, 0}, []Money{0, -3, 0}},\n\t\t{-3, []uint{0, 4, 2}, []Money{0, -2, -1}},\n\t\t{-105, []uint{3, 7}, []Money{-32, -73}},\n\t\t{-5, []uint{1, 1}, []Money{-3, -2}},\n\t\t{-30000, []uint{122, 878}, []Money{-3660, -26340}},\n\t\t{-30000, []uint{122, 0, 878}, []Money{-3660, 0, -26340}},\n\t\t{-12000, []uint{20, 100}, []Money{-2000, -10000}},\n\t\t{-30000, []uint{0}, []Money{-30000}},\n\t\t{-30000, []uint{0, 0, 0}, []Money{-10000, -10000, -10000}},\n\t}\n\tfor ci, c := range cases {\n\t\tres := c.a.Share(c.ratios)\n\t\tif len(c.ratios) != len(res) {\n\t\t\tt.Errorf(\"Case %d. Incorrect number of allocations returned. Expected %d, got %d: %v\", ci, len(c.ratios), len(res), res)\n\t\t\treturn\n\t\t}\n\t\tfor i := range c.want {\n\t\t\tif c.want[i] != res[i] {\n\t\t\t\tt.Errorf(\"Case %d: Sharing %d into (%v), portion %d: Expected %d, got %d\", ci, c, c.ratios, i, c.want[i], res[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func ArrayOfProducts(array []int) []int {\n\tresult := 1\n\tresultArr := []int{}\n\tzeroCounter := 0\n\t// For multiplies every number by the next number\n\t// and keeps in a variable\n\tfor i := 0; i < len(array); i++ {\n\t\tswitch {\n\t\tcase zeroCounter > 1:\n\t\t\t// If we find more than 1 zero we stop iterating\n\t\t\t// because everything will be a 0\n\t\t\tbreak\n\t\tcase array[i] == 0:\n\t\t\t// keeps track of how many zeros we have\n\t\t\tzeroCounter++\n\t\tdefault:\n\t\t\tresult = result * array[i]\n\t\t}\n\t}\n\t// For creates our resultArray and fills it up\n\tfor i := 0; i < len(array); i++ {\n\t\tswitch {\n\t\tcase zeroCounter > 1:\n\t\t\t// If zeros > 1 the whole array is filled with 0s\n\t\t\tresultArr = append(resultArr, 0)\n\t\tcase array[i] == 0:\n\t\t\t// on the spot where there's a zero in our\n\t\t\t// input array we put the multiplication of all the numbers\n\t\t\t// except the zero\n\t\t\tresultArr = append(resultArr, result)\n\t\tcase zeroCounter == 1:\n\t\t\t// If there is a zero in our input array\n\t\t\t// make every spot in our output array = 0\n\t\t\tresultArr = append(resultArr, 0)\n\t\tdefault:\n\t\t\tresultArr = append(resultArr, result/array[i])\n\t\t}\n\t}\n\treturn resultArr\n}", "func jump(nums []int) int {\n\tif len(nums) <= 1 {\n\t\treturn 0\n\t}\n\n\tvar maxIdx, i, step int\n\tfor i < len(nums)-1 {\n\t\tnextIdx, tmpIdx := 0, 0\n\t\tfor j := 0; j < nums[i]; j++ {\n\t\t\ttmpIdx = i + j + 1\n\t\t\tif tmpIdx < len(nums) && tmpIdx+nums[tmpIdx] > maxIdx {\n\t\t\t\tmaxIdx = tmpIdx + nums[tmpIdx]\n\t\t\t\tnextIdx = tmpIdx\n\t\t\t}\n\t\t\tif tmpIdx == len(nums)-1 {\n\t\t\t\tnextIdx = tmpIdx\n\t\t\t}\n\t\t}\n\n\t\ti = nextIdx\n\t\tstep++\n\t}\n\n\treturn step\n}", "func threeSumClosest(nums []int, target int) int {\n\n\tvar res int\n\t//给数组排序\n\tsort.Ints(nums)\n\t//固定一个数. 其余的按双指针进行计算\n\tfor index, value := range nums {\n\n\t\tleft := index + 1\n\t\tright := len(nums) - 1\n\n\t\tfor left < right {\n\t\t\tsum := value + nums[left] + nums[right]\n\t\t\tif target-sum == 0 { //相等\n\t\t\t\tres = sum\n\t\t\t\treturn res\n\t\t\t}\n\t\t\tif sum-target > 0 { //右边大\n\t\t\t\tif target-sum < target-res {\n\t\t\t\t\tres = sum\n\t\t\t\t}\n\n\t\t\t\tright--\n\t\t\t}\n\t\t\tif sum-target < 0 { //左边大\n\t\t\t\tif target-sum < target-res {\n\t\t\t\t\tres = sum\n\t\t\t\t}\n\n\t\t\t\tleft++\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn res\n}", "func sumSubarrayMinsBasic(arr []int) int {\n\tmodBase := 1000000007\n\tsum := 0\n\tsz := len(arr)\n\tfor start := 0; start < sz; start++ {\n\t\tmin := arr[start]\n\t\tfor j := start; j < sz; j++ {\n\t\t\tif arr[j] < min {\n\t\t\t\tmin = arr[j]\n\t\t\t}\n\t\t\tsum = sum + min\n\t\t\tsum = sum % modBase\n\t\t}\n\t}\n\treturn sum\n}", "func minOperations(n int) int {\n\tif n%2 == 0 {\n\t\treturn (n >> 1) * (n >> 1)\n\t} else {\n\t\treturn (n / 2) * (n/2 + 1)\n\t}\n}", "func (s *CollapsingLowestDenseStore) adjust(newMinIndex, newMaxIndex int) {\n\tif newMaxIndex-newMinIndex+1 > len(s.bins) {\n\t\t// The range of indices is too wide, buckets of lowest indices need to be collapsed.\n\t\tnewMinIndex = newMaxIndex - len(s.bins) + 1\n\t\tif newMinIndex >= s.maxIndex {\n\t\t\t// There will be only one non-empty bucket.\n\t\t\ts.bins = make([]float64, len(s.bins))\n\t\t\ts.offset = newMinIndex\n\t\t\ts.minIndex = newMinIndex\n\t\t\ts.bins[0] = s.count\n\t\t} else {\n\t\t\tshift := s.offset - newMinIndex\n\t\t\tif shift < 0 {\n\t\t\t\t// Collapse the buckets.\n\t\t\t\tn := float64(0)\n\t\t\t\tfor i := s.minIndex; i < newMinIndex; i++ {\n\t\t\t\t\tn += s.bins[i-s.offset]\n\t\t\t\t}\n\t\t\t\ts.resetBins(s.minIndex, newMinIndex-1)\n\t\t\t\ts.bins[newMinIndex-s.offset] += n\n\t\t\t\ts.minIndex = newMinIndex\n\t\t\t\t// Shift the buckets to make room for newMaxIndex.\n\t\t\t\ts.shiftCounts(shift)\n\t\t\t} else {\n\t\t\t\t// Shift the buckets to make room for newMinIndex.\n\t\t\t\ts.shiftCounts(shift)\n\t\t\t\ts.minIndex = newMinIndex\n\t\t\t}\n\t\t}\n\t\ts.maxIndex = newMaxIndex\n\t\ts.isCollapsed = true\n\t} else {\n\t\ts.centerCounts(newMinIndex, newMaxIndex)\n\t}\n}", "func getMCombinationsOfN(m, n int) [][]int { // nolint:gocyclo\n\tswitch {\n\tcase m > n:\n\t\treturn nil\n\tcase m == 0:\n\t\treturn [][]int{{}}\n\tcase m == n:\n\t\treturn [][]int{rangeInt(0, n)}\n\t}\n\n\tcomb := rangeInt(0, m)\n\tgapStack := []int{m - 1}\n\n\tcombCopy := make([]int, len(comb))\n\tcopy(combCopy, comb)\n\n\tout := [][]int{combCopy}\n\n\tshiftingFirstElement := false\n\n\tfor len(gapStack) > 0 {\n\t\tfirstGapIndex := gapStack[len(gapStack)-1]\n\n\t\tif comb[firstGapIndex] >= n-2 || (firstGapIndex+1 < m && comb[firstGapIndex+1]-2 <= comb[firstGapIndex]) {\n\t\t\t// the element being moved rightwards will no longer be a gap, so we pop it\n\t\t\tgapStack = gapStack[:len(gapStack)-1]\n\t\t}\n\n\t\tif firstGapIndex > 0 && comb[firstGapIndex-1] == comb[firstGapIndex]-1 {\n\t\t\t// if the preceding element in the combination is directly preceding the gap element being swapped,\n\t\t\t// then the preceding element is now a gap.\n\t\t\tgapStack = append(gapStack, firstGapIndex-1)\n\t\t}\n\n\t\tcomb[firstGapIndex]++\n\n\t\tswappedIndex := firstGapIndex\n\n\t\tif swappedIndex == 0 {\n\t\t\tshiftingFirstElement = true\n\t\t} else if shiftingFirstElement {\n\t\t\t// once swappedIndex is nonzero again, do the Shift to Start step\n\t\t\tstart := comb[0]\n\n\t\t\tfor i := 0; i < swappedIndex; i++ {\n\t\t\t\tcomb[i] -= start\n\t\t\t}\n\n\t\t\tshiftingFirstElement = false\n\t\t}\n\n\t\tcombCopy = make([]int, len(comb))\n\t\tcopy(combCopy, comb)\n\n\t\tout = append(out, combCopy)\n\t}\n\n\treturn out\n}", "func main() {\n\n\tinput := []int{1, 1, 0, 1, 1, 1}\n\n\tresult := solution(input)\n\tfmt.Println(result)\n\n}", "func createSet(input [9]int8) int16 {\n\tvar used int16 = 0\n\tfor i := 0; i < 9; i++ {\n\t\tused += (1 << uint(input[i] - 1))\n\t}\n\treturn used;\n}", "func twoSumOne(nums []int, target int) []int {\n\tif len(nums) == 0 {\n\t\treturn []int{}\n\t}\n\n\tvar numMap map[int][]int\n\tnumMap = mapByIndex(nums)\n\n\tfor i, num := range nums {\n\t\tindices, hasVal := numMap[target-num]\n\t\tif hasVal {\n\t\t\tj, isOtherIndex := someOtherNumber(i, indices)\n\t\t\tif isOtherIndex {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []int{}\n}", "func twoSum(nums []int, target int) []int {\n\tvar result []int\n\tlength := len(nums)\n\tfor idxI, i := range nums {\n\t\tidxJStart := idxI + 1\n\t\tfor idxJ, j := range nums[idxJStart:length] {\n\t\t\tif i + j == target {\n\t\t\t\tresult = append(result, idxI)\n\t\t\t\tresult = append(result, idxJ + idxJStart)\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func searchRange(nums []int, target int) []int {\n\tans := []int{-1, -1}\n\tif len(nums) == 0 {\n\t\treturn ans\n\t}\n\tfirstHit := -1\n\tlo, hi, mid := 0, len(nums)-1, 0\n\tfor lo <= hi {\n\t\tmid = (lo + hi) >> 1\n\t\tif nums[mid] == target {\n\t\t\tfirstHit = mid\n\t\t\tbreak\n\t\t} else if nums[mid] < target {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid - 1\n\t\t}\n\t}\n\n\tif firstHit == -1 {\n\t\treturn ans\n\t}\n\n\tsearchBoundary := func(l, h, t int) int {\n\t\tmid := 0\n\t\tfor l < h {\n\t\t\tmid = (l + h) >> 1\n\t\t\tif nums[mid] < t {\n\t\t\t\tl = mid + 1\n\t\t\t} else {\n\t\t\t\th = mid\n\t\t\t}\n\t\t}\n\t\treturn l\n\t}\n\n\tans[0] = searchBoundary(lo, firstHit, target)\n\tans[1] = searchBoundary(firstHit, hi+1, target+1) - 1\n\treturn ans\n}", "func getStrictBitSize(src []int32) int {\n\tcounter := [32]int{}\n\tfor _, x := range src {\n\t\tsize := 0\n\t\tfor i := 30; i >= 0; i-- {\n\t\t\tif x&(1<<uint(i)) != 0 {\n\t\t\t\tsize = i + 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tcounter[size] += 1\n\t}\n\n\tsum := 0\n\tfor i, c := range counter {\n\t\tsum += c\n\n\t\t// Check if sum/len >= 0.9.\n\t\tif sum*10 >= len(src)*9 {\n\t\t\treturn i\n\t\t}\n\t}\n\n\t// Impossible to arrive here.\n\treturn 31\n}", "func getLongestConsecutiveIncrease(arr []int) (int, []int) {\n\tvar current, currentStart, currentEnd, saved, savedStart, savedEnd int\n\tvar size = len(arr)\n\n\tfor i := 1; i < size; i++ {\n\t\tif arr[i] > arr[i-1] {\n\t\t\tcurrentEnd = i + 1\n\t\t\tcurrent++\n\t\t} else {\n\t\t\tif current > saved {\n\t\t\t\tsaved = current\n\t\t\t\tsavedStart = currentStart\n\t\t\t\tsavedEnd = currentEnd\n\t\t\t}\n\t\t\tif saved >= (size - i) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrent = 0\n\t\t\tcurrentStart = i\n\t\t\tcurrentEnd = i\n\t\t}\n\t}\n\n\tif current == 0 && saved == 0 {\n\t\treturn 0, []int{}\n\t} else if current > saved {\n\t\treturn current + 1, arr[currentStart:currentEnd]\n\t}\n\n\treturn saved + 1, arr[savedStart:savedEnd]\n}", "func Solution(a []int) int {\n\tmaxGain := 0\n\tminPrice := 0\n\tfor i, price := range a {\n\t\tif i == 0 {\n\t\t\tminPrice = price\n\t\t\tcontinue\n\t\t}\n\n\t\tmaxGain = max(maxGain, price-minPrice)\n\t\tminPrice = min(minPrice, price)\n\t}\n\treturn maxGain\n}", "func d(i, j int, a, b string) int {\n\tmin_v := 100\n\n\tcost := 1\n\tif a[i] == b[j] {\n\t\tcost = 0\n\t}\n\n\tif i == j && j == 0 {\n\t\tmin_v = 0\n\t}\n\tif i > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j, a, b) + 1)\n\t}\n\tif j > 0 {\n\t\tmin_v = min(min_v, d(i, j - 1, a, b) + 1)\n\t}\n\tif i > 0 && j > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j - 1, a, b) + cost)\n\t}\n\tif i > 1 && j > 1 && a[i] == b[j - 1] && a[i - 1] == b[j] {\n\t\tmin_v = min(min_v, d(i - 2, j - 2, a, b) + 1)\n\t}\n\n\treturn min_v\n\n}", "func TestMinimumSwaps(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput []int32\n\t\twant int32\n\t}{\n\t\t{\n\t\t\tname: \"test case #1\",\n\t\t\tinput: []int32{7, 1, 3, 2, 4, 5, 6},\n\t\t\twant: 5,\n\t\t},\n\t\t{\n\t\t\tname: \"test case #2\",\n\t\t\tinput: []int32{2, 3, 4, 1, 5},\n\t\t\twant: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"test case #3\",\n\t\t\tinput: []int32{1, 3, 5, 2, 4, 6, 7},\n\t\t\twant: 3,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := minimumSwaps(tt.input)\n\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func part1(numbers []int, target int) (error, int, int) {\n\tfor _, num1 := range numbers {\n\t\tfor _, num2 := range numbers {\n\t\t\tif num1+num2 == target {\n\t\t\t\treturn nil, num1, num2\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"Could not find pair\"), -1, -1\n}", "func minimumBribes(q []int32) {\n\tvar min int32\n\tminor := make([]int32, 0, len(q))\n\tfor i := 0; i < len(q); i++ {\n\t\toffset := q[i] - int32(i) - 1\n\t\tif offset > 2 {\n\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\treturn\n\t\t} else if offset > 0 {\n\t\t\tmin += offset\n\t\t} else if offset <= 0 {\n\t\t\tminor = append(minor, q[i])\n\t\t\t/*\n\t\t\t\tfor j := i; j < len(q); j++ {\n\t\t\t\t\tif q[j] < q[i] {\n\t\t\t\t\t\tmin++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\tvar curMax int32\n\tmax := make([]int32, len(minor))\n\tfor i := 0; i < len(minor); i++ {\n\t\tif minor[i] > curMax {\n\t\t\tmax[i] = minor[i]\n\t\t\tcurMax = minor[i]\n\t\t} else {\n\t\t\tmax[i] = curMax\n\n\t\t\tback := i - 1\n\t\t\tfor back >= 0 {\n\t\t\t\tif minor[i] < max[i] {\n\t\t\t\t\tif minor[i] < minor[back] {\n\t\t\t\t\t\tmin++\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\tback--\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\tfor i := len(q) - 1; i >= 0; i-- {\n\t\t\toffset := q[i] - int32(i) - 1\n\t\t\toffset1 := int32(i) + 1 - q[i]\n\t\t\tif offset > 2 {\n\t\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\t\treturn\n\t\t\t} else if offset1 >= 0 {\n\t\t\t\tmin += offset1\n\t\t\t\tif offset1 == 0 {\n\t\t\t\t\tmin++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t*/\n\n\tfmt.Println(min)\n}", "func timeAdjust(target int, s []*list.Element, elem *comm.Order) int {\n\tvar obj *list.Element\n\n\t/// When target != 0\n\tfor targetT := target; targetT >= 0 && targetT < len(s); targetT-- {\n\t\tobj = s[targetT]\n\t\tif obj.Value.(comm.Order).Price == elem.Price {\n\t\t\tif obj.Value.(comm.Order).Timestamp <= elem.Timestamp {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\ttarget--\n\t\t\t\t///debug:\n\t\t\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_DEBUG, \"Order(Symbol:%s, ID: %d) TimeAdjust- act: set target to %d\\n\", elem.Symbol, elem.ID, target)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t/// adjust down:\n\t/// When target != 0\n\tfor targetT := target + 1; targetT >= 0 && targetT < len(s); targetT++ {\n\t\tobj = s[targetT]\n\t\tif obj.Value.(comm.Order).Price == elem.Price {\n\t\t\tif obj.Value.(comm.Order).Timestamp >= elem.Timestamp {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\ttarget++\n\t\t\t\t///debug:\n\t\t\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_DEBUG, \"Order(Symbol:%s, ID: %d) TimeAdjust+ act: set target to %d\\n\", elem.Symbol, elem.ID, target)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn target\n}", "func sumSubarrayMins(arr []int) int {\n\tmodBase := 1000000007\n\tsum := 0\n\tsz := len(arr)\n\tstack := util.Stack[int]{}\n\tfor i := 0; i <= sz; i++ {\n\t\tfor evaluateCondition(stack, i, arr) {\n\t\t\tmid, _ := stack.Pop()\n\t\t\tleftBoundry := -1\n\t\t\tif !stack.Empty() {\n\t\t\t\tleftBoundry, _ = stack.Peek()\n\t\t\t}\n\t\t\trightBoundry := i\n\n\t\t\tcount := (mid - leftBoundry) * (rightBoundry - mid) % modBase\n\t\t\tsum += (count * arr[mid]) % modBase\n\t\t\tsum = sum % modBase\n\t\t}\n\t\tstack.Push(i)\n\t}\n\treturn sum\n}", "func genIdxForTest(d, p, survivedN, needReconstN int) ([]int, []int) {\n\tif survivedN < d {\n\t\tsurvivedN = d\n\t}\n\tif needReconstN > p {\n\t\tneedReconstN = p\n\t}\n\tif survivedN+needReconstN > d+p {\n\t\tsurvivedN = d\n\t}\n\n\tneedReconst := randPermK(d+p, needReconstN)\n\n\tsurvived := make([]int, 0, survivedN)\n\n\tfullIdx := make([]int, d+p)\n\tfor i := range fullIdx {\n\t\tfullIdx[i] = i\n\t}\n\trand.Shuffle(d+p, func(i, j int) { // More chance to get balanced survived index\n\t\tfullIdx[i], fullIdx[j] = fullIdx[j], fullIdx[i]\n\t})\n\n\tfor i := 0; i < d+p; i++ {\n\t\tif len(survived) == survivedN {\n\t\t\tbreak\n\t\t}\n\t\tif !isIn(fullIdx[i], needReconst) {\n\t\t\tsurvived = append(survived, fullIdx[i])\n\t\t}\n\t}\n\n\tsort.Ints(survived)\n\tsort.Ints(needReconst)\n\n\treturn survived, needReconst\n}", "func minSubArrayLen(s int, nums []int) int {\n\tleft := 0\n\tflen := 0\n\tlength := 0\n\tvar sum int\n\tfor j := 0; j < len(nums); j++ {\n\t\tsum += nums[j]\n\t\tif sum >= s {\n\t\t\tlength = j + 1\n\t\t}\n\t}\n\n\tfor left <= len(nums) {\n\t\ttmp := 0\n\t\tfor i := left; i < min(left+length, len(nums)); i++ {\n\t\t\ttmp += nums[i]\n\t\t}\n\t\tif tmp >= s {\n\t\t\tflen = length\n\t\t\tlength--\n\t\t\tcontinue\n\t\t}\n\t\tleft++\n\t}\n\n\treturn flen\n}", "func SatisfiesTargetValue(targetValue int64, minChange int64, utxos []*common.UTXO) bool {\n\ttotalValue := int64(0)\n\tfor _, utxo := range utxos {\n\t\ttotalValue += utxo.Value\n\t}\n\n\treturn (totalValue == targetValue || totalValue >= targetValue+minChange)\n}", "func twoSum1(nums []int, target int) []int {\n\thashTable := make(map[int]int)\n\tfor i, x := range nums {\n\t\tif j, ok := hashTable[target-x]; ok {\n\t\t\treturn []int{j, i}\n\t\t}\n\t\thashTable[x] = i\n\t}\n\treturn nil\n}", "func NaiveShift(arr []int) []int {\n\twork := make([]int, len(arr))\n\tcopy(work, arr)\n\n\tfor i := 0; i < len(work); i++ {\n\t\tfmt.Println(work)\n\t\tif work[i] == 0 {\n\t\t\tfor j := i; j < len(work); j++ {\n\t\t\t\tif work[j] != 0 {\n\t\t\t\t\twork[i], work[j] = work[j], work[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn work\n}", "func twoSum(nums []int, target int) (out []int) {\n\tN := len(nums)\n\tfor i, n := range nums {\n\t\tt := target - n\n\t\tfor j := i + 1; j < N; j ++ {\n\t\t\tif nums[j] == t {\n\t\t\t\tout = []int{i, j}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func findMaximumSubArrProduct(src []int) int {\n\treturn -1\n}", "func maxChunksToSorted(arr []int) int {\n\tvar chunkNumber int = 0\n\tvar length int = len(arr)\n\t//DP state\n\t// the last chunk slice, lastChunk[i] means the max number in first i numbers\n\tlastChunk := make([]int, length)\n\t// the next chunk slice,nextChunk[i] means the min number in next i numbers\n\tnextChunk := make([]int, length)\n\t//DP init\n\tlastChunk[0] = arr[0]\n\tnextChunk[length-1] = arr[length-1]\n\t// DP function\n\t// init the lastChunk\n\tfor i := 1; i < length; i++ {\n\t\tlastChunk[i] = max(arr[i], lastChunk[i-1])\n\t}\n\t// init the nextChunk\n\tfor i := length - 2; i >= 0; i-- {\n\t\tnextChunk[i] = min(arr[i], nextChunk[i+1])\n\t}\n\t// result\n\tfor i := 0; i < length-1; i++ {\n\t\tif lastChunk[i] <= nextChunk[i+1] {\n\t\t\tchunkNumber++\n\t\t}\n\t}\n\treturn chunkNumber + 1\n}" ]
[ "0.6181356", "0.5764789", "0.5685976", "0.56609714", "0.5647986", "0.5613157", "0.54398996", "0.5425992", "0.5423529", "0.54122925", "0.5385608", "0.53834355", "0.53657883", "0.5365726", "0.5328744", "0.5317138", "0.5295888", "0.5199396", "0.51928216", "0.5167618", "0.5157009", "0.5130274", "0.50980145", "0.5078243", "0.505936", "0.5021465", "0.4968252", "0.49607527", "0.4960554", "0.49543086", "0.49383786", "0.4848194", "0.48342878", "0.48163897", "0.48123252", "0.47706935", "0.47697145", "0.47654417", "0.47540003", "0.4753776", "0.47406894", "0.47253093", "0.47061664", "0.4704859", "0.47040755", "0.46898654", "0.4671698", "0.46634042", "0.46528476", "0.46437216", "0.46433347", "0.46426138", "0.46332482", "0.4625051", "0.4623429", "0.46209207", "0.45839483", "0.4578431", "0.4575571", "0.45670453", "0.4558655", "0.45415592", "0.4537616", "0.45215306", "0.45183355", "0.45148817", "0.45127356", "0.45055097", "0.44981635", "0.448282", "0.44823143", "0.44739726", "0.44638482", "0.44612035", "0.44576633", "0.4455724", "0.44412005", "0.44403774", "0.44394287", "0.44380406", "0.4428232", "0.44274527", "0.44260588", "0.44223246", "0.4414376", "0.4413592", "0.4412847", "0.44082335", "0.44080037", "0.4405577", "0.44042", "0.43972808", "0.439424", "0.4387559", "0.43795094", "0.43722284", "0.43706623", "0.43654588", "0.43574595", "0.43542096" ]
0.6858109
0
tree[ind]=x where data[x] = min(data[left...right])
func build(tree, data []int, ind, left, right int) { if left == right { tree[ind] = left return } leftSub, rightSub, mid := ind*2+1, ind*2+2, left+(right-left)/2 build(tree, data, leftSub, left, mid) build(tree, data, rightSub, mid+1, right) // merge two sub trees if data[tree[leftSub]] <= data[tree[rightSub]] { // prefer left index if tie tree[ind] = tree[leftSub] } else { tree[ind] = tree[rightSub] } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func query(tree, data []int, ind, left, right, queryLeft, queryRight int) (minInd int) {\n\t// query range is equal to tree range\n\tif left==queryLeft && right==queryRight {\n\t\treturn tree[ind]\n\t}\n\tleftSub, rightSub, mid := ind*2+1, ind*2+2, left+(right-left)/2\n\n\tif queryRight<=mid { // query range in left sub tree\n\t\treturn query(tree, data, leftSub, left, mid, queryLeft, queryRight)\n\t} else if queryLeft>mid { // query range in right sub tree\n\t\treturn query(tree, data, rightSub, mid+1, right, queryLeft, queryRight)\n\t}\n\n\t// else, query in both sub trees\n\tl := query(tree, data, leftSub, left, mid, queryLeft, mid)\n\tr := query(tree, data, rightSub, mid+1, right, mid+1, queryRight)\n\t\n\t// merge result for sub trees\n\tif data[l] <= data[r] { // prefer left index if tie\n\t\treturn l\n\t}\n\treturn r\n}", "func (st *RedBlackBST) min(x *RedBlackBSTNode) *RedBlackBSTNode {\n\tif x.left == nil {\n\t\treturn x\n\t}\n\treturn st.min(x.left)\n}", "func extractMinAdjust(list []int) int {\n\n\t// Creste Min Heap\n\t// listSize/2 -1 are all the non-leaf nodes\n\t// Start with lowest level of non-leaf nodes and their children\n\t// Move smaller values up, push larger values down\n\n\tfor i := CurrentSize/2 - 1; i >= 0; i-- {\n\t\tcreateMinHeap(list, i, CurrentSize)\n\t}\n\n\t// All roots now less than its children, but not yet sorted\n\n\t// Debug\n\t//printMinHeap(list, len(list))\n\n\tmin := list[0]\n\n\t// swap last element (list[CurrentSize-1] and root (list[0])\n\tlist[0] = list[CurrentSize-1]\n\tlist[CurrentSize-1] = min\n\n\t//fmt.Printf(\"last and root swapped\\n\")\n\t//printMinHeap(list, len(list))\n\n\tCurrentSize--\n\n\treturn min\n}", "func MinBST(ns []int, node *TreeNode) *TreeNode {\n\tif len(ns) == 0 {\n\t\treturn nil\n\t}\n\n\tif node == nil {\n\t\tnode = new(TreeNode)\n\t}\n\n\tdata, left, right := splitSlice(ns)\n\tnode.Data = data\n\n\tif len(left) > 0 {\n\t\tnode.Left = new(TreeNode)\n\t\tMinBST(left, node.Left)\n\t}\n\n\tif len(right) > 0 {\n\t\tnode.Right = new(TreeNode)\n\t\tMinBST(right, node.Right)\n\t}\n\n\treturn node\n}", "func FindMin(tree *TreeNode) *TreeNode {\n\tif tree.Left != nil {\n\t\treturn FindMin(tree.Left)\n\t} else {\n\t\treturn tree\n\t}\n}", "func bstRemoveMin(root *bstNode) (newRoot, minNode *bstNode) {\n if root.left == nil {\n newRoot, minNode = root.right, root\n return\n }\n newRoot = root\n root.left, minNode = bstRemoveMin(root.left)\n return\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 (x *Node) findMinimum(sentinelT *Node) *Node {\n\n\tif x.left != sentinelT {\n\n\t\tx = x.left.findMinimum(sentinelT)\n\t}\n\treturn x\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 *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 (t *Tree) RangeMinQuery(left, right int) int {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\treturn (&query{left: left, right: right, nodes: t.nodes}).rangeMinimum(0, 0, t.size-1)\n}", "func (v *VEBTree) low(x int) int {\n\treturn x % v.rootU()\n}", "func chmin(dp [][]int64, idx, dir int, dn int64) {\n\tif dp[idx][dir] > dn {\n\t\tdp[idx][dir] = dn\n\t}\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 FetchMin(t *treeNode) int {\n\tif t.Left == nil {\n\t\treturn t.Value\n\t}\n\treturn FetchMin(t.Left)\n}", "func build(data []*TreeNode, s, e int) *TreeNode {\r\n if s > e {\r\n return nil\r\n }\r\n m := (s + e)/2\r\n u := data[m]\r\n u.Left = build(data, s, m-1)\r\n u.Right = build(data, m+1, e)\r\n return u\r\n}", "func getIndexOfMinChild(list []Comparable, pos int) (int, bool) {\n\tleft, right := getChildIndices(pos)\n\n\t// if indices are both out of range return 0 with false flag\n\tif left >= len(list) && right >= len(list) {\n\t\treturn 0, false\n\t}\n\n\t// left is in range but right is not\n\tif right >= len(list) {\n\t\treturn left, true\n\t}\n\n\t// otherwise return the index of the bigger value\n\tif list[left].GetComparable() < list[right].GetComparable() {\n\t\treturn left, true\n\t} else {\n\t\treturn right, true\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() (node *Node) {\n\tif node = n; node == nil {\n\t\treturn\n\t}\n\n\tfor node.left != nil {\n\t\tnode = node.left\n\t}\n\n\treturn\n}", "func MinimalTree(arr []int) *Node {\n\treturn CreateMinimalBST(arr, 0, len(arr)-1)\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 minDepth(root *TreeNode) int {\n\tif root == nil {\n\t\treturn 0\n\t}\n\tres := 0\n\tqueue := []*TreeNode{root}\n\tfor len(queue) > 0 {\n\t\tsize := len(queue)\n\t\tres++\n\t\t// fmt.Println(queue[0].Val)\n\t\tfor i := 0; i < size; i++ {\n\t\t\t// node := queue[0]\n\t\t\t// queue = queue[1:]\n\t\t\tnode := queue[i]\n\t\t\tif node.Left == nil && node.Right == nil {\n\t\t\t\treturn res\n\t\t\t}\n\t\t\tif node.Left != nil {\n\t\t\t\tqueue = append(queue, node.Left)\n\t\t\t}\n\t\t\tif node.Right != nil {\n\t\t\t\tqueue = append(queue, node.Right)\n\t\t\t}\n\t\t}\n\t\t// ! 一次弹出,提高性能\n\t\tqueue = queue[size:]\n\t}\n\treturn res\n}", "func lowestCommonAncestor1(root, p, q *TreeNode) *TreeNode {\n\tif root == nil {\n\t\treturn nil\n\t}\n\n\tvar stk []*TreeNode\n\tvar parent = make(map[*TreeNode]*TreeNode)\n\n\tstk = append(stk, root)\n\n\tvar gotCnt int\n\tfor gotCnt < 2 && len(stk) != 0 {\n\t\tnode := stk[len(stk)-1]\n\t\tstk = stk[:len(stk)-1]\n\n\t\tif node.Left != nil {\n\t\t\tif node.Left == p || node.Left == q {\n\t\t\t\tgotCnt++\n\t\t\t}\n\t\t\tparent[node.Left] = node\n\t\t\tstk = append(stk, node.Left)\n\t\t}\n\t\tif node.Right != nil {\n\t\t\tif node.Right == p || node.Right == q {\n\t\t\t\tgotCnt++\n\t\t\t}\n\t\t\tparent[node.Right] = node\n\t\t\tstk = append(stk, node.Right)\n\t\t}\n\t}\n\n\t// backtracking process.\n\tvar ancestors = make(map[*TreeNode]bool)\n\tfor p != nil {\n\t\tancestors[p] = true\n\t\tp = parent[p]\n\t}\n\tfor !ancestors[q] {\n\t\tq = parent[q]\n\t}\n\n\treturn q\n}", "func min(d dataSet) int {\n\treturn d[0]\n}", "func (s *stack) calcMin(value interface{}, isPop bool) {\n\tvar valueType interface{}\n\tif s.min != nil {\n\t\tvalueType = s.min.value\n\t} else if value != nil {\n\t\ts.min = &node{\n\t\t\tvalue: value,\n\t\t}\n\t\treturn\n\t} else {\n\t\treturn\n\t}\n\tif isPop && value == s.min.value {\n\t\ts.min = s.min.prev\n\t\treturn\n\t}\n\tswitch valueType.(type) {\n\tcase int:\n\t\tif value.(int) <= s.min.value.(int) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase int8:\n\t\tif value.(int8) <= s.min.value.(int8) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase int16:\n\t\tif value.(int16) <= s.min.value.(int16) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase int32:\n\t\tif value.(int32) <= s.min.value.(int32) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase int64:\n\t\tif value.(int64) <= s.min.value.(int64) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase float32:\n\t\tif value.(float32) <= s.min.value.(float32) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tcase float64:\n\t\tif value.(float64) <= s.min.value.(float64) {\n\t\t\ts.pushMin(value)\n\t\t}\n\tdefault:\n\t\treturn\n\t}\n\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 (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 FindMinOptimalSubset(tree Tree, bound int) (float64, []*Node) {\n\tn := tree.UpdateSizes()\n\tdp := make([][]float64, n+1)\n\tpred := make([][]bool, n+1)\n\tfor i := 0; i <= n; i++ {\n\t\tdp[i] = make([]float64, bound+1)\n\t\tpred[i] = make([]bool, bound+1)\n\t\tfor j := 0; j < len(dp[i]); j++ {\n\t\t\tdp[i][j] = 1\n\t\t}\n\t}\n\n\ti := 1\n\tnodesInOrder := []*Node{nil}\n\tvar buildDP func(*Node)\n\tbuildDP = func(node *Node) {\n\t\tfor _, child := range node.Children {\n\t\t\tbuildDP(child)\n\t\t}\n\n\t\tfor w := 0; w <= bound; w++ {\n\t\t\tif w - node.Weight >= 0 && node.Profit * dp[i-1][w-node.Weight] < dp[i-node.Size][w] {\n\t\t\t\tpred[i][w] = true\n\t\t\t\tdp[i][w] = node.Profit * dp[i-1][w-node.Weight]\n\t\t\t} else {\n\t\t\t\tpred[i][w] = false\n\t\t\t\tdp[i][w] = dp[i-node.Size][w]\n\t\t\t}\n\t\t}\n\n\t\tnodesInOrder = append(nodesInOrder, node)\n\t\ti++\n\t}\n\tbuildDP(tree.Root)\n\n\toptimalSubset := []*Node{}\n\ti = n\n\tw := bound\n\tfor i > 0 {\n\t\tcurrentNode := nodesInOrder[i]\n\t\tif pred[i][w] == true {\n\t\t\toptimalSubset = append(optimalSubset, currentNode)\n\t\t\tw -= currentNode.Weight\n\t\t\ti--;\n\t\t} else {\n\t\t\ti -= currentNode.Size;\n\t\t}\n\t}\n\n\treturn dp[n][bound], optimalSubset\n}", "func (root *binNode) insert(inData int) {\n\tnewNode := &binNode{data: inData, left: nil, right: nil}\n\tnode := root\n\tfor {\n\t\tif node.data > inData {\n\t\t\tif node.left == nil {\n\t\t\t\tnode.left = newNode\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnode = node.left\n\t\t} else {\n\t\t\tif node.right == nil {\n\t\t\t\tnode.right = newNode\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnode = node.right\n\t\t}\n\t}\n}", "func minTreeLazyInsert(t *MinTree, word string) {\n\tnode := t.Root\n\tfor _, r := range word {\n\t\tif child, ok := node.Edges[r]; ok {\n\t\t\tnode = child\n\t\t} else {\n\t\t\tnode.Edges[r] = &MinTreeNode{\n\t\t\t\tEdges: make(map[rune]*MinTreeNode),\n\t\t\t}\n\t\t\tnode = node.Edges[r]\n\t\t}\n\t}\n\tnode.Final = true\n}", "func InsertLevelOrder(arr [][]int32, node *Node, index int) *Node {\n\n\t// Check if arr slice is not empty\n\tif len(arr) == 0 || node == nil {\n\n\t\t// If empty return nil value\n\t\treturn nil\n\t}\n\n\t// arrInteger is an array converted tree with the root value of 1\n\tarrInteger := []int32{1}\n\n\t// Populate the arrInteger\n\tfor _, val := range arr {\n\t\tfor _, el := range val {\n\t\t\tarrInteger = append(arrInteger, el)\n\t\t}\n\t}\n\n\t// Create the queue for node\n\t// Queue is a First In First Out\n\ttreeNodeQueue := []*Node{}\n\n\t// Create queue for node value\n\tintegerQueue := arrInteger[1:]\n\n\t// For the root node\n\t// Its value is always on arrInteger[0]\n\tnode.Value = arrInteger[0]\n\n\t// Insert the root node to the node queue\n\ttreeNodeQueue = append(treeNodeQueue, node)\n\n\t// Loop this logic as long as minimum there is a node\n\t// waiting in the node queue\n\tfor len(treeNodeQueue) > 0 {\n\n\t\t// Initializing value for left and right child\n\t\t// -1 is a replacement value for nil\n\t\tleftVal := int32(-1)\n\t\trightVal := int32(-1)\n\n\t\t// If the node value queue have a queue\n\t\t// Then assign the first value to the value for left node\n\t\tif len(integerQueue) > 0 {\n\t\t\tleftVal = integerQueue[0]\n\n\t\t\t// After assigning the first value to the left value\n\t\t\t// for the left node, pops that value out of the queue\n\t\t\tintegerQueue = integerQueue[1:]\n\t\t}\n\n\t\t// After assign the left value for the left node\n\t\t// If it still have a queue waiting to assigned\n\t\t// Assign the first value to the right value\n\t\t// For the right node\n\t\tif len(integerQueue) > 0 {\n\t\t\trightVal = integerQueue[0]\n\n\t\t\t// After assigning the first value to the right value\n\t\t\t// for the right node, pops that value out of the queue\n\t\t\tintegerQueue = integerQueue[1:]\n\t\t}\n\n\t\t// Assign the first node in the queue\n\t\tcurrentNode := treeNodeQueue[0]\n\n\t\t// After assign the first node\n\t\t// Pops that node out of the queue\n\t\ttreeNodeQueue = treeNodeQueue[1:]\n\n\t\t// If leftVal is not nil\n\t\t// -1 is a replacement value for nil\n\t\tif leftVal != -1 {\n\n\t\t\t// Create new node for the left node\n\t\t\tnodeLeft := new(Node)\n\n\t\t\t// Assign its value\n\t\t\tnodeLeft.Value = leftVal\n\n\t\t\t// Assign the left node to current node\n\t\t\tcurrentNode.Left = nodeLeft\n\n\t\t\t// And append the newly created node\n\t\t\t// Left node to the node queue for assigning its child\n\t\t\ttreeNodeQueue = append(treeNodeQueue, nodeLeft)\n\t\t}\n\n\t\t// If rightVal is not nil\n\t\t// -1 is a replacement value for nil\n\t\tif rightVal != -1 {\n\n\t\t\t// Create new node for the left node\n\t\t\tnodeRight := new(Node)\n\n\t\t\t// Assign its value\n\t\t\tnodeRight.Value = rightVal\n\n\t\t\t// Assign the right node to current node\n\t\t\tcurrentNode.Right = nodeRight\n\n\t\t\t// And append the newly created node\n\t\t\t// Right node to the node queue for assigning its child\n\t\t\ttreeNodeQueue = append(treeNodeQueue, nodeRight)\n\t\t}\n\t}\n\n\treturn node\n}", "func minHeapify(array []int, i int) {\n\tsmallest := i\n\n\tl := left(i)\n\tr := right(i)\n\n\tif l < len(array) && array[l] < array[i] {\n\t\tsmallest = l\n\t}\n\n\tif r < len(array) && array[r] < array[smallest] {\n\t\tsmallest = r\n\t}\n\n\tif i != smallest {\n\t\tarray[i], array[smallest] = array[smallest], array[i]\n\t\tminHeapify(array, smallest)\n\t}\n}", "func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {\n\tif root == nil || root == p || root == q {\n\t\treturn root\n\t}\n\tleft, right := lowestCommonAncestor(root.Left, p, q), lowestCommonAncestor(root.Right, p, q)\n\tswitch {\n\tcase left == nil:\n\t\t{\n\t\t\treturn right\n\t\t}\n\tcase right == nil:\n\t\t{\n\t\t\treturn left\n\t\t}\n\tcase left != nil && right != nil:\n\t\t{\n\t\t\treturn root\n\t\t}\n\tdefault:\n\t\treturn root\n\t}\n}", "func insert(node *TreeNode, value int) *TreeNode {\n\n\tif node == nil {\n\t\tnode = new(TreeNode)\n\t\tnode.data = value\n\t} else {\n\t\tif value < node.data {\n\t\t\tnode.left = insert(node.left, value)\n\t\t} else {\n\t\t\tnode.right = insert(node.right, value)\n\t\t}\n\t}\n\n\treturn node\n}", "func (n *nodeHeader) lowerBound(c byte) *nodeHeader {\n\tswitch n.typ {\n\tcase typLeaf:\n\t\t// Leaves have no children\n\t\treturn nil\n\n\tcase typNode4:\n\t\treturn n.node4().lowerBound(c)\n\n\tcase typNode16:\n\t\treturn n.node16().lowerBound(c)\n\n\tcase typNode48:\n\t\treturn n.node48().lowerBound(c)\n\n\tcase typNode256:\n\t\treturn n.node256().lowerBound(c)\n\t}\n\tpanic(\"invalid type\")\n}", "func min(dataSlice []float64) float64 {\n\tmin := dataSlice[0]\n\tfor _, j := range dataSlice {\n\t\tif j < min {\n\t\t\tmin = j\n\t\t}\n\t}\n\treturn min\n}", "func lowestCommonAncestor1676(root *TreeNode, nodes []*TreeNode) *TreeNode {\n\tnodeSet := make(map[*TreeNode]bool)\n\tfor _, node := range nodes {\n\t\tnodeSet[node] = true\n\t}\n\treturn lca1676(root, nodeSet)\n}", "func findSecondMinimumValue(root *TreeNode) int {\n\tif root == nil || root.Left == nil || root.Right == nil {\n\t\treturn -1\n\t}\n\n\t// 1\n\t// / \\\n\t// 1 3\n\t// / \\ / \\\n\t// 1 1 3 4\n\t// / \\ / \\ / \\ / \\\n\t// 3 1 1 1 3 8 4 8\n\t// / \\ / \\ / \\\n\t// 3 3 1 6 2 1\n\t// 在遇到上述 case 时, 下面的 if 就会导致结果错误\n\t//if root.Val == root.Left.Val && root.Val == root.Right.Val {\n\t//\treturn -1\n\t//}\n\n\tlsv, rsv := root.Left.Val, root.Right.Val\n\t// 根值和左子树根值相等,第二小的值有可能在左子树里\n\t// 所以需要找出左子树的第二小值,和右子树的根值作比较\n\tif root.Val == root.Left.Val {\n\t\tlsv = findSecondMinimumValue(root.Left)\n\t}\n\t// 根值和右子树根值相等\n\tif root.Val == root.Right.Val {\n\t\trsv = findSecondMinimumValue(root.Right)\n\t}\n\tif lsv != -1 && rsv != -1 {\n\t\tif lsv < rsv {\n\t\t\treturn lsv\n\t\t}\n\t\treturn rsv\n\t}\n\t// 如果代码能到这一行,说明 lsv 和 rsv 两者有一个为-1或者两者都为-1\n\tif lsv != -1 {\n\t\treturn lsv\n\t}\n\treturn rsv\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 min(n *node) Item {\n\tif n == nil {\n\t\treturn nil\n\t}\n\tfor len(n.children) > 0 {\n\t\tn = n.children[0]\n\t}\n\tif len(n.items) == 0 {\n\t\treturn nil\n\t}\n\treturn n.items[0]\n}", "func (s *stack) pushMin(value interface{}) {\n\tif s.min == nil {\n\t\ts.min = &node{value, nil}\n\t} else {\n\t\tnode := &node{\n\t\t\tvalue: value,\n\t\t\tprev: s.min,\n\t\t}\n\t\ts.min = node\n\t}\n}", "func (tree *Tree) naiveInsert(value interface{}) *Node {\n\tvar inserted *Node\n\n\troot := tree.Root\n\tif root == nil {\n\t\tinserted = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority)}\n\t\ttree.Root = inserted\n\t}\n\n\tfor inserted == nil {\n\t\tif compare(value, root.Value) < 0 {\n\t\t\tif root.Left == nil {\n\t\t\t\troot.Left = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority), Parent: root}\n\t\t\t\tinserted = root.Left\n\t\t\t} else {\n\t\t\t\troot = root.Left\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Duplicate values placed on the right\n\t\t\tif root.Right == nil {\n\t\t\t\troot.Right = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority), Parent: root}\n\t\t\t\tinserted = root.Right\n\t\t\t} else {\n\t\t\t\troot = root.Right\n\t\t\t}\n\t\t}\n\t}\n\treturn inserted\n}", "func (x *biggerIntPair) lowerMin(y biggerInt) {\n\tif x[0].extra > 0 || y.extra < 0 ||\n\t\t(x[0].extra == 0 && y.extra == 0 && x[0].i.Cmp(y.i) > 0) {\n\t\tx[0] = y\n\t}\n}", "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 (v *VEBTree) Minimum() int {\n\treturn v.min\n}", "func (heap *Heap) ExtractMin() (Comparable, bool) {\n\tif heap.root == nil {\n\t\treturn nil, false\n\t}\n\n\tmin := heap.root.value\n\troots := [64]*FHNode{}\n\tfor node := heap.root.next; node != heap.root; {\n\t\tnextNode := node.next\n\t\theap.addToRoots(node, &roots)\n\t\tnode = nextNode\n\t}\n\tif child := heap.root.child; child != nil {\n\t\tchild.parent = nil\n\t\tnode := child.next\n\t\theap.addToRoots(child, &roots)\n\n\t\tfor node != child {\n\t\t\tnextNode := node.next\n\t\t\tnode.parent = nil\n\t\t\theap.addToRoots(node, &roots)\n\t\t\tnode = nextNode\n\t\t}\n\t}\n\tvar newRoot *FHNode\n\tvar degree int\n\n\tfor degree, newRoot = range roots {\n\t\tif newRoot == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tbreak\n\t}\n\n\tif newRoot == nil {\n\t\theap.root = nil\n\t\theap.size--\n\n\t\treturn min, true\n\t}\n\n\troots[degree] = nil\n\tnewRoot.next = newRoot\n\tnewRoot.prev = newRoot\n\n\tfor _, node := range roots {\n\t\tif node == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnode.prev = newRoot\n\t\tnode.next = newRoot.next\n\t\tnewRoot.next.prev = node\n\t\tnewRoot.next = node\n\t\tif node.value.LessThen(newRoot.value) {\n\t\t\tnewRoot = node\n\t\t}\n\t}\n\theap.root = newRoot\n\theap.size--\n\n\treturn min, true\n}", "func (treeNode *TreeNode) FindMin() int {\n\tif treeNode.left == nil {\n\t\treturn treeNode.value\n\t}\n\n\treturn treeNode.left.FindMin()\n}", "func insertIntoBST(root *TreeNode, val int) *TreeNode {\n\tif root == nil {\n\t\treturn &TreeNode{Val: val}\n\t}\n\n\t// 找到比val应该插入的节点\n\tcur := root\n\tvar last *TreeNode\n\tfor cur != nil {\n\t\tlast = cur\n\t\tif cur.Val > val {\n\t\t\tcur = cur.Left\n\t\t} else {\n\t\t\tcur = cur.Right\n\t\t}\n\t}\n\n\tif last != nil {\n\t\tif last.Val > val {\n\t\t\tlast.Left = &TreeNode{Val: val}\n\t\t} else {\n\t\t\tlast.Right = &TreeNode{Val: val}\n\t\t}\n\t}\n\n\treturn root\n}", "func (v *nodes) insert(ele int) {\r\n\tif len(v.n) == 0 {\r\n\t\tv.n = append(v.n, node{ele, -1, -1, -1, 0})\r\n\t\treturn\r\n\t}\r\n\ti := 0\r\n\tfor true {\r\n\t\tif ele <= v.n[i].value {\r\n\t\t\tif v.n[i].left < 0 {\r\n\t\t\t\tv.n = append(v.n, node{ele, i, -1, -1, 0})\r\n\t\t\t\tv.n[i].left = len(v.n)-1\r\n\t\t\t\tbreak\r\n\t\t\t} else {\r\n\t\t\t\ti = v.n[i].left\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif v.n[i].right < 0 {\r\n\t\t\t\tv.n = append(v.n, node{ele, i, -1, -1, 0})\r\n\t\t\t\tv.n[i].right = len(v.n)-1\r\n\t\t\t\tbreak\r\n\t\t\t} else {\r\n\t\t\t\ti = v.n[i].right\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}", "func (t *treeNode) Insert(data int) {\n\tif t == nil {\n\t\tt = &treeNode{Value: data}\n\t\treturn\n\t}\n\tif data == t.Value {\n\t\tfmt.Println(\"Node already exists\")\n\t\treturn\n\t}\n\tif data < t.Value {\n\t\tif t.Left == nil {\n\t\t\tt.Left = &treeNode{Value: data}\n\t\t\treturn\n\t\t}\n\t\tt.Left.Insert(data)\n\t\treturn\n\t}\n\tif data > t.Value {\n\t\tif t.Right == nil {\n\t\t\tt.Right = &treeNode{Value: data}\n\t\t\treturn\n\t\t}\n\t\tt.Right.Insert(data)\n\t}\n}", "func (m *Memtable) findGreaterOrEqual(key string, timestamp int64, prev []*node) *node {\n\tc := m.head\n\tvar nextAtLevel *node\n\n\tfor cl := maxLevel - 1; cl >= 0; cl-- {\n\t\tnextAtLevel = c.atomicLoadNext(cl)\n\t\tfor nextAtLevel != nil &&\n\t\t\t(nextAtLevel.key < key || (nextAtLevel.key == key && nextAtLevel.timestamp > timestamp)) {\n\t\t\tc = nextAtLevel\n\t\t\tnextAtLevel = c.atomicLoadNext(cl)\n\t\t}\n\n\t\tif prev != nil {\n\t\t\tprev[cl] = c\n\t\t}\n\t}\n\n\treturn nextAtLevel\n}", "func llrbRemoveMin(root *llrbNode) *llrbNode {\n if root.left == nil {\n return nil\n }\n if (!llrbIsRed(root.left)) && (!llrbIsRed(root.left.left)) {\n root = llrbMoveRedLeft(root)\n }\n root.left = llrbRemoveMin(root.left)\n return llrbFixUp(root)\n}", "func insert(root *Node, data int) *Node{\n\t//if the tree has not been created yet, insert in to root.\n\tif root == nil {\n\t\troot = &Node{data, nil, nil}\n\t\treturn root\n\t} \n\n\t//if the data is less than the data contained in the root\n\t//recursivly insert into the left node.\n\tif data < root.Data {\n\t\troot.Left = insert(root.Left, data)\n\t} \n\n\t//if the data is greater than the data contained in the root,\n\t//recursivly insert into the right node\n\tif data > root.Data {\n\t\troot.Right = insert(root.Right, data)\n\t}\n\treturn root\n}", "func reconstructBSTFromTraversalData(ints ...int) *binaryTree {\n\n\tif len(ints) == 0 {\n\t\treturn nil\n\t}\n\tif len(ints) == 1 {\n\t\treturn &binaryTree{ints[0], \"\", nil, nil, nil}\n\t}\n\tif len(ints) == 2 && ints[0] > ints[1] {\n\t\tleft := &binaryTree{ints[1], \"\", nil, nil, nil}\n\t\troot := &binaryTree{ints[0], \"\", nil, left, nil}\n\t\treturn root\n\t}\n\tif len(ints) == 2 && ints[0] < ints[1] {\n\t\tright := &binaryTree{ints[1], \"\", nil, nil, nil}\n\t\troot := &binaryTree{ints[0], \"\", nil, nil, right}\n\t\treturn root\n\t}\n\n\trootData := ints[0]\n\troot := &binaryTree{rootData, \"\", nil, nil, nil}\n\tleftSubtree := []int{}\n\trightSubtree := []int{}\n\tlr := ints[1:]\n\tfor _, val := range lr {\n\t\tif val < rootData {\n\t\t\tleftSubtree = append(leftSubtree, val)\n\t\t} else {\n\t\t\trightSubtree = append(rightSubtree, val)\n\t\t}\n\t}\n\troot.left = reconstructBSTFromTraversalData(leftSubtree...)\n\troot.right = reconstructBSTFromTraversalData(rightSubtree...)\n\n\treturn root\n}", "func (t *fixedTree) insert(c rbtree.Comparable) {\n\tmin := t.tree.Minimum()\n\tif t.tree.Len() < int64(t.size) || min.Key().LessThan(c) {\n\t\tif t.tree.Len() == int64(t.size) {\n\t\t\tt.tree.DeleteNode(min.Key())\n\t\t}\n\n\t\tt.tree.Insert(c)\n\t}\n}", "func bstRemoveThis(root *bstNode) *bstNode {\n switch {\n case root.left == nil:\n return root.right\n case root.right == nil:\n return root.left\n }\n newRight, newRoot := bstRemoveMin(root.right)\n newRoot.left = root.left\n newRoot.right = newRight\n return newRoot\n}", "func (s *SGTree) build(treeindex, l, r int) {\n\tif l == r {\n\t\ts.tree[treeindex] = s.data[l]\n\t\treturn\n\t}\n\tleftTreeIndex := s.leftChild(treeindex)\n\trightTreeIndex := s.rightChild(treeindex)\n\t//mid = (l + r )/ 2 notice: it's easy to core dump while hug int l and r so we do s:\n\tmid := l + (r-l)/2\n\t//recursive\n\ts.build(leftTreeIndex, l, mid)\n\ts.build(rightTreeIndex, mid+1, r)\n\ts.tree[treeindex] = s.merger(s.tree[leftTreeIndex], s.tree[rightTreeIndex])\n}", "func (inT *INTree) buildTree(bnds []Bounds) {\n\n\tinT.idxs = make([]int, len(bnds))\n\tinT.lmts = make([]float64, 3*len(bnds))\n\n\tfor i, v := range bnds {\n\n\t\tinT.idxs[i] = i\n\t\tl, u := v.Limits()\n\n\t\tinT.lmts[3*i] = l\n\t\tinT.lmts[3*i+1] = u\n\t\tinT.lmts[3*i+2] = 0\n\n\t}\n\n\tsort(inT.lmts, inT.idxs)\n\taugment(inT.lmts, inT.idxs)\n\n}", "func (t *RedBlackTree) Min() *Node {\n\treturn t.root.Min()\n}", "func TestBuildTree(t *testing.T) {\n\tpreOrder := []int{3, 9, 20, 15, 7}\n\tinOrder := []int{9, 3, 15, 20, 7}\n\tn3 := buildTree(preOrder, inOrder)\n\tassert.Equal(t, 3, n3.Val)\n\tn9 := n3.Left\n\tn20 := n3.Right\n\tassert.NotNil(t, n9)\n\tassert.NotNil(t, n20)\n\tassert.Equal(t, 9, n9.Val)\n\tassert.Equal(t, 20, n20.Val)\n\tn15 := n20.Left\n\tn7 := n20.Right\n\tassert.NotNil(t, n15)\n\tassert.NotNil(t, n7)\n\tassert.Equal(t, 15, n15.Val)\n\tassert.Equal(t, 7, n7.Val)\n}", "func MergeMin(vals []uint64) uint64 {\n\trv := vals[0]\n\tfor _, v := range vals[1:] {\n\t\tif v < rv {\n\t\t\trv = v\n\t\t}\n\t}\n\treturn rv\n}", "func adjustTree(t *TreeNode) *TreeNode {\n\tif t.Left == nil {\n\t\treturn t.Right\n\t}\n\n\tif t.Right == nil {\n\t\treturn t.Left\n\t}\n\n\t// This is the hard part, you need to find the correct node to replace the\n\t// head with. At his point we know that the neither the left nor right\n\t// children are nil\n\troot := t.Left // you have to assign this because you need to return root\n\tcur := root\n\n\t// Go to the furthest right child under the original left child we looked at\n\tfor cur.Right != nil {\n\t\tcur = cur.Right\n\t}\n\n\t// After we reach the right most node, assign the right child of this node\n\t// to be the right child of the root node of this subtree\n\tcur.Right = t.Right\n\n\treturn root\n}", "func (t *KDTree) build(l []XY, level int) *kdNode {\n\tif len(l) == 0 {\n\t\treturn nil\n\t}\n\n\tnode := new(kdNode)\n\tif level%2 == 0 {\n\t\tnode.cmp = t.compare.CompareX\n\t} else {\n\t\tnode.cmp = t.compare.CompareY\n\t}\n\n\tif len(l) == 1 {\n\t\tnode.val = l[0]\n\t\treturn node\n\t}\n\n\t// Find median of current list, set that to val of current node\n\t// Recursively apply the same on left and right point set\n\tsl := XYSlice(l)\n\tm := len(l) / 2\n\tSelectK(sl, m, node.cmp)\n\n\tfor m < sl.Len()-1 && node.cmp(sl.At(m-1), sl.At(m)) == 0 {\n\t\tm += 1\n\t}\n\n\tnode.val = sl.At(m - 1).(XY)\n\tnode.left = t.build(l[:m-1], level+1)\n\tnode.right = t.build(l[m:], level+1)\n\n\treturn node\n}", "func sortMinStackElement(el int, s stack) stack {\n\tif s.isEmpty() {\n\t\ts.push(el)\n\t\treturn s\n\t}\n\tpeek, _ := s.peek()\n\tif el > peek {\n\t\tnext, _ := s.pop()\n\t\ts = sortMinStackElement(el, s)\n\t\ts.push(next)\n\t} else {\n\t\ts.push(el)\n\t}\n\n\treturn s\n}", "func (tree *Tree) insert( m int) {\nif tree != nil {\nif tree.LeftNode == nil {\ntree.LeftNode = &Tree{nil,m,nil}\n} else {\nif tree.RightNode == nil {\ntree.RightNode = &Tree{nil,m,nil}\n} else {\nif tree.LeftNode != nil {\ntree.LeftNode.insert(m)\n} else {\ntree.RightNode.insert(m)\n}\n}\n}\n} else {\ntree = &Tree{nil,m,nil}\n}\n}", "func insert(n *Node, data int) {\n\tif n.value > data {\n\t\tif n.left != nil {\n\t\t\tinsert(n.left, data)\n\t\t} else {\n\t\t\tn.left = &Node{\n\t\t\t\tvalue: data,\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif n.right != nil {\n\t\t\tinsert(n.right, data)\n\t\t} else {\n\t\t\tn.right = &Node{\n\t\t\t\tvalue: data,\n\t\t\t}\n\t\t}\n\t}\n}", "func (t *Tree) Insert(low, high int64, data interface{}) {\n\tinserted_node := new_node(low, high, data, RED, nil, nil)\n\tif t.root == nil {\n\t\tt.root = inserted_node\n\t} else {\n\t\tn := t.root\n\t\tfor {\n\t\t\t// update 'm' for each node traversed from root\n\t\t\tif inserted_node.m > n.m {\n\t\t\t\tn.m = inserted_node.m\n\t\t\t}\n\n\t\t\t// find a proper position\n\t\t\tif low < n.low {\n\t\t\t\tif n.left == nil {\n\t\t\t\t\tn.left = inserted_node\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tn = n.left\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif n.right == nil {\n\t\t\t\t\tn.right = inserted_node\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tn = n.right\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinserted_node.parent = n\n\t}\n\n\tt.insert_case1(inserted_node)\n}", "func (treeNode *TreeNode) Insert(son1 *TreeNode, son2 *TreeNode) *TreeNode {\n\tvar root *TreeNode\n\tvar item Item\n\n\titem.Symbol = 0\n\titem.Weight = son1.Value.Weight + son2.Value.Weight\n\troot, _ = root.New(item)\n\n\t//This condition may be avoided if the heap is well managed.\n\tif son1.Value.Weight < son2.Value.Weight {\n\t\troot.Left = son1\n\t\troot.Right = son2\n\t} else {\n\t\troot.Left = son2\n\t\troot.Right = son1\n\t}\n\n\treturn root\n}", "func (rt *RTree) chooseSubtree(r *Rectangle, height int) *node {\n\tn := rt.root //CS1\n\tfor !n.isLeaf() && n.height > height { //CS2\t\tn.height gets lower for every iteration\n\t\tbestChild := n.entries[0]\n\t\tpointsToLeaves := false\n\t\tif n.height == 1 {\n\t\t\tpointsToLeaves = true\n\t\t}\n\t\tvar bestDifference float64 //must be reset for each node n\n\t\tif pointsToLeaves {\n\t\t\tbestDifference = bestChild.overlapChangeWith(r)\n\t\t} else {\n\t\t\tbestDifference = bestChild.mbr.AreaDifference(bestChild.mbr.MBRWith(r))\n\t\t}\n\t\tfor i := 1; i < len(n.entries); i++ {\n\t\t\te := n.entries[i]\n\t\t\tif pointsToLeaves { //childpointer points to leaves -> [Determine the minimum overlap cost]\n\t\t\t\toverlapDifference := e.overlapChangeWith(r)\n\t\t\t\tif overlapDifference <= bestDifference {\n\t\t\t\t\tif overlapDifference < bestDifference { //strictly smaller\n\t\t\t\t\t\tbestDifference = overlapDifference\n\t\t\t\t\t\tbestChild = e //CS3 set new bestChild, repeat from CS2\n\t\t\t\t\t} else { //tie -> choose the entry whose rectangle needs least area enlargement\n\t\t\t\t\t\te_new := e.mbr.MBRWith(r).AreaDifference(e.mbr)\n\t\t\t\t\t\te_old := bestChild.mbr.MBRWith(r).AreaDifference(bestChild.mbr)\n\t\t\t\t\t\tif e_new < e_old {\n\t\t\t\t\t\t\tbestDifference = overlapDifference\n\t\t\t\t\t\t\tbestChild = e //CS3 set new bestChild, repeat from CS2\n\t\t\t\t\t\t} else if e.mbr.Area() < bestChild.mbr.Area() { //if tie again: -> choose the entry with the smallest MBR\n\t\t\t\t\t\t\tbestDifference = overlapDifference\n\t\t\t\t\t\t\tbestChild = e //CS3 set new bestChild, repeat from CS2\n\t\t\t\t\t\t} //else the bestChild is kept\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else { //childpointer do not point to leaves -> choose the child-node whose rectangle needs least enlargement to include r\n\t\t\t\tnewMBR := e.mbr.MBRWith(r)\n\t\t\t\tareaDifference := e.mbr.AreaDifference(newMBR)\n\t\t\t\tif areaDifference <= bestDifference { //we have a new best (or a tie)\n\t\t\t\t\tif areaDifference < bestDifference {\n\t\t\t\t\t\tbestDifference = areaDifference //CS3 set new bestChild, repeat from CS2\n\t\t\t\t\t\tbestChild = e\n\t\t\t\t\t} else if e.mbr.Area() < bestChild.mbr.Area() { // change in MBR is a tie -> keep the rectangle with the smallest area\n\t\t\t\t\t\tbestDifference = areaDifference //CS3 set new bestChild, repeat from CS2\n\t\t\t\t\t\tbestChild = e\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tn = bestChild.child\n\t}\n\treturn n\n}", "func remove(node *Node, key int) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif key < node.key {\n\t\tnode.left = remove(node.left, key)\n\t\treturn node\n\t}\n\tif key > node.key {\n\t\tnode.right = remove(node.right, key)\n\t\treturn node\n\t}\n\t// key == node.key\n\tif node.left == nil && node.right == nil {\n\t\tnode = nil\n\t\treturn nil\n\t}\n\tif node.left == nil {\n\t\tnode = node.right\n\t\treturn node\n\t}\n\tif node.right == nil {\n\t\tnode = node.left\n\t\treturn node\n\t}\n\tleftmostrightside := node.right\n\tfor {\n\t\t//find smallest value on the right side\n\t\tif leftmostrightside != nil && leftmostrightside.left != nil {\n\t\t\tleftmostrightside = leftmostrightside.left\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tnode.key, node.value = leftmostrightside.key, leftmostrightside.value\n\tnode.right = remove(node.right, node.key)\n\treturn node\n}", "func (d *ImplData) MergeMinLevel(min Level) {\n\tif d.MinLevel < min {\n\t\td.MinLevel = min\n\t}\n}", "func (bts *binarySearchTree) insert(v int) {\n\tn := &node{\n\t\tvalue: v,\n\t\tleft: nil,\n\t\tright: nil,\n\t}\n\tif bts.root == nil {\n\t\tbts.root = n\n\t\treturn\n\t}\n\n\tcurrent := bts.root\n\tfor {\n\t\tif v > current.value {\n\t\t\tif current.right == nil {\n\t\t\t\tcurrent.right = n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcurrent = current.right\n\t\t} else if v < current.value {\n\t\t\tif current.left == nil {\n\t\t\t\tcurrent.left = n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcurrent = current.left\n\t\t} else {\n\t\t\tfmt.Println(\"The value already existed in the BTS.\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (v *VEBTree) Insert(x int) {\n\tif v.min == v.null {\n\t\tv.emptyTreeInsert(x)\n\t\treturn\n\t}\n\n\tif x < v.min {\n\t\t// x is the new min; we now have to place the old min into a cluster\n\t\tv.min, x = x, v.min\n\t}\n\n\tif v.u > 2 {\n\t\t// recursive case\n\t\tclusterForX := v.cluster[v.high(x)]\n\t\tif clusterForX.Minimum() == v.null {\n\t\t\t// if the cluster that would contain x is empty,\n\t\t\t// add it to the empty tree, and add it to the top tree's summary as well\n\t\t\tv.summary.Insert(v.high(x))\n\t\t\tclusterForX.emptyTreeInsert(v.low(x))\n\t\t} else {\n\t\t\tclusterForX.Insert(v.low(x))\n\t\t}\n\t}\n\n\tif x > v.max {\n\t\tv.max = x\n\t}\n}", "func (g *Graph) PrimMinimumSpanningTree(sourceVertex int) (mst SpanningTree) {\n\tconst infDist = math.MaxInt64\n\n\tmst.PredecessorMap = make(map[int]int)\n\tmst.DistanceMap = make(map[int]int)\n\n\t// Initialize distances from sourceVertex\n\tdistArr := make([]int, g.VertexCount())\n\tfor vertex := range distArr {\n\t\tdistArr[vertex] = infDist\n\t}\n\tdistArr[sourceVertex] = 0\n\n\t// Add all vertices to the unvisited heap/set.\n\tunvisited := newVertexHeap()\n\tfor vertex := range g.adjList {\n\t\tunvisited.PushVertex(vertex, distArr[vertex])\n\t}\n\n\t// Pop the nearest vertex from the heap untill all are visited.\n\tfor unvisited.Len() > 0 {\n\t\tvertex := unvisited.PopVertex()\n\t\tfor _, edge := range g.adjList[vertex] {\n\t\t\tedgeWeight := g.edgesWeights[edge.ID]\n\n\t\t\t// If src is infinity away than no route is know to src from start.\n\t\t\t// Should not happen in connected graph, vut might happen\n\t\t\t// in disconnecte one.\n\t\t\tif distArr[edge.Src] != infDist && edgeWeight < distArr[edge.Dst] &&\n\t\t\t\tunvisited.Contains(edge.Dst) {\n\t\t\t\tdistArr[edge.Dst] = edgeWeight\n\t\t\t\tunvisited.UpdateVertex(edge.Dst, edgeWeight)\n\t\t\t\tmst.PredecessorMap[edge.Dst] = edge.Src\n\t\t\t\tmst.DistanceMap[edge.Dst] = edgeWeight\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (s SGTree) leftChild(treeIndex int) int {\n\treturn 2*treeIndex + 1\n}", "func (heap Heap) Min() (Comparable, bool) {\n\tif heap.root == nil {\n\t\treturn nil, false\n\t}\n\n\treturn heap.root.value, true\n}", "func (t *Indexed) Min(i, j int) int {\n\treturn -1\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 (g *Graph) Min(x1 Node, x2 Node) Node {\n\treturn g.NewOperator(fn.NewMin(x1, x2), x1, x2)\n}", "func buildTree(preorder []int, inorder []int) *TreeNode {\n\tif len(preorder) == 0 || len(inorder) == 0 || len(preorder) != len(inorder) {\n\t\treturn nil\n\t}\n\n\tresultNode := &TreeNode{Val: preorder[0]}\n\n\tfindInInorder := func(target int) int {\n\t\tfor i := 0; i < len(inorder); i++ {\n\t\t\tif inorder[i] == target {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\tindex := findInInorder(resultNode.Val)\n\n\tresultNode.Left = buildTree(preorder[1:len(inorder[:index])+1], inorder[:index])\n\tresultNode.Right = buildTree(preorder[len(inorder[:index])+1:], inorder[index+1:])\n\treturn resultNode\n}", "func (bst BinaryTree) InsertLeft(n, at *BSTreeNode) *BSTreeNode {\n\tif at.Left == nil {\n\t\tat.Left = n\n\t\treturn at.Left\n\t}\n\tif at.Left.Value >= n.Value {\n\t\treturn bst.InsertLeft(n, at.Left)\n\t}\n\treturn bst.InsertRight(n, at.Left)\n}", "func getMinimumDifference(root *lib.TreeNode) int {\n\tvar sortedList []int\n\ttraverse(root, &sortedList)\n\tdiff := math.MaxInt32\n\tprev := sortedList[0]\n\tfor i := 1; i < len(sortedList); i++ {\n\t\tvar localDiff int\n\t\tlocalDiff = sortedList[i] - prev\n\t\tif diff > localDiff {\n\t\t\tdiff = localDiff\n\t\t}\n\t\tprev = sortedList[i]\n\t}\n\treturn diff\n}", "func findMinPos(tsmemlog *TimestampMemLog, low, high uint64) uint64 {\n\ttslog := (*tsmemlog).tslog\n\n\t// base cases\n\tif high == low {\n\t\treturn high\n\t}\n\n\tvar hts Timestamp\n\tmid := low + (high-low)/2\n\ttslog[row(mid)].lk.RLock() // Read lock segment\n\tmts := tslog[row(mid)].ts[col(mid)]\n\ttslog[row(mid)].lk.RUnlock()\n\n\ttslog[row(high)].lk.RLock() // Read lock segment\n\thts = tslog[row(high)].ts[col(high)]\n\ttslog[row(high)].lk.RUnlock()\n\n\tif mts.Before(hts) {\n\t\treturn findMinPos(tsmemlog, low, mid)\n\t} else {\n\t\treturn findMinPos(tsmemlog, mid+1, high)\n\t}\n}", "func insert(i int, root *BSTNode) {\n\tif root.data == -1 {\n\t\troot.data = i\n\t\treturn\n\t}\n\tif i <= root.data {\n\t\tif root.left == nil {\n\t\t\troot.left = NewBSTNode()\n\t\t\troot.left.data = i\n\t\t} else {\n\t\t\tinsert(i, root.left)\n\t\t}\n\t} else {\n\t\tif root.right == nil {\n\t\t\troot.right = NewBSTNode()\n\t\t\troot.right.data = i\n\t\t} else {\n\t\t\tinsert(i, root.right)\n\t\t}\n\t}\n}", "func MinRange(d []float64, l, r int) (m int) {\n\tmin := d[l]\n\tm = l\n\tfor l++; l < r; l++ {\n\t\tif d[l] <= min {\n\t\t\tmin = d[l]\n\t\t\tm = l\n\t\t}\n\t}\n\treturn\n}", "func (v *VEBTree) emptyTreeInsert(x int) {\n\tv.max = x\n\tv.min = x\n}", "func insert[T Ordered](root *node[T], value T) *node[T] {\n\t// TODO: Should this structure support multiple keys of the same value?\n\t// Should it be configurable?\n\tif value >= root.value {\n\t\tif root.right != nil {\n\t\t\treturn insert(root.right, value)\n\t\t}\n\t\troot.right = &node[T]{\n\t\t\tparent: root,\n\t\t\tvalue: value,\n\t\t}\n\t\treturn root.right\n\t}\n\tif root.left != nil {\n\t\treturn insert(root.left, value)\n\t}\n\troot.left = &node[T]{\n\t\tparent: root,\n\t\tvalue: value,\n\t}\n\treturn root.left\n}", "func removeNode(treeNode *TreeNode, key int) *TreeNode {\n\tif treeNode == nil {\n\t\treturn nil\n\t}\n\tif key < treeNode.key {\n\t\ttreeNode.leftNode = removeNode(treeNode.leftNode, key)\n\t\treturn treeNode\n\t}\n\tif key > treeNode.key {\n\t\ttreeNode.rightNode = removeNode(treeNode.rightNode, key)\n\t\treturn treeNode\n\t}\n\t// key == node.key\n\tif treeNode.leftNode == nil && treeNode.rightNode == nil {\n\t\ttreeNode = nil\n\t\treturn nil\n\t}\n\tif treeNode.leftNode == nil {\n\t\ttreeNode = treeNode.rightNode\n\t\treturn treeNode\n\t}\n\tif treeNode.rightNode == nil {\n\t\ttreeNode = treeNode.leftNode\n\t\treturn treeNode\n\t}\n\tvar leftmostrightNode *TreeNode\n\tleftmostrightNode = treeNode.rightNode\n\tfor {\n\t\t//find smallest value on the right side\n\t\tif leftmostrightNode != nil && leftmostrightNode.leftNode != nil {\n\t\t\tleftmostrightNode = leftmostrightNode.leftNode\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\ttreeNode.key, treeNode.value = leftmostrightNode.key, leftmostrightNode.value\n\ttreeNode.rightNode = removeNode(treeNode.rightNode, treeNode.key)\n\treturn treeNode\n}", "func (h sendPacketHeap) Min(greaterEqual packet.PacketID, lessEqual packet.PacketID) (*packet.DataPacket, int) {\n\tlen := len(h)\n\tidx := 0\n\twrapped := greaterEqual.Seq > lessEqual.Seq\n\tfor idx < len {\n\t\tpid := h[idx].pkt.Seq\n\t\tvar next int\n\t\tif pid.Seq == greaterEqual.Seq {\n\t\t\treturn h[idx].pkt, idx\n\t\t} else if pid.Seq >= greaterEqual.Seq {\n\t\t\tnext = idx * 2\n\t\t} else {\n\t\t\tnext = idx*2 + 1\n\t\t}\n\t\tif next >= len && h[idx].pkt.Seq.Seq > greaterEqual.Seq && (wrapped || h[idx].pkt.Seq.Seq <= lessEqual.Seq) {\n\t\t\treturn h[idx].pkt, idx\n\t\t}\n\t\tidx = next\n\t}\n\n\t// can't find any packets with greater value, wrap around\n\tif wrapped {\n\t\tidx = 0\n\t\tfor {\n\t\t\tnext := idx * 2\n\t\t\tif next >= len && h[idx].pkt.Seq.Seq <= lessEqual.Seq {\n\t\t\t\treturn h[idx].pkt, idx\n\t\t\t}\n\t\t\tidx = next\n\t\t}\n\t}\n\treturn nil, -1\n}", "func bstFirstGE(node *bstNode, key string) *bstNode {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif key < node.item.Key {\n\t\tcandidate := bstFirstGE(node.left, key)\n\t\tif candidate != nil {\n\t\t\treturn candidate\n\t\t} else {\n\t\t\treturn node\n\t\t}\n\t} else if key == node.item.Key {\n\t\treturn node\n\t} else {\n\t\treturn bstFirstGE(node.right, key)\n\t}\n}", "func min(x, y int64) int64 {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func (e *Tree) SetLeft(replacement *Tree) { e.left = replacement }", "func (h *Heap) MinHeap() {\n for i := h.num_nodes; i >= 0; i-- {\n if h.data[i] > h.data[i * 2 + 1] {\n swap(h.data, i, i * 2 + 1)\n }else if len(h.data) > i * 2 + 2 && h.data[i] > h.data[i * 2 + 2] {\n swap(h.data, i, i * 2 + 2)\n }\n }\n\n if !h.MinHeapTest() {\n h.MinHeap()\n }\n}", "func (rbt *RBTree) LowerBound(d interface{}) RBTreeIterator {\n\trbt.init()\n\treturn RBTreeIterator{\n\t\ttree: rbt,\n\t\tnode: rbtreeLowerBound(d, forward(rbt)),\n\t}\n}", "func MinDepth(root *TreeNode, c int) int {\n\tif root == nil {\n\t\treturn c\n\t}\n\n\tif root.Right == nil && root.Left == nil {\n\t\treturn c + 1\n\t}\n\n\tif root.Left == nil {\n\t\treturn MinDepth(root.Right, c+1)\n\t}\n\n\tif root.Right == nil {\n\t\treturn MinDepth(root.Left, c+1)\n\t}\n\n\tlDep := MinDepth(root.Left, c+1)\n\trDep := MinDepth(root.Right, c+1)\n\n\tif lDep < rDep {\n\t\treturn lDep\n\t}\n\n\treturn rDep\n}", "func d1pickBranch(rect *d1rectT, node *d1nodeT) int {\n\tvar firstTime bool = true\n\tvar increase float64\n\tvar bestIncr float64 = -1\n\tvar area float64\n\tvar bestArea float64\n\tvar best int\n\tvar tempRect d1rectT\n\n\tfor index := 0; index < node.count; index++ {\n\t\tcurRect := &node.branch[index].rect\n\t\tarea = d1calcRectVolume(curRect)\n\t\ttempRect = d1combineRect(rect, curRect)\n\t\tincrease = d1calcRectVolume(&tempRect) - area\n\t\tif (increase < bestIncr) || firstTime {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t\tfirstTime = false\n\t\t} else if (increase == bestIncr) && (area < bestArea) {\n\t\t\tbest = index\n\t\t\tbestArea = area\n\t\t\tbestIncr = increase\n\t\t}\n\t}\n\treturn best\n}", "func isValidBST(root *TreeNode) bool {\n if root == nil {\n return true\n }\n\n s := Stack{LimNode{root, math.MinInt64, math.MaxInt64}}\n\n for s.length() > 0 {\n n := s.pop()\n if n.node.Left != nil {\n // fmt.Printf(\"left %+v \\n\",n)\n if n.node.Left.Val < n.node.Val && n.node.Left.Val > n.min {\n s.push(LimNode{n.node.Left, n.min, n.node.Val})\n } else {\n return false\n }\n }\n if n.node.Right != nil {\n // fmt.Printf(\"right %+v \\n\",n)\n if n.node.Right.Val > n.node.Val && n.node.Right.Val < n.max {\n s.push(LimNode{n.node.Right, n.node.Val, n.max})\n } else {\n return false\n }\n }\n }\n return true\n}", "func (t *treapNode) findMinimal(f treapIterFilter) *treapNode {\n\tif t == nil || !f.matches(t.types) {\n\t\treturn nil\n\t}\n\tfor t != nil {\n\t\tif t.left != nil && f.matches(t.left.types) {\n\t\t\tt = t.left\n\t\t} else if f.matches(t.span.treapFilter()) {\n\t\t\tbreak\n\t\t} else if t.right != nil && f.matches(t.right.types) {\n\t\t\tt = t.right\n\t\t} else {\n\t\t\tprintln(\"runtime: f=\", f)\n\t\t\tthrow(\"failed to find minimal node matching filter\")\n\t\t}\n\t}\n\treturn t\n}", "func insert(t *Tree, value *Value) *Tree {\n\tif t == nil {\n\t\treturn &Tree{\n\t\t\tLeft: nil,\n\t\t\tValue: value,\n\t\t\tRight: nil,\n\t\t}\n\t}\n\tdiff := CompareVersions(value.Version, t.Value.Version)\n\tdegreeDiff := DegreeOfDifference(value.Version, t.Value.Version)\n\tdegreeDiffRight := 0\n\tif t.Right != nil && t.Right.Value != nil {\n\t\tdegreeDiffRight = DegreeOfDifference(t.Value.Version, t.Right.Value.Version)\n\t}\n\tif diff == 0 {\n\t\treturn t\n\t}\n\tif diff < 0 || degreeDiffRight > degreeDiff {\n\t\tt.Left = insert(t.Left, value)\n\t\treturn t\n\t}\n\n\tt.Right = insert(t.Right, value)\n\treturn t\n}", "func (h *heap) leftChildIndex(i int64) int64 {\n\treturn i*2 + 1\n}" ]
[ "0.65579015", "0.63982654", "0.6077484", "0.6045773", "0.6023213", "0.59858984", "0.59344995", "0.5929177", "0.58831096", "0.5850334", "0.5849182", "0.5813741", "0.58136743", "0.5782743", "0.577138", "0.5654119", "0.56292677", "0.5617895", "0.5615513", "0.56151456", "0.5564259", "0.55280083", "0.55269027", "0.55227655", "0.5509983", "0.550517", "0.54774976", "0.54553", "0.53942794", "0.538157", "0.5379554", "0.5375528", "0.5370667", "0.5361725", "0.5354165", "0.5350432", "0.53451204", "0.5344426", "0.5314818", "0.53111583", "0.53071845", "0.5305196", "0.5289566", "0.52871007", "0.5284748", "0.52831113", "0.5274599", "0.5260865", "0.5257517", "0.52556735", "0.52531654", "0.5249472", "0.5238475", "0.5229658", "0.5221657", "0.52191025", "0.5216859", "0.5194569", "0.51757073", "0.51477665", "0.51462847", "0.514234", "0.5138482", "0.51308566", "0.51305556", "0.51251715", "0.51130074", "0.50898594", "0.50848895", "0.5084587", "0.5083314", "0.5078256", "0.5070707", "0.50704676", "0.5063705", "0.5062821", "0.50627863", "0.50509304", "0.50383365", "0.50362223", "0.5035018", "0.50302905", "0.50227535", "0.5021915", "0.5014337", "0.50137997", "0.5013206", "0.50114197", "0.5008083", "0.5006532", "0.50063056", "0.50027144", "0.5000203", "0.499997", "0.4994499", "0.49901608", "0.49853072", "0.49690467", "0.49621665", "0.49609983" ]
0.6383897
2
query min value index
func query(tree, data []int, ind, left, right, queryLeft, queryRight int) (minInd int) { // query range is equal to tree range if left==queryLeft && right==queryRight { return tree[ind] } leftSub, rightSub, mid := ind*2+1, ind*2+2, left+(right-left)/2 if queryRight<=mid { // query range in left sub tree return query(tree, data, leftSub, left, mid, queryLeft, queryRight) } else if queryLeft>mid { // query range in right sub tree return query(tree, data, rightSub, mid+1, right, queryLeft, queryRight) } // else, query in both sub trees l := query(tree, data, leftSub, left, mid, queryLeft, mid) r := query(tree, data, rightSub, mid+1, right, mid+1, queryRight) // merge result for sub trees if data[l] <= data[r] { // prefer left index if tie return l } return r }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Indexed) Min(i, j int) int {\n\treturn -1\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 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 min(d dataSet) int {\n\treturn d[0]\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 minIdx(a []int) int {\n\tmin := a[0]\n\tidx := 0\n\tfor i, v := range a {\n\t\tif v < min {\n\t\t\tmin = v\n\t\t\tidx = i\n\t\t}\n\t}\n\treturn idx\n}", "func (v *V) Min() (f float64, idx int) {\n\tif v.IsNaV() {\n\t\tpanic(ErrNaV)\n\t}\n\tf = NaN()\n\tidx = -1\n\tfor i, e := range v.Data {\n\t\tif e < f || IsNaN(f) {\n\t\t\tf = e\n\t\t\tidx = i\n\t\t}\n\t}\n\tif IsNaN(f) {\n\t\tidx = -1\n\t\treturn\n\t}\n\treturn f, idx\n}", "func (f *fragment) min(filter *Row, bitDepth uint) (min int64, count uint64, err error) {\n\tconsider := f.row(bsiExistsBit)\n\tif filter != nil {\n\t\tconsider = consider.Intersect(filter)\n\t}\n\n\t// If there are no columns to consider, return early.\n\tif consider.Count() == 0 {\n\t\treturn 0, 0, nil\n\t}\n\n\t// If we have negative values, we should find the highest unsigned value\n\t// from that set, then negate it, and return it. For example, if values\n\t// (-1, -2) exist, they are stored unsigned (1,2) with a negative sign bit\n\t// set. We take the highest of that set (2) and negate it and return it.\n\tif row := f.row(bsiSignBit).Intersect(consider); row.Any() {\n\t\tmin, count := f.maxUnsigned(row, bitDepth)\n\t\treturn -min, count, nil\n\t}\n\n\t// Otherwise find lowest positive number.\n\tmin, count = f.minUnsigned(consider, bitDepth)\n\treturn min, count, nil\n}", "func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilder {\n\tiob.document = append(iob.document, bson.E{\"min\", min})\n\treturn iob\n}", "func findMin(vals []float64) float64 {\n\tmin := float64(vals[0])\n\tfor v := range vals {\n\t\tif vals[v] < min {\n\t\t\tmin = vals[v]\n\t\t}\n\t}\n\treturn float64(min)\n}", "func (r Results) Min() int {\n\tmin := r.Max()\n\n\tfor _, result := range r {\n\t\tm := result.Min()\n\t\tif m < min {\n\t\t\tmin = m\n\t\t}\n\t}\n\n\treturn min\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 Min(v float64) predicate.Transactionfactoritemtmp {\n\treturn predicate.Transactionfactoritemtmp(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldMin), v))\n\t})\n}", "func getIndexOfMinChild(list []Comparable, pos int) (int, bool) {\n\tleft, right := getChildIndices(pos)\n\n\t// if indices are both out of range return 0 with false flag\n\tif left >= len(list) && right >= len(list) {\n\t\treturn 0, false\n\t}\n\n\t// left is in range but right is not\n\tif right >= len(list) {\n\t\treturn left, true\n\t}\n\n\t// otherwise return the index of the bigger value\n\tif list[left].GetComparable() < list[right].GetComparable() {\n\t\treturn left, true\n\t} else {\n\t\treturn right, true\n\t}\n}", "func (tb *TimeBucket) Min() int64 { return tb.min }", "func MinKey() Val { return Val{t: bsontype.MinKey} }", "func (t *Tree) RangeMinQuery(left, right int) int {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\treturn (&query{left: left, right: right, nodes: t.nodes}).rangeMinimum(0, 0, t.size-1)\n}", "func flexibleGetSmallest(r *ring.Ring, index int) (float64, error) {\n var arr []float64\n\n // Put each ring value into an array\n for i := 0; i < r.Len(); i++ {\n switch r.Value.(type) {\n case int:\n arr = append(arr, float64(r.Value.(int)))\n r = r.Next()\n case float32:\n arr = append(arr, float64(r.Value.(float32)))\n r = r.Next()\n case float64:\n arr = append(arr, r.Value.(float64))\n r = r.Next()\n case string:\n if val, err := strconv.ParseFloat(r.Value.(string), 64); err == nil {\n arr = append(arr, val)\n r = r.Next()\n } else {\n return -1, errors.New(err.Error())\n }\n default:\n return -1, errors.New(\"Data type not yet supported\")\n } \n }\n\n // Sort the array (smallest to largest)\n sort.Float64s(arr)\n\n return arr[index], nil\n}", "func TestLogarithmIndexMin(t *testing.T) {\n\tfor scale := MinScale; scale <= MaxScale; scale++ {\n\t\tm, err := NewMapping(scale)\n\t\trequire.NoError(t, err)\n\n\t\tminIndex := m.MapToIndex(MinValue)\n\n\t\tmapped, err := m.LowerBoundary(minIndex)\n\t\trequire.NoError(t, err)\n\n\t\tcorrectMinIndex := int64(exponent.MinNormalExponent) << scale\n\t\trequire.Greater(t, correctMinIndex, int64(math.MinInt32))\n\n\t\tcorrectMapped := roundedBoundary(scale, int32(correctMinIndex))\n\t\trequire.Equal(t, correctMapped, MinValue)\n\t\trequire.InEpsilon(t, mapped, MinValue, 1e-6)\n\n\t\trequire.Equal(t, minIndex, int32(correctMinIndex))\n\n\t\t// Subnormal values map to the min index:\n\t\trequire.Equal(t, m.MapToIndex(MinValue/2), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/3), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/100), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1050), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1.1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1074), int32(correctMinIndex))\n\n\t\t// One smaller index will underflow.\n\t\t_, err = m.LowerBoundary(minIndex - 1)\n\t\trequire.Equal(t, err, mapping.ErrUnderflow)\n\t}\n}", "func (evsq *ExValueScanQuery) FirstIDX(ctx context.Context) int {\n\tid, err := evsq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\t// TBD: Do I need to lock? Or only use Min() in lock?\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\n\tcurMin := px.doneValue[0]\n\tfor i := range px.doneValue {\n\t\tif px.doneValue[i] < curMin {\n\t\t\tcurMin = px.doneValue[i]\n\t\t}\n\t}\n\treturn curMin + 1\n}", "func getMinOfMajority(index map[int]int, commitIndex int) (min int) {\n\tmin = 10000\n\tcountMap := make(map[int]int)\n\tfor _, currentIndex := range index {\n\t\t_, ok := countMap[currentIndex]\n\t\tif !ok {\n\t\t\tcountMap[currentIndex] = 0\n\t\t}\n\t\t// update every entry in countMap, if the key of entry is larger than currentIndex, its value plus one.\n\t\tfor key, value := range countMap {\n\t\t\tif key <= currentIndex {\n\t\t\t\tcountMap[key] = value + 1\n\t\t\t}\n\t\t}\n\t}\n\tfor key, value := range countMap {\n\t\tif min > key && value >= len(index)/2+1 && key > commitIndex {\n\t\t\tmin = key\n\t\t}\n\t}\n\tTPrintf(\"getMinOfMajority: countMap=%v, commitIndex=%d, min=%d.\", countMap, commitIndex, min)\n\treturn min\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 (s VectOp) MinOp(o fs.IndexedFunc) VectOp {\n\treturn fs.MinOp(s, o)\n}", "func (t *binarySearchST) Min() interface{} {\n\tutils.AssertF(!t.IsEmpty(), \"called Min() with empty symbol table\")\n\treturn t.keys[0]\n}", "func (v Vector) Min() (float64, int) {\n\tif len(v) == 0 {\n\t\treturn 0, 0\n\t}\n\tmin := v[0]\n\tidx := 0\n\tfor i := 1; i < len(v); i++ {\n\t\tif v[i] < min {\n\t\t\tmin = v[i]\n\t\t\tidx = i\n\t\t}\n\t}\n\treturn min, idx\n}", "func (f *fragment) minRow(filter *Row) (uint64, uint64) {\n\tminRowID, hasRowID := f.minRowID()\n\tif hasRowID {\n\t\tif filter == nil {\n\t\t\treturn minRowID, 1\n\t\t}\n\t\t// iterate from min row ID and return the first that intersects with filter.\n\t\tfor i := minRowID; i <= f.maxRowID; i++ {\n\t\t\trow := f.row(i).Intersect(filter)\n\t\t\tcount := row.Count()\n\t\t\tif count > 0 {\n\t\t\t\treturn i, count\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, 0\n}", "func Min(slice AnySlice) AnyValue {\n\tmustBeSlice(slice)\n\tcount := reflect.ValueOf(slice).Len()\n\tif count == 0 {\n\t\treturn nil\n\t}\n\tsliceVal := reflect.ValueOf(slice)\n\tvar min AnyValue = sliceVal.Index(0).Interface()\n\tfor i := 0; i < count; i++ {\n\t\tval := sliceVal.Index(i).Interface()\n\t\tif less(val, min) {\n\t\t\tmin = val\n\t\t}\n\t}\n\treturn min\n}", "func TestExponentIndexMin(t *testing.T) {\n\tfor scale := MinScale; scale <= MaxScale; scale++ {\n\t\tm, err := NewMapping(scale)\n\t\trequire.NoError(t, err)\n\n\t\tminIndex := m.MapToIndex(MinValue)\n\n\t\tmapped, err := m.LowerBoundary(minIndex)\n\t\trequire.NoError(t, err)\n\n\t\tcorrectMinIndex := int64(exponent.MinNormalExponent) << scale\n\t\trequire.Greater(t, correctMinIndex, int64(math.MinInt32))\n\n\t\tcorrectMapped := roundedBoundary(scale, int32(correctMinIndex))\n\t\trequire.Equal(t, correctMapped, MinValue)\n\t\trequire.InEpsilon(t, mapped, MinValue, 1e-6)\n\n\t\trequire.Equal(t, minIndex, int32(correctMinIndex))\n\n\t\t// Subnormal values map to the min index:\n\t\trequire.Equal(t, m.MapToIndex(MinValue/2), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/3), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/100), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1050), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1.1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1074), int32(correctMinIndex))\n\n\t\t// One smaller index will underflow.\n\t\t_, err = m.LowerBoundary(minIndex - 1)\n\t\trequire.Equal(t, err, mapping.ErrUnderflow)\n\t}\n}", "func min[T constraints.Ordered](values ...T) T {\n\tvar acc T = values[0]\n\n\tfor _, v := range values {\n\t\tif v < acc {\n\t\t\tacc = v\n\t\t}\n\t}\n\treturn acc\n}", "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 (o SolutionIntegerHyperParameterRangeOutput) MinValue() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v SolutionIntegerHyperParameterRange) *int { return v.MinValue }).(pulumi.IntPtrOutput)\n}", "func min(dataSlice []float64) float64 {\n\tmin := dataSlice[0]\n\tfor _, j := range dataSlice {\n\t\tif j < min {\n\t\t\tmin = j\n\t\t}\n\t}\n\treturn min\n}", "func (v Vec) Min() float64 {\n\treturn v[1:].Reduce(func(a, e float64) float64 { return math.Min(a, e) }, v[0])\n}", "func MinGTE(v float64) predicate.Transactionfactoritemtmp {\n\treturn predicate.Transactionfactoritemtmp(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldMin), v))\n\t})\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\tmin := px.localDoneMin\n\tfor _, v := range px.doneMins {\n\t\tif min > v {\n\t\t\tmin = v\n\t\t}\n\t}\n\t//清理数据,或者放到decide中清理,但是总是会调用这个min的\n\thead := px.prepareStatus.Head\n\tfor head.Next != nil {\n\t\tseq := head.Seq\n\t\thead = head.Next\n\t\tif seq < min && seq != -1 {\n\t\t\t//log.Printf(\"now delete element of %d\", seq)\n\t\t\tpx.prepareStatus.DeleteElem(seq)\n\t\t}\n\t}\n\treturn min + 1\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 getLeastConInstIdx(instances []*Instance) int {\r\n\tminLoad := maxFloat32\r\n\tidx := 0\r\n\r\n\tfor i, inst := range instances {\r\n\t\tif inst == nil {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tload := float32(len(inst.ReqCount)) / inst.Weight\r\n\t\tif load < minLoad {\r\n\t\t\tminLoad = load\r\n\t\t\tidx = i\r\n\t\t}\r\n\t}\r\n\r\n\treturn idx\r\n}", "func (h *PCPHistogram) Min() int64 {\n\th.mutex.RLock()\n\tdefer h.mutex.RUnlock()\n\treturn int64(h.vals[\"min\"].val.(float64))\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 minStartValue(nums []int) int {\n\tstartValue, sum := 1, 1\n\tfor _, num := range nums {\n\t\tsum = sum + num\n\t\tif sum <= 0 {\n\t\t\taddNum := 1 - sum\n\t\t\tsum, startValue = sum+addNum, startValue+addNum\n\t\t}\n\t}\n\treturn startValue\n}", "func (b ValExprBuilder) Min() ValExprBuilder {\n\treturn b.makeFunc(\"MIN\", false)\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\n\tmin := px.dones[px.me]\n\tfor k := range px.dones {\n\t\tif min > px.dones[k] {\n\t\t\tmin = px.dones[k]\n\t\t}\n\t}\n\n\tfor k, _ := range px.acceptor {\n\t\tif k <= min && px.acceptor[k].state == Decided {\n\t\t\tdelete(px.acceptor, k)\n\t\t\tdelete(px.prepareNum, k)\n\t\t}\n\t}\n\n\treturn min + 1\n}", "func FindMin(arr []int) int {\n\tresult := arr[0]\n\tfor _, v := range arr {\n\t\tif v < result {\n\t\t\tresult = v\n\t\t}\n\t}\n\treturn result\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 Min(field string) AggregateFunc {\n\treturn func(start, end string) (string, *dsl.Traversal) {\n\t\tif end == \"\" {\n\t\t\tend = DefaultMinLabel\n\t\t}\n\t\treturn end, __.As(start).Unfold().Values(field).Min().As(end)\n\t}\n}", "func (eq *EntryQuery) FirstIDX(ctx context.Context) int {\n\tid, err := eq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\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 (luq *LastUpdatedQuery) FirstIDX(ctx context.Context) int {\n\tid, err := luq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\tpx.RLock()\n\tdefer px.RUnlock()\n\treturn px.minSeq\n}", "func FindMinValueFromList(list []int) (int, int) {\n\tmin := list[0]\n\tindexOfMinElement := 0\n\tfor i := 1; i < len(list); i++ {\n\t\tif list[i] < min {\n\t\t\tmin = list[i]\n\t\t\tindexOfMinElement = i\n\t\t}\n\t}\n\treturn min, indexOfMinElement\n}", "func (na *NArray) MinElem(v float32, indices ...int) {\n\n\tidx := na.Index(indices...)\n\tif v < na.Data[idx] {\n\t\tna.Data[idx] = v\n\t}\n}", "func (s VectOp) Min() float64 {\n\tmin := math.Inf(+1)\n\tfor _, val := range s {\n\t\tmin = math.Min(min, val)\n\t}\n\treturn min\n}", "func Min(xs []float64) float64 {\n if len(xs) == 0 {\n return float64(0)\n }\n i := xs[0]\n for _, x := range xs {\n if i > x {\n i = x\n }\n }\n return i\n}", "func MinLT(v float64) predicate.Transactionfactoritemtmp {\n\treturn predicate.Transactionfactoritemtmp(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldMin), v))\n\t})\n}", "func (v *V) MinAbs() (f float64, idx int) {\n\tif v.IsNaV() {\n\t\tpanic(ErrNaV)\n\t}\n\tf = NaN()\n\tidx = -1\n\tfor i, e := range v.Data {\n\t\tabs := math.Abs(e)\n\t\tif abs < f || IsNaN(f) {\n\t\t\tf = abs\n\t\t\tidx = i\n\t\t}\n\t}\n\tif IsNaN(f) {\n\t\tidx = -1\n\t\treturn\n\t}\n\treturn f, idx\n}", "func Min(x, min int) int { return x }", "func (px *Paxos) Min() int {\n\t//DPrintf(\"Min()\\n\")\n\n\tmin := math.MaxInt64\n\tfor _, seq := range px.done {\n\t\tif seq < min {\n\t\t\tmin = seq\n\t\t}\n\t}\n\treturn min + 1\n}", "func (px *Paxos) Min() int {\n // You code here.\n px.mu.Lock()\n defer px.mu.Unlock()\n\n min_seq := math.MaxInt32\n for _, v := range px.decisions {\n if v < min_seq {\n min_seq = v\n }\n }\n\n //Delete unnecessary instances\n for seq, ins := range px.history {\n if seq <= min_seq && ins.status {\n delete(px.history, seq)\n }\n\n }\n return min_seq + 1\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 Min(col Columnar) ColumnElem {\n\treturn Function(MIN, col)\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 Min(inp data) (min float64, err error) {\n\n\tlength := inp.Len()\n\n\tif length == 0 {\n\t\treturn math.NaN(), errors.New(\"Empty Set\")\n\t}\n\n\tmin = inp.Get(0)\n\n\tfor i := 1; i < length; i++ {\n\t\tif inp.Get(i) < min {\n\t\t\tmin = inp.Get(i)\n\t\t}\n\t}\n\treturn min, nil\n}", "func (c *Counter) Min() int64 { return c.min }", "func (px *Paxos) Min() int {\n // You code here.\n return minOfArray(px.doneMap) + 1\n}", "func Min(vals []float64) float64 {\n\tmin := vals[0]\n\tfor _, val := range vals {\n\t\tif val < min {\n\t\t\tmin = val\n\t\t}\n\t}\n\treturn min\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\treturn px.minSeq\n}", "func MINSD(mx, x operand.Op) { ctx.MINSD(mx, x) }", "func minInASlice(l []float64) int {\n\tvar max float64\n\tvar index int\n\tfor i, d := range l {\n\t\tif d > max {\n\t\t\tmax = d\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn index\n}", "func (px *Paxos) Min() int {\n\t// You code here.\n\treturn px.min\n}", "func (i *InmemStore) FirstIndex() (uint64, error) {\n\ti.l.RLock()\n\tdefer i.l.RUnlock()\n\treturn i.lowIndex, nil\n}", "func (o *Object) Min_V(j int) float32 {\n\tx := float32(0)\n\tif len(o.v_list) != 0 {\n\t\t// initial value\n\t\tx = o.v_list[0].x[j]\n\t\tfor i := 0; i < len(o.v_list); i++ {\n\t\t\tif o.v_list[i].x[j] < x {\n\t\t\t\tx = o.v_list[i].x[j]\n\t\t\t}\n\t\t}\n\t}\n\treturn x\n}", "func lookUpIdx(scaledValue int) int {\n\tscaledValue32 := int32(scaledValue)\n\tif scaledValue32 < maxArrayValue { //constant\n\t\treturn val2Bucket[scaledValue]\n\t}\n\tfor i := maxArrayValueIndex; i < numValues; i++ {\n\t\tif histogramBucketValues[i] > scaledValue32 {\n\t\t\treturn i\n\t\t}\n\t}\n\tlog.Fatalf(\"never reached/bug\")\n\treturn 0\n}", "func (s *UniformSample) Min() int64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SampleMin(s.values)\n}", "func MinEQ(v float64) predicate.Transactionfactoritemtmp {\n\treturn predicate.Transactionfactoritemtmp(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldMin), v))\n\t})\n}", "func (t *TimerSnapshot) Min() int64 { return t.histogram.Min() }", "func Min(vals ...float64) float64 {\n\tmin := vals[0]\n\tfor _, v := range vals {\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn min\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 (lbq *LatestBlockQuery) FirstIDX(ctx context.Context) int {\n\tid, err := lbq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func calcListMatrixMin(mina bool, min float64, arg formulaArg) float64 {\n\tfor _, cell := range arg.ToList() {\n\t\tif cell.Type == ArgNumber && cell.Number < min {\n\t\t\tif mina && cell.Boolean || !cell.Boolean {\n\t\t\t\tmin = cell.Number\n\t\t\t}\n\t\t}\n\t}\n\treturn min\n}", "func (s FloatList) Min() float64 {\n\tif s.size == 0 {\n\t\treturn 0\n\t}\n\treturn s.sorted[0]\n}", "func (logStore *logStore) FirstIndex() (uint64, error) {\n\treturn logStore.LowestOffset()\n}", "func perfGetSmallest(r *ring.Ring) int {\n // Set smallest to first value\n var smallest int = r.Value.(int)\n\n // Do a single loop through ring to determine smallest number\n r.Do(func(p interface{}) {\n\t\tif p.(int) < smallest {\n smallest = p.(int)\n }\n })\n \n return smallest\n}", "func (omq *OutcomeMeasureQuery) FirstIDX(ctx context.Context) int {\n\tid, err := omq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func MINPD(mx, x operand.Op) { ctx.MINPD(mx, x) }", "func (list Int64Set) Min() int64 {\n\treturn list.MinBy(func(a int64, b int64) bool {\n\t\treturn a < b\n\t})\n}", "func (ds *Dataset) Min() float64 {\n\tds.mustNotEmpty()\n\treturn ds.min\n}", "func (o *Grid) Xmin(idim int) float64 {\n\treturn o.xmin[idim]\n}", "func (wtq *WorkerTypeQuery) FirstIDX(ctx context.Context) int {\n\tid, err := wtq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (rq *RemedyQuery) FirstIDX(ctx context.Context) int {\n\tid, err := rq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func GetMinAbsIdx(l []int) int {\n\tstartIndex := 0\n\tendIndex := len(l) - 1\n\tmidIndex := len(l) / 2\n\n\tminIdx := midIndex\n\tmin := abs(l[midIndex])\n\tfor startIndex <= endIndex {\n\t\tvalue := l[midIndex]\n\t\tif abs(value) < min {\n\t\t\tminIdx = midIndex\n\t\t\tmin = abs(value)\n\t\t}\n\n\t\tif min == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif value > 0 {\n\t\t\tendIndex = midIndex - 1\n\t\t\tmidIndex = (startIndex + endIndex) / 2\n\t\t\tcontinue\n\t\t}\n\n\t\tstartIndex = midIndex + 1\n\t\tmidIndex = (startIndex + endIndex) / 2\n\t}\n\n\treturn minIdx\n}", "func FindKthMin(nums []int, k int) (int, error) {\n\tindex := k - 1\n\treturn kthNumber(nums, index)\n}", "func (r Result) Min() int {\n\treturn len(r.Ints()) * r.Die().Min().N\n}", "func Min(a, operand int) int {\n\tif a < operand {\n\t\treturn a\n\t}\n\treturn operand\n}", "func (u *Update) Min(obj types.M) *Update {\n\tu.update[\"$min\"] = obj\n\treturn u\n}", "func (t *Tensor) Min(along ...int) (retVal *Tensor, err error) {\n\tmonotonic, incr1 := types.IsMonotonicInts(along) // if both are true, then it means all axes are accounted for, then it'll return a scalar value\n\tif (monotonic && incr1 && len(along) == t.Dims()) || len(along) == 0 {\n\t\tret := sliceMin(t.data)\n\t\tretVal = NewTensor(AsScalar(ret))\n\t\treturn\n\t}\n\tretVal = t\n\tprev := -1\n\tdims := len(retVal.Shape())\n\n\tfor _, axis := range along {\n\t\tif prev == -1 {\n\t\t\tprev = axis\n\t\t}\n\t\tif axis > prev {\n\t\t\taxis--\n\t\t}\n\n\t\tif axis >= dims {\n\t\t\terr = types.DimMismatchErr(axis, retVal.Dims())\n\t\t\treturn\n\t\t}\n\n\t\tretVal = retVal.min(axis)\n\t}\n\treturn\n}", "func (_TellorMesosphere *TellorMesosphereSession) Min(_a *big.Int, _b *big.Int) (*big.Int, error) {\n\treturn _TellorMesosphere.Contract.Min(&_TellorMesosphere.CallOpts, _a, _b)\n}", "func (hq *HarborQuery) FirstIDX(ctx context.Context) int {\n\tid, err := hq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func Min(d []float64) (v float64, i int, ok bool) {\n\tif len(d) == 0 {\n\t\treturn 0, 0, false\n\t}\n\tv = d[0]\n\ti = 0\n\tfor x := 1; x < len(d); x++ {\n\t\tif d[x] < v {\n\t\t\tv = d[x]\n\t\t\ti = x\n\t\t}\n\t}\n\treturn v, i, true\n}", "func (px *Paxos) Min() int {\n\treturn px.Lo\n}", "func (wq *WidgetQuery) FirstIDX(ctx context.Context) int {\n\tid, err := wq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}" ]
[ "0.6968053", "0.68700284", "0.67979103", "0.67292726", "0.65732807", "0.6550194", "0.6415493", "0.6412388", "0.6291479", "0.62318045", "0.62206954", "0.61924726", "0.6145002", "0.610618", "0.6099185", "0.60543025", "0.60209656", "0.60148805", "0.5997986", "0.5984362", "0.596354", "0.5958028", "0.59459096", "0.593134", "0.59235585", "0.58931816", "0.587271", "0.58699626", "0.58689594", "0.58427805", "0.58380204", "0.5829906", "0.5813691", "0.5802816", "0.57953835", "0.5794524", "0.5791532", "0.57898784", "0.5783669", "0.5776817", "0.5775887", "0.57703525", "0.5766831", "0.57661784", "0.57598025", "0.5755184", "0.5739273", "0.57378715", "0.5736022", "0.57166886", "0.57156193", "0.57123303", "0.5706713", "0.5702411", "0.5700837", "0.56994784", "0.5694971", "0.5686071", "0.5680965", "0.56806463", "0.5674692", "0.5664711", "0.5659352", "0.56576896", "0.5653727", "0.56504756", "0.5645829", "0.5623501", "0.5604361", "0.55951476", "0.5594884", "0.559209", "0.55916727", "0.55913746", "0.55882996", "0.5585913", "0.5579503", "0.5576488", "0.55720174", "0.5568859", "0.5568856", "0.5563851", "0.5562943", "0.5559031", "0.5558613", "0.55553865", "0.5553635", "0.5545822", "0.55366457", "0.55358136", "0.5526726", "0.5526478", "0.55236095", "0.5523208", "0.5522209", "0.551721", "0.5514393", "0.55081725", "0.5500156", "0.54995453", "0.5497398" ]
0.0
-1
NewSTSManager implements AWS GO SDK
func NewSTSManager(client STSClientDescriptor) *STSManager { return &STSManager{ client: client, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newClient() *sts.STS {\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\tconfig := aws.NewConfig()\n\tif debug {\n\t\tconfig.WithLogLevel(aws.LogDebugWithHTTPBody)\n\t}\n\treturn sts.New(sess, config)\n}", "func RunCreateAWSSTSS3(cmd *cobra.Command, args []string) {\n\tlog := util.Logger()\n\tif len(args) != 1 || args[0] == \"\" {\n\t\tlog.Fatalf(`❌ Missing expected arguments: <namespace-store-name> %s`, cmd.UsageString())\n\t}\n\tname := args[0]\n\to := util.KubeObject(bundle.File_deploy_crds_noobaa_io_v1alpha1_noobaa_cr_yaml)\n\tsys := o.(*nbv1.NooBaa)\n\tsys.Name = options.SystemName\n\tsys.Namespace = options.Namespace\n\n\to = util.KubeObject(bundle.File_deploy_crds_noobaa_io_v1alpha1_namespacestore_cr_yaml)\n\tnamespaceStore := o.(*nbv1.NamespaceStore)\n\tnamespaceStore.Name = name\n\tnamespaceStore.Namespace = options.Namespace\n\tnamespaceStore.Spec = nbv1.NamespaceStoreSpec{Type: nbv1.NSStoreTypeAWSS3}\n\n\tif !util.KubeCheck(sys) {\n\t\tlog.Fatalf(`❌ Could not find NooBaa system %q in namespace %q`, sys.Name, sys.Namespace)\n\t}\n\n\terr := util.KubeClient().Get(util.Context(), util.ObjectKey(namespaceStore), namespaceStore)\n\tif err == nil {\n\t\tlog.Fatalf(`❌ NamespaceStore %q already exists in namespace %q`, namespaceStore.Name, namespaceStore.Namespace)\n\t}\n\tawsSTSARN := util.GetFlagStringOrPrompt(cmd, \"aws-sts-arn\")\n\ttargetBucket := util.GetFlagStringOrPrompt(cmd, \"target-bucket\")\n\tregion, _ := cmd.Flags().GetString(\"region\")\n\tnamespaceStore.Spec.AWSS3 = &nbv1.AWSS3Spec{\n\t\tTargetBucket: targetBucket,\n\t\tRegion: region,\n\t\tAWSSTSRoleARN: &awsSTSARN,\n\t}\n\t// Create namespace store CR\n\tutil.Panic(controllerutil.SetControllerReference(sys, namespaceStore, scheme.Scheme))\n\tif !util.KubeCreateFailExisting(namespaceStore) {\n\t\tlog.Fatalf(`❌ Could not create NamespaceStore %q in Namespace %q (conflict)`, namespaceStore.Name, namespaceStore.Namespace)\n\t}\n\tlog.Printf(\"\")\n\tutil.PrintThisNoteWhenFinishedApplyingAndStartWaitLoop()\n\tlog.Printf(\"\")\n\tlog.Printf(\"NamespaceStore Wait Ready:\")\n\tif WaitReady(namespaceStore) {\n\t\tlog.Printf(\"\")\n\t\tlog.Printf(\"\")\n\t\tRunStatus(cmd, args)\n\t}\n}", "func New(auth stacks.AuthenticationOptions, localCfg stacks.AWSConfiguration, cfg stacks.ConfigurationOptions) (*stack, error) { // nolint\n\tif localCfg.Ec2Endpoint == \"\" {\n\t\tlocalCfg.Ec2Endpoint = fmt.Sprintf(\"https://ec2.%s.amazonaws.com\", localCfg.Region)\n\t}\n\tif localCfg.SsmEndpoint == \"\" {\n\t\tlocalCfg.SsmEndpoint = fmt.Sprintf(\"https://ssm.%s.amazonaws.com\", localCfg.Region)\n\t}\n\n\tstack := &stack{\n\t\tConfig: &cfg,\n\t\tAuthOptions: &auth,\n\t\tAwsConfig: &localCfg,\n\t}\n\n\taccessKeyID := auth.AccessKeyID\n\tsecretAccessKey := auth.SecretAccessKey\n\n\tss3 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.S3Endpoint),\n\t}))\n\n\tsec2 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.Ec2Endpoint),\n\t}))\n\n\tsssm := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.SsmEndpoint),\n\t}))\n\n\tspricing := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(endpoints.UsEast1RegionID),\n\t}))\n\n\tstack.S3Service = s3.New(ss3, &aws.Config{})\n\tstack.EC2Service = ec2.New(sec2, &aws.Config{})\n\tstack.SSMService = ssm.New(sssm, &aws.Config{})\n\tstack.PricingService = pricing.New(spricing, &aws.Config{})\n\n\tif cfg.Timings != nil {\n\t\tstack.MutableTimings = cfg.Timings\n\t} else {\n\t\tstack.MutableTimings = temporal.NewTimings()\n\t}\n\n\treturn stack, nil\n}", "func init() {\n\tdebugMode = (os.Getenv(\"DEBUG\") != \"\")\n\n\tarnPattern = regexp.MustCompile(\"\\\\Aarn:aws:sts::\\\\d+:assumed-role/([a-z0-9_-]+)/(i-[0-9a-f]+)\\\\z\")\n\n\tcaKeyBucket, caKeyPath, err := parseS3URI(os.Getenv(\"CA_KEY_URI\"))\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"CA_KEY_URI: %w\", err)\n\t\treturn\n\t}\n\n\tob, op, err := parseS3URI(os.Getenv(\"OUTPUT_URI_PREFIX\"))\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"OUTPUT_URI_PREFIX: %w\", err)\n\t\treturn\n\t}\n\toutBucket = ob\n\toutPathPrefix = op\n\n\taws, err := newAwsClient()\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"initializing aws client: %w\", err)\n\t\treturn\n\t}\n\tawsCli = aws\n\n\tcaKey, err := awsCli.getS3Object(caKeyBucket, caKeyPath)\n\tif err != nil {\n\t\tfmt.Printf(\"error getting CA key, bucket=%q path=%q\\n\", caKeyBucket, caKeyPath)\n\t\tinitError = fmt.Errorf(\"getting caKey: %w\", err)\n\t\treturn\n\t}\n\n\tsigner, err = NewSigner(caKey)\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"creating signer: %w\", err)\n\t\treturn\n\t}\n\n\tif debugMode {\n\t\tfmt.Printf(\"init completed\")\n\t}\n}", "func AWSCreate() {\n\tSetClusterName()\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/.terraform\"); err == nil {\n\t\tfmt.Println(\"Configuration folder already exists\")\n\t} else {\n\t\tsshUser, osLabel := distSelect()\n\t\tfmt.Printf(\"Prepairing Setup for user %s on %s\\n\", sshUser, osLabel)\n\t\tos.MkdirAll(\"./inventory/\"+common.Name+\"/provisioner\", 0755)\n\t\terr := exec.Command(\"cp\", \"-rfp\", \"./kubespray/contrib/terraform/aws/.\", \"./inventory/\"+common.Name+\"/provisioner\").Run()\n\t\tcommon.ErrorCheck(\"provisioner could not provided: %v\", err)\n\t\tprepareConfigFiles(osLabel)\n\t\tprovisioner.ExecuteTerraform(\"init\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\t}\n\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\n\t// waiting for Loadbalancer and other not completed stuff\n\tfmt.Println(\"Infrastructure is upcoming.\")\n\ttime.Sleep(15 * time.Second)\n\treturn\n\n}", "func sts(r AirflowResource, component string, suffix string, svc bool) *appsv1.StatefulSet {\n\tname, labels, matchlabels := nameAndLabels(r, component, suffix, true)\n\tsvcName := \"\"\n\tif svc {\n\t\tsvcName = name\n\t}\n\n\treturn &appsv1.StatefulSet{\n\t\tObjectMeta: r.getMeta(name, labels),\n\t\tSpec: appsv1.StatefulSetSpec{\n\t\t\tServiceName: svcName,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: matchlabels,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: r.getAnnotations(),\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tAffinity: r.getAffinity(),\n\t\t\t\t\tNodeSelector: r.getNodeSelector(),\n\t\t\t\t\tSubdomain: name,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func CmdCreateAWSSTSS3() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"aws-sts-s3 <namespace-store-name>\",\n\t\tShort: \"Create aws-sts-s3 namespace store\",\n\t\tRun: RunCreateAWSSTSS3,\n\t}\n\tcmd.Flags().String(\n\t\t\"target-bucket\", \"\",\n\t\t\"The target bucket name on the cloud\",\n\t)\n\tcmd.Flags().String(\n\t\t\"aws-sts-arn\", \"\",\n\t\t\"The AWS STS Role ARN which will assume role\",\n\t)\n\tcmd.Flags().String(\n\t\t\"region\", \"\",\n\t\t\"The AWS bucket region\",\n\t)\n\treturn cmd\n}", "func (s *TestSuiteIAM) TestSTSForRoot(c *check) {\n\tctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)\n\tdefer cancel()\n\n\tbucket := getRandomBucketName()\n\terr := s.client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})\n\tif err != nil {\n\t\tc.Fatalf(\"bucket create error: %v\", err)\n\t}\n\n\tassumeRole := cr.STSAssumeRole{\n\t\tClient: s.TestSuiteCommon.client,\n\t\tSTSEndpoint: s.endPoint,\n\t\tOptions: cr.STSAssumeRoleOptions{\n\t\t\tAccessKey: globalActiveCred.AccessKey,\n\t\t\tSecretKey: globalActiveCred.SecretKey,\n\t\t\tLocation: \"\",\n\t\t},\n\t}\n\n\tvalue, err := assumeRole.Retrieve()\n\tif err != nil {\n\t\tc.Fatalf(\"err calling assumeRole: %v\", err)\n\t}\n\n\tminioClient, err := minio.New(s.endpoint, &minio.Options{\n\t\tCreds: cr.NewStaticV4(value.AccessKeyID, value.SecretAccessKey, value.SessionToken),\n\t\tSecure: s.secure,\n\t\tTransport: s.TestSuiteCommon.client.Transport,\n\t})\n\tif err != nil {\n\t\tc.Fatalf(\"Error initializing client: %v\", err)\n\t}\n\n\t// Validate that the client from sts creds can access the bucket.\n\tc.mustListObjects(ctx, minioClient, bucket)\n\n\t// Validate that a bucket can be created\n\tbucket2 := getRandomBucketName()\n\terr = minioClient.MakeBucket(ctx, bucket2, minio.MakeBucketOptions{})\n\tif err != nil {\n\t\tc.Fatalf(\"bucket creat error: %v\", err)\n\t}\n\n\t// Validate that admin APIs can be called - create an madmin client with\n\t// user creds\n\tuserAdmClient, err := madmin.NewWithOptions(s.endpoint, &madmin.Options{\n\t\tCreds: cr.NewStaticV4(value.AccessKeyID, value.SecretAccessKey, value.SessionToken),\n\t\tSecure: s.secure,\n\t})\n\tif err != nil {\n\t\tc.Fatalf(\"Err creating user admin client: %v\", err)\n\t}\n\tuserAdmClient.SetCustomTransport(s.TestSuiteCommon.client.Transport)\n\n\taccInfo, err := userAdmClient.AccountInfo(ctx, madmin.AccountOpts{})\n\tif err != nil {\n\t\tc.Fatalf(\"root user STS should be able to get account info: %v\", err)\n\t}\n\n\tgotBuckets := set.NewStringSet()\n\tfor _, b := range accInfo.Buckets {\n\t\tgotBuckets.Add(b.Name)\n\t\tif !(b.Access.Read && b.Access.Write) {\n\t\t\tc.Fatalf(\"root user should have read and write access to bucket: %v\", b.Name)\n\t\t}\n\t}\n\tshouldHaveBuckets := set.CreateStringSet(bucket2, bucket)\n\tif !gotBuckets.Equals(shouldHaveBuckets) {\n\t\tc.Fatalf(\"root user should have access to all buckets\")\n\t}\n}", "func (service *S3Service) newS3Request() *S3Request {\n return NewS3Request(service.accessKey, service.secretKey)\n}", "func NewClient(baseARN string, regional bool) *Client {\n\treturn &Client{\n\t\tBaseARN: baseARN,\n\t\tEndpoint: \"sts.amazonaws.com\",\n\t\tUseRegionalEndpoint: regional,\n\t}\n}", "func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler.ProgressEvent, error) {\n\t// Add your code here:\n\t// * Make API calls (use req.Session)\n\t// * Mutate the model\n\t// * Check/set any callback context (req.CallbackContext / response.CallbackContext)\n\n\tiotSvc := iot.New(req.Session)\n\ts3Svc := s3.New(req.Session)\n\n\ttestKey := req.LogicalResourceID\n\t_, err := s3Svc.PutObject(&s3.PutObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &testKey,\n\t\tBody: strings.NewReader(\"test\"),\n\t})\n\tif err != nil {\n\t\taerr, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tfmt.Printf(\"%v\", aerr)\n\t\t}\n\t\tresponse := handler.ProgressEvent{\n\t\t\tOperationStatus: handler.Failed,\n\t\t\tMessage: \"Bucket is not accessible\",\n\t\t}\n\t\treturn response, nil\n\t}\n\t_, err = s3Svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &testKey,\n\t})\n\tactive := false\n\tif currentModel.Status != nil && strings.Compare(*currentModel.Status, \"ACTIVE\") == 0 {\n\t\tactive = true\n\t}\n\tres, err := iotSvc.CreateKeysAndCertificate(&iot.CreateKeysAndCertificateInput{\n\t\tSetAsActive: &active,\n\t})\n\n\tif err != nil {\n\t\taerr, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tfmt.Printf(\"%v\", aerr)\n\t\t}\n\t\tresponse := handler.ProgressEvent{\n\t\t\tOperationStatus: handler.Failed,\n\t\t\tMessage: fmt.Sprintf(\"Failed: %s\", aerr.Error()),\n\t\t}\n\t\treturn response, nil\n\t}\n\n\tvar key string\n\tkey = fmt.Sprintf(\"%s.pem\", *res.CertificateId)\n\t_, err = s3Svc.PutObject(&s3.PutObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &key,\n\t\tBody: strings.NewReader(*res.CertificatePem),\n\t})\n\tkey = fmt.Sprintf(\"%s.key\", *res.CertificateId)\n\t_, err = s3Svc.PutObject(&s3.PutObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &key,\n\t\tBody: strings.NewReader(*res.KeyPair.PrivateKey),\n\t})\n\tcurrentModel.Arn = res.CertificateArn\n\tcurrentModel.Id = res.CertificateId\n\n\tresponse := handler.ProgressEvent{\n\t\tOperationStatus: handler.Success,\n\t\tMessage: \"Created certificate\",\n\t\tResourceModel: currentModel,\n\t}\n\treturn response, nil\n}", "func initAWSSvc() *s3.S3 {\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tsdkLoadConfig := os.Getenv(\"AWS_SDK_LOAD_CONFIG\")\n\tif sdkLoadConfig != \"true\" {\n\t\tlog.Fatal(`Env var \"AWS_SDK_LOAD_CONFIG\" needs to be true to read credentials.\\n\\n Run \"export AWS_SDK_LOAD_CONFIG=true\" to fix this. Aborting run.`)\n\t}\n\n\treturn s3.New(sess)\n}", "func (c *config) createCognitoService() error {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't create AWS cfg. Error: %s\", err.Error())\n\t}\n\n\tc.svc = cognitoidentityprovider.New(cfg)\n\treturn nil\n}", "func newAwsServiceDiscoveryServices(c *TrussleV1Client, namespace string) *awsServiceDiscoveryServices {\n\treturn &awsServiceDiscoveryServices{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func main() {\n\tif len(os.Args) != 3 {\n\t\texitErrorf(\"AMI ID and Instance Type are required\"+\n\t\t\t\"\\nUsage: %s image_id instance_type\", os.Args[0])\n\t}\n\n\n\t//Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"eu-west-1\")}, )\n\tsvc := ec2.New(sess)\n\tif err != nil {\n\t\texitErrorf(\"Error creating session, %v\", err)\n\t}\n\n}", "func (c *Config) CreateSTS(sts *appsv1.StatefulSet, commonConfiguration *CommonConfiguration, instanceType string, request reconcile.Request, scheme *runtime.Scheme, reconcileClient client.Client) error {\n\treturn CreateSTS(sts, commonConfiguration, instanceType, request, scheme, reconcileClient)\n}", "func NewSTS() *STSBuilder {\n\treturn &STSBuilder{}\n}", "func NewCreateServiceInput(config map[string]interface{}) (*ecs.CreateServiceInput, error){\n\t// TODO: may make a struct for this to take... then again, that basically becomes UpdateServiceInput...\n\t// but maybe can simplify it slightly or something.\n\t// TODO: Should this be fargate specific or should this just be NewCreateServiceInput and the fargate or not\n\t// is more dynamic?\n\n\t// TODO: support ClientToken!\n\n\tserviceName := aws.String(config[\"name\"].(string))\n\t// https://docs.aws.amazon.com/sdk-for-go/api/service/ecs/#UpdateServiceInput\n\tinput := &ecs.CreateServiceInput{ServiceName: serviceName}\n\n\tif taskDef, ok := config[\"task_definition\"]; ok {\n\t\tinput = input.SetTaskDefinition(taskDef.(string)) // seems to be not required - perhaps can update things without changing the task def.\n\t}\n\n\tif cluster, ok := config[\"cluster\"]; ok {\n\t\tinput = input.SetCluster(cluster.(string))\n\t}\n\n\tif desiredCount, ok := config[\"desired_count\"]; ok {\n\t\tinput = input.SetDesiredCount(desiredCount.(int64))\n\t}\n\n\tif launchType, ok := config[\"launch_type\"]; ok {\n\t\tinput = input.SetLaunchType(launchType.(string))\n\t}\n\n\tdeploymentController := &ecs.DeploymentController{}\n\tif dc, ok := config[\"deployment_controller\"]; ok {\n\t\tdeploymentController = deploymentController.SetType(dc.(string))\n\t} else {\n\t\tdeploymentController = deploymentController.SetType(\"ECS\")\n\t}\n\tinput = input.SetDeploymentController(deploymentController)\n\n\tawsVpcConfig := &ecs.AwsVpcConfiguration{}\n\t// Supported for fargate, not for ec2 launch type\n\tif assignPublicIp, ok := config[\"assign_public_ip\"]; ok {\n\t\tawsVpcConfig = awsVpcConfig.SetAssignPublicIp(assignPublicIp.(string))\n\t}\n\n\tif securityGroupIds, ok := config[\"security_groups\"]; ok {\n\t\tg := securityGroupIds.([]interface{})\n\t\tsecurityGroups := make([]*string, len(g))\n\t\tfor i := range g {\n\t\t\tgroupId := securityGroupIds.([]interface{})[i].(string)\n\t\t securityGroups[i] = &groupId\n\t\t}\n\t\tawsVpcConfig = awsVpcConfig.SetSecurityGroups(securityGroups)\n\t}\n\n\t// TODO: assumptions made here about vpc config assuming that this is for a Fargate service\n\t// TODO: support non-fargate cleanly?\n\tif subnetIds, ok := config[\"subnets\"]; ok {\n\t\ts := subnetIds.([]interface{})\n\t\tsubnets := make([]*string, len(s))\n\t\tfor i := range s {\n\t\t\tsubnetId := subnetIds.([]interface{})[i].(string)\n\t\t subnets[i] = &subnetId\n\t\t}\n\t\tawsVpcConfig = awsVpcConfig.SetSubnets(subnets)\n\t}\n\n\tnetworkConfig := ecs.NetworkConfiguration{AwsvpcConfiguration: awsVpcConfig}\n\tinput.SetNetworkConfiguration(&networkConfig)\n\n\t// TODO: other otpions\n\t// fmt.Printf(\"\\n\\nINPUT: %v\\n\\n\", input)\n\treturn input, input.Validate()\n}", "func newNs(ctx context.Context, cl client.Client, name string) error {\n\tns := &corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t}\n\tif err := cl.Create(ctx, ns); err != nil {\n\t\tif !errors.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"failed to create namespace %s: %v\", ns.Name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func newAWSKMSClient(sess client.ConfigProvider, region, arn string) AWSKMSClient {\n\treturn AWSKMSClient{\n\t\tKMS: clientFactory(sess, aws.NewConfig().WithRegion(region)),\n\t\tRegion: region,\n\t\tARN: arn,\n\t}\n}", "func newClient(ctx context.Context, cfg vcConfig) (*vsClient, error) {\n\tu := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: cfg.server,\n\t\tPath: \"sdk\",\n\t}\n\n\tu.User = url.UserPassword(cfg.user, cfg.password)\n\tinsecure := cfg.insecure\n\n\tgc, err := govmomi.NewClient(ctx, &u, insecure)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connecting to vSphere API: %w\", err)\n\t}\n\n\trc := rest.NewClient(gc.Client)\n\ttm := tags.NewManager(rc)\n\n\tvsc := vsClient{\n\t\tgovmomi: gc,\n\t\trest: rc,\n\t\ttagManager: tm,\n\t}\n\n\terr = vsc.rest.Login(ctx, u.User)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"logging into rest api: %w\", err)\n\t}\n\n\treturn &vsc, nil\n}", "func (sdk *SDK) createNode(req *CreateInstanceRequest) (*cloudsvr.CloudNode, error) {\n\tvar err error\n\n\t// create ecs firstly\n\tecsID, err := sdk.NewEcs(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs create failed: %v\", err)\n\t}\n\tlog.Printf(\"aliyun ecs %s created at %s\", ecsID, req.RegionID)\n\n\t// if create succeed, but other operations failed, clean up the newly created ecs instance to prevent garbage left\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"aliyun cloud node creation failed, clean up the newly created ecs instance %s. [%v]\", ecsID, err)\n\t\t\tsdk.RemoveNode(&cloudsvr.CloudNode{ID: ecsID, RegionOrZoneID: req.RegionID})\n\t\t}\n\t}()\n\n\t// now ecs is stopped, we assign an public ip to it\n\tip, err := sdk.AssignEcsPublicIP(ecsID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s assign public ip failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s assgined public ipaddress %s\", ecsID, ip)\n\n\t// start ecs\n\tif err = sdk.StartEcs(ecsID); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s start failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s starting\", ecsID)\n\n\t// wait ecs to be running\n\tif err = sdk.WaitEcs(req.RegionID, ecsID, \"Running\", time.Second*300); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s waitting to be running failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s is Running now\", ecsID)\n\n\treturn &cloudsvr.CloudNode{\n\t\tID: ecsID,\n\t\tRegionOrZoneID: req.RegionID,\n\t\tInstanceType: req.InstanceType,\n\t\tCloudSvrType: sdk.Type(),\n\t\tIPAddr: ip,\n\t\tPort: \"22\",\n\t\tUser: \"root\",\n\t\tPassword: req.Password,\n\t}, nil\n}", "func newAWSCommand() *cobra.Command {\n\tvar (\n\t\tclusterName string\n\t\troleARN string\n\t)\n\tvar command = &cobra.Command{\n\t\tUse: \"aws\",\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tctx := c.Context()\n\n\t\t\tpresignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, getSignedRequest)\n\t\t\terrors.CheckError(err)\n\t\t\ttoken := v1Prefix + base64.RawURLEncoding.EncodeToString([]byte(presignedURLString))\n\t\t\t// Set token expiration to 1 minute before the presigned URL expires for some cushion\n\t\t\ttokenExpiration := time.Now().Local().Add(presignedURLExpiration - 1*time.Minute)\n\t\t\t_, _ = fmt.Fprint(os.Stdout, formatJSON(token, tokenExpiration))\n\t\t},\n\t}\n\tcommand.Flags().StringVar(&clusterName, \"cluster-name\", \"\", \"AWS Cluster name\")\n\tcommand.Flags().StringVar(&roleARN, \"role-arn\", \"\", \"AWS Role ARN\")\n\treturn command\n}", "func main() {\n\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\texitErrorf(\"failed to load config, %v\", err)\n\t}\n\n\tsagemakerSvc := sagemaker.New(cfg)\n\n\t//Define intput variables\n\trole := \"arn:aws:iam::xxxxxx:role/<name of role>\"\n\tname := \"k-means-in-sagemaker\"\n\tMaxRuntimeInSeconds := int64(60 * 60)\n\tS3OutputPath := \"s3://<bucket where your model artifact will be saved\"\n\tInstanceCount := int64(2)\n\tVolumeSizeInGB := int64(75)\n\tTrainingInstanceType := sagemaker.TrainingInstanceType(\"ml.c4.8xlarge\")\n\tTrainingImage := \"174872318107.dkr.ecr.us-west-2.amazonaws.com/kmeans:1\"\n\tTrainingInputMode := sagemaker.TrainingInputMode(\"File\")\n\n\tChannelName := \"train\"\n\tS3DataDistributionType := sagemaker.S3DataDistribution(\"FullyReplicated\")\n\tS3DataType := sagemaker.S3DataType(\"S3Prefix\")\n\tS3Uri := \"s3://<bucket where the input data is available>\"\n\n\tHyperParameters := map[string]string{\n\t\t\"k\": \"10\",\n\t\t\"feature_dim\": \"784\",\n\t\t\"mini_batch_size\": \"500\",\n\t}\n\n\tparams := &sagemaker.CreateTrainingJobInput{\n\t\tRoleArn: &role,\n\t\tTrainingJobName: &name,\n\n\t\tStoppingCondition: &sagemaker.StoppingCondition{\n\t\t\tMaxRuntimeInSeconds: &MaxRuntimeInSeconds,\n\t\t},\n\n\t\tOutputDataConfig: &sagemaker.OutputDataConfig{\n\t\t\tS3OutputPath: &S3OutputPath,\n\t\t},\n\n\t\tResourceConfig: &sagemaker.ResourceConfig{\n\t\t\tInstanceCount: &InstanceCount,\n\t\t\tVolumeSizeInGB: &VolumeSizeInGB,\n\t\t\tInstanceType: TrainingInstanceType,\n\t\t},\n\n\t\tAlgorithmSpecification: &sagemaker.AlgorithmSpecification{\n\t\t\tTrainingImage: &TrainingImage,\n\t\t\tTrainingInputMode: TrainingInputMode,\n\t\t},\n\n\t\tInputDataConfig: []sagemaker.Channel{\n\t\t\t{\n\t\t\t\tChannelName: &ChannelName,\n\t\t\t\tDataSource: &sagemaker.DataSource{\n\t\t\t\t\tS3DataSource: &sagemaker.S3DataSource{\n\t\t\t\t\t\tS3DataDistributionType: S3DataDistributionType,\n\t\t\t\t\t\tS3DataType: S3DataType,\n\t\t\t\t\t\tS3Uri: &S3Uri,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHyperParameters: HyperParameters,\n\t}\n\n\treq := sagemakerSvc.CreateTrainingJobRequest(params)\n\n\tresp, err := req.Send(context.TODO())\n\tif err != nil {\n\t\texitErrorf(\"Error creating TrainingJob, %v\", err)\n\t\treturn\n\t}\n\n\tfmt.Println(resp)\n}", "func addStagedSigner(notaryRepo client.Repository, newSigner data.RoleName, signerKeys []data.PublicKey) {\n\t// create targets/<username>\n\tnotaryRepo.AddDelegationRoleAndKeys(newSigner, signerKeys)\n\tnotaryRepo.AddDelegationPaths(newSigner, []string{\"\"})\n\n\t// create targets/releases\n\tnotaryRepo.AddDelegationRoleAndKeys(trust.ReleasesRole, signerKeys)\n\tnotaryRepo.AddDelegationPaths(trust.ReleasesRole, []string{\"\"})\n}", "func NewStsPolicy()(*StsPolicy) {\n m := &StsPolicy{\n PolicyBase: *NewPolicyBase(),\n }\n odataTypeValue := \"#microsoft.graph.stsPolicy\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func NewIntegrationSts(ctx *pulumi.Context,\n\tname string, args *IntegrationStsArgs, opts ...pulumi.ResourceOption) (*IntegrationSts, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ClientEmail == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ClientEmail'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource IntegrationSts\n\terr := ctx.RegisterResource(\"datadog:gcp/integrationSts:IntegrationSts\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (rm *resourceManager) sdkCreate(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\tinput, err := rm.newCreateRequestPayload(ctx, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.CreateReservedInstancesListingWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"CREATE\", \"CreateReservedInstancesListing\", respErr)\n\tif respErr != nil {\n\t\treturn nil, respErr\n\t}\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.ReservedInstancesListings != nil {\n\t\tf0 := []*svcapitypes.ReservedInstancesListing_SDK{}\n\t\tfor _, f0iter := range resp.ReservedInstancesListings {\n\t\t\tf0elem := &svcapitypes.ReservedInstancesListing_SDK{}\n\t\t\tif f0iter.ClientToken != nil {\n\t\t\t\tf0elem.ClientToken = f0iter.ClientToken\n\t\t\t}\n\t\t\tif f0iter.CreateDate != nil {\n\t\t\t\tf0elem.CreateDate = &metav1.Time{*f0iter.CreateDate}\n\t\t\t}\n\t\t\tif f0iter.InstanceCounts != nil {\n\t\t\t\tf0elemf2 := []*svcapitypes.InstanceCount{}\n\t\t\t\tfor _, f0elemf2iter := range f0iter.InstanceCounts {\n\t\t\t\t\tf0elemf2elem := &svcapitypes.InstanceCount{}\n\t\t\t\t\tif f0elemf2iter.InstanceCount != nil {\n\t\t\t\t\t\tf0elemf2elem.InstanceCount = f0elemf2iter.InstanceCount\n\t\t\t\t\t}\n\t\t\t\t\tif f0elemf2iter.State != nil {\n\t\t\t\t\t\tf0elemf2elem.State = f0elemf2iter.State\n\t\t\t\t\t}\n\t\t\t\t\tf0elemf2 = append(f0elemf2, f0elemf2elem)\n\t\t\t\t}\n\t\t\t\tf0elem.InstanceCounts = f0elemf2\n\t\t\t}\n\t\t\tif f0iter.PriceSchedules != nil {\n\t\t\t\tf0elemf3 := []*svcapitypes.PriceSchedule{}\n\t\t\t\tfor _, f0elemf3iter := range f0iter.PriceSchedules {\n\t\t\t\t\tf0elemf3elem := &svcapitypes.PriceSchedule{}\n\t\t\t\t\tif f0elemf3iter.Active != nil {\n\t\t\t\t\t\tf0elemf3elem.Active = f0elemf3iter.Active\n\t\t\t\t\t}\n\t\t\t\t\tif f0elemf3iter.CurrencyCode != nil {\n\t\t\t\t\t\tf0elemf3elem.CurrencyCode = f0elemf3iter.CurrencyCode\n\t\t\t\t\t}\n\t\t\t\t\tif f0elemf3iter.Price != nil {\n\t\t\t\t\t\tf0elemf3elem.Price = f0elemf3iter.Price\n\t\t\t\t\t}\n\t\t\t\t\tif f0elemf3iter.Term != nil {\n\t\t\t\t\t\tf0elemf3elem.Term = f0elemf3iter.Term\n\t\t\t\t\t}\n\t\t\t\t\tf0elemf3 = append(f0elemf3, f0elemf3elem)\n\t\t\t\t}\n\t\t\t\tf0elem.PriceSchedules = f0elemf3\n\t\t\t}\n\t\t\tif f0iter.ReservedInstancesId != nil {\n\t\t\t\tf0elem.ReservedInstancesID = f0iter.ReservedInstancesId\n\t\t\t}\n\t\t\tif f0iter.ReservedInstancesListingId != nil {\n\t\t\t\tf0elem.ReservedInstancesListingID = f0iter.ReservedInstancesListingId\n\t\t\t}\n\t\t\tif f0iter.Status != nil {\n\t\t\t\tf0elem.Status = f0iter.Status\n\t\t\t}\n\t\t\tif f0iter.StatusMessage != nil {\n\t\t\t\tf0elem.StatusMessage = f0iter.StatusMessage\n\t\t\t}\n\t\t\tif f0iter.Tags != nil {\n\t\t\t\tf0elemf8 := []*svcapitypes.Tag{}\n\t\t\t\tfor _, f0elemf8iter := range f0iter.Tags {\n\t\t\t\t\tf0elemf8elem := &svcapitypes.Tag{}\n\t\t\t\t\tif f0elemf8iter.Key != nil {\n\t\t\t\t\t\tf0elemf8elem.Key = f0elemf8iter.Key\n\t\t\t\t\t}\n\t\t\t\t\tif f0elemf8iter.Value != nil {\n\t\t\t\t\t\tf0elemf8elem.Value = f0elemf8iter.Value\n\t\t\t\t\t}\n\t\t\t\t\tf0elemf8 = append(f0elemf8, f0elemf8elem)\n\t\t\t\t}\n\t\t\t\tf0elem.Tags = f0elemf8\n\t\t\t}\n\t\t\tif f0iter.UpdateDate != nil {\n\t\t\t\tf0elem.UpdateDate = &metav1.Time{*f0iter.UpdateDate}\n\t\t\t}\n\t\t\tf0 = append(f0, f0elem)\n\t\t}\n\t\tko.Status.ReservedInstancesListings = f0\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\treturn &resource{ko}, nil\n}", "func (d *driver) getSVC() (*s3.S3, error) {\n\tif s3Service != nil {\n\t\treturn s3Service, nil\n\t}\n\n\tcfg, err := clusterconfig.GetAWSConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsess, err := session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(cfg.Storage.S3.AccessKey, cfg.Storage.S3.SecretKey, \"\"),\n\t\tRegion: &cfg.Storage.S3.Region,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts3Service := s3.New(sess)\n\n\treturn s3Service, nil\n\n}", "func NewAWSClient(config *types.Configuration, stats *types.Statistics, statsdClient, dogstatsdClient *statsd.Client) (*Client, error) {\r\n\r\n\tif config.AWS.AccessKeyID != \"\" && config.AWS.SecretAccessKey != \"\" && config.AWS.Region != \"\" {\r\n\t\tos.Setenv(\"AWS_ACCESS_KEY_ID\", config.AWS.AccessKeyID)\r\n\t\tos.Setenv(\"AWS_SECRET_ACCESS_KEY\", config.AWS.SecretAccessKey)\r\n\t\tos.Setenv(\"AWS_DEFAULT_REGION\", config.AWS.Region)\r\n\t}\r\n\r\n\tsess, err := session.NewSession(&aws.Config{\r\n\t\tRegion: aws.String(config.AWS.Region)},\r\n\t)\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS - %v\\n\", \"Error while creating AWS Session\")\r\n\t\treturn nil, errors.New(\"Error while creating AWS Session\")\r\n\t}\r\n\r\n\t_, err = sts.New(session.New()).GetCallerIdentity(&sts.GetCallerIdentityInput{})\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS - %v\\n\", \"Error while getting AWS Token\")\r\n\t\treturn nil, errors.New(\"Error while getting AWS Token\")\r\n\t}\r\n\r\n\tvar endpointURL *url.URL\r\n\tendpointURL, err = url.Parse(config.AWS.SQS.URL)\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS SQS - %v\\n\", err.Error())\r\n\t\treturn nil, ErrClientCreation\r\n\t}\r\n\r\n\treturn &Client{\r\n\t\tOutputType: \"AWS\",\r\n\t\tEndpointURL: endpointURL,\r\n\t\tConfig: config,\r\n\t\tAWSSession: sess,\r\n\t\tStats: stats,\r\n\t\tStatsdClient: statsdClient,\r\n\t\tDogstatsdClient: dogstatsdClient,\r\n\t}, nil\r\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var bucket NewBucket\n err = decoder.Decode(&bucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n\n // Add the necessary headers for Metadata Search and Access During Outage\n createBucketHeaders := map[string][]string{}\n createBucketHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n createBucketHeaders[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n createBucketHeaders[\"x-emc-metadata-search\"] = []string{\"ObjectName,x-amz-meta-image-width;Integer,x-amz-meta-image-height;Integer,x-amz-meta-gps-latitude;Decimal,x-amz-meta-gps-longitude;Decimal\"}\n\n createBucketResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/\", createBucketHeaders, \"\")\n\n // Enable CORS after the bucket creation to allow the web browser to send requests directly to ECS\n if createBucketResponse.Code == 200 {\n enableBucketCorsHeaders := map[string][]string{}\n enableBucketCorsHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n corsConfiguration := `\n <CORSConfiguration>\n <CORSRule>\n <AllowedOrigin>*</AllowedOrigin>\n <AllowedHeader>*</AllowedHeader>\n <ExposeHeader>x-amz-meta-image-width</ExposeHeader>\n <ExposeHeader>x-amz-meta-image-height</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-latitude</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-longitude</ExposeHeader>\n <AllowedMethod>HEAD</AllowedMethod>\n <AllowedMethod>GET</AllowedMethod>\n <AllowedMethod>PUT</AllowedMethod>\n <AllowedMethod>POST</AllowedMethod>\n <AllowedMethod>DELETE</AllowedMethod>\n </CORSRule>\n </CORSConfiguration>\n `\n enableBucketCorsResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/?cors\", enableBucketCorsHeaders, corsConfiguration)\n if enableBucketCorsResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, struct {\n CorsConfiguration string `json:\"cors_configuration\"`\n Bucket string `json:\"bucket\"`\n } {\n CorsConfiguration: corsConfiguration,\n Bucket: bucket.Name,\n })\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket created, but CORS can't be enabled\"}\n }\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket can't be created\"}\n }\n return nil\n}", "func newS3Storage(backend *backup.S3) (*S3Storage, error) {\n\tqs := *backend\n\tawsConfig := aws.NewConfig().\n\t\tWithMaxRetries(maxRetries).\n\t\tWithS3ForcePathStyle(qs.ForcePathStyle).\n\t\tWithRegion(qs.Region)\n\tif qs.Endpoint != \"\" {\n\t\tawsConfig.WithEndpoint(qs.Endpoint)\n\t}\n\tvar cred *credentials.Credentials\n\tif qs.AccessKey != \"\" && qs.SecretAccessKey != \"\" {\n\t\tcred = credentials.NewStaticCredentials(qs.AccessKey, qs.SecretAccessKey, \"\")\n\t}\n\tif cred != nil {\n\t\tawsConfig.WithCredentials(cred)\n\t}\n\t// awsConfig.WithLogLevel(aws.LogDebugWithSigning)\n\tawsSessionOpts := session.Options{\n\t\tConfig: *awsConfig,\n\t}\n\tses, err := session.NewSessionWithOptions(awsSessionOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !sendCredential {\n\t\t// Clear the credentials if exists so that they will not be sent to TiKV\n\t\tbackend.AccessKey = \"\"\n\t\tbackend.SecretAccessKey = \"\"\n\t} else if ses.Config.Credentials != nil {\n\t\tif qs.AccessKey == \"\" || qs.SecretAccessKey == \"\" {\n\t\t\tv, cerr := ses.Config.Credentials.Get()\n\t\t\tif cerr != nil {\n\t\t\t\treturn nil, cerr\n\t\t\t}\n\t\t\tbackend.AccessKey = v.AccessKeyID\n\t\t\tbackend.SecretAccessKey = v.SecretAccessKey\n\t\t}\n\t}\n\n\tc := s3.New(ses)\n\terr = checkS3Bucket(c, qs.Bucket)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Bucket %s is not accessible: %v\", qs.Bucket, err)\n\t}\n\n\tqs.Prefix += \"/\"\n\treturn &S3Storage{\n\t\tsession: ses,\n\t\tsvc: c,\n\t\toptions: &qs,\n\t}, nil\n}", "func GetSts(t *testing.T, k8client client.Client, stsName string) (*appsv1.StatefulSet, error) {\n\tsts := &appsv1.StatefulSet{}\n\tns := \"default\"\n\terr := k8client.Get(goctx.TODO(), types.NamespacedName{Namespace: ns, Name: stsName}, sts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sts doesnt exist: %v\", err)\n\t}\n\n\treturn sts, nil\n}", "func newStorer(pluginName string, storagePath string, gcpProjectID string, gcpCredentialsFile string) (storer store.GlobalSiloStringStorer, err error) {\n\tif gcpProjectID != \"\" {\n\t\treturn newDatastoreStorerWithInMemoryCache(pluginName, gcpProjectID, gcpCredentialsFile)\n\t}\n\n\treturn store.NewLevelDB(pluginName, storagePath)\n}", "func newServices(\n\tsettingsFile string,\n\tswanAccess Access,\n\tswiftAccess swift.Access,\n\towidAccess owid.Access) *services {\n\tvar swiftStore swift.Store\n\tvar owidStore owid.Store\n\n\t// Use the file provided to get the SWIFT settings.\n\tswiftConfig := swift.NewConfig(settingsFile)\n\terr := swiftConfig.Validate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Use the file provided to get the OWID settings.\n\towidConfig := owid.NewConfig(settingsFile)\n\terr = owidConfig.Validate()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Link to the SWIFT storage.\n\tswiftStore = swift.NewStore(swiftConfig)\n\n\t// Link to the OWID storage.\n\towidStore = owid.NewStore(owidConfig)\n\n\t// Get the default browser detector.\n\tb, err := swift.NewBrowserRegexes()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create the swan configuration.\n\tc := newConfig(settingsFile)\n\n\t// Get the SWIFT access node for the SWAN network. Log any errors rather\n\t// than panic because it may be that a network has yet to be established\n\t// for SWAN in the storage tables.\n\tan, err := swiftStore.GetAccessNode(c.Network)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tlog.Printf(\"Has a '%s' network been created?\", c.Network)\n\t}\n\n\t// Return the services.\n\treturn &services{\n\t\tc,\n\t\tswift.NewServices(swiftConfig, swiftStore, swiftAccess, b),\n\t\towid.NewServices(owidConfig, owidStore, owidAccess),\n\t\tan,\n\t\tswanAccess}\n}", "func New(cfg *eksconfig.Config) (*Tester, error) {\n\tif err := cfg.ValidateAndSetDefaults(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlcfg := logutil.AddOutputPaths(logutil.DefaultZapLoggerConfig, cfg.LogOutputs, cfg.LogOutputs)\n\tlcfg.Level = zap.NewAtomicLevelAt(logutil.ConvertToZapLevel(cfg.LogLevel))\n\tlg, err := lcfg.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = fileutil.EnsureExecutable(cfg.AWSCLIPath); err != nil {\n\t\t// file may be already executable while the process does not own the file/directory\n\t\t// ref. https://github.com/aws/aws-k8s-tester/issues/66\n\t\tlg.Error(\"failed to ensure executable\", zap.Error(err))\n\t}\n\n\t// aws --version\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tvo, verr := exec.New().CommandContext(\n\t\tctx,\n\t\tcfg.AWSCLIPath,\n\t\t\"--version\",\n\t).CombinedOutput()\n\tcancel()\n\tif verr != nil {\n\t\treturn nil, fmt.Errorf(\"'aws --version' failed (output %q, error %v)\", string(vo), verr)\n\t}\n\tlg.Info(\n\t\t\"aws version\",\n\t\tzap.String(\"aws-cli-path\", cfg.AWSCLIPath),\n\t\tzap.String(\"aws-version\", string(vo)),\n\t)\n\n\tlg.Info(\"mkdir\", zap.String(\"kubectl-path-dir\", filepath.Dir(cfg.KubectlPath)))\n\tif err := os.MkdirAll(filepath.Dir(cfg.KubectlPath), 0700); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create %q (%v)\", filepath.Dir(cfg.KubectlPath), err)\n\t}\n\tlg.Info(\"downloading kubectl\", zap.String(\"kubectl-path\", cfg.KubectlPath))\n\tif err := os.RemoveAll(cfg.KubectlPath); err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := os.Create(cfg.KubectlPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create %q (%v)\", cfg.KubectlPath, err)\n\t}\n\tcfg.KubectlPath = f.Name()\n\tcfg.KubectlPath, _ = filepath.Abs(cfg.KubectlPath)\n\tif err := httpDownloadFile(lg, cfg.KubectlDownloadURL, f); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to close kubectl %v\", err)\n\t}\n\tif err := fileutil.EnsureExecutable(cfg.KubectlPath); err != nil {\n\t\t// file may be already executable while the process does not own the file/directory\n\t\t// ref. https://github.com/aws/aws-k8s-tester/issues/66\n\t\tlg.Error(\"failed to ensure executable\", zap.Error(err))\n\t}\n\t// kubectl version --client=true\n\tctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)\n\tvo, verr = exec.New().CommandContext(\n\t\tctx,\n\t\tcfg.KubectlPath,\n\t\t\"version\",\n\t\t\"--client=true\",\n\t).CombinedOutput()\n\tcancel()\n\tif verr != nil {\n\t\treturn nil, fmt.Errorf(\"'kubectl version' failed (output %q, error %v)\", string(vo), verr)\n\t}\n\tlg.Info(\n\t\t\"kubectl version\",\n\t\tzap.String(\"kubectl-path\", cfg.KubectlPath),\n\t\tzap.String(\"kubectl-version\", string(vo)),\n\t)\n\n\tif cfg.AWSIAMAuthenticatorPath != \"\" && cfg.AWSIAMAuthenticatorDownloadURL != \"\" {\n\t\tlg.Info(\"mkdir\", zap.String(\"aws-iam-authenticator-path-dir\", filepath.Dir(cfg.AWSIAMAuthenticatorPath)))\n\t\tif err := os.MkdirAll(filepath.Dir(cfg.AWSIAMAuthenticatorPath), 0700); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not create %q (%v)\", filepath.Dir(cfg.AWSIAMAuthenticatorPath), err)\n\t\t}\n\t\tlg.Info(\"downloading aws-iam-authenticator\", zap.String(\"aws-iam-authenticator-path\", cfg.AWSIAMAuthenticatorPath))\n\t\tif err := os.RemoveAll(cfg.AWSIAMAuthenticatorPath); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf, err := os.Create(cfg.AWSIAMAuthenticatorPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create %q (%v)\", cfg.AWSIAMAuthenticatorPath, err)\n\t\t}\n\t\tcfg.AWSIAMAuthenticatorPath = f.Name()\n\t\tcfg.AWSIAMAuthenticatorPath, _ = filepath.Abs(cfg.AWSIAMAuthenticatorPath)\n\t\tif err := httpDownloadFile(lg, cfg.AWSIAMAuthenticatorDownloadURL, f); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to close aws-iam-authenticator %v\", err)\n\t\t}\n\t\tif err := fileutil.EnsureExecutable(cfg.AWSIAMAuthenticatorPath); err != nil {\n\t\t\t// file may be already executable while the process does not own the file/directory\n\t\t\t// ref. https://github.com/aws/aws-k8s-tester/issues/66\n\t\t\tlg.Error(\"failed to ensure executable\", zap.Error(err))\n\t\t}\n\t\t// aws-iam-authenticator version\n\t\tctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)\n\t\tvo, verr = exec.New().CommandContext(\n\t\t\tctx,\n\t\t\tcfg.AWSIAMAuthenticatorPath,\n\t\t\t\"version\",\n\t\t).CombinedOutput()\n\t\tcancel()\n\t\tif verr != nil {\n\t\t\treturn nil, fmt.Errorf(\"'aws-iam-authenticator version' failed (output %q, error %v)\", string(vo), verr)\n\t\t}\n\t\tlg.Info(\n\t\t\t\"aws-iam-authenticator version\",\n\t\t\tzap.String(\"aws-iam-authenticator-path\", cfg.AWSIAMAuthenticatorPath),\n\t\t\tzap.String(\"aws-iam-authenticator-version\", string(vo)),\n\t\t)\n\t}\n\n\tts := &Tester{\n\t\tstopCreationCh: make(chan struct{}),\n\t\tstopCreationChOnce: new(sync.Once),\n\t\tinterruptSig: make(chan os.Signal),\n\t\tlg: lg,\n\t\tcfg: cfg,\n\t\tdownMu: new(sync.Mutex),\n\t\tfetchLogsManagedNodeGroupMu: new(sync.RWMutex),\n\t}\n\tsignal.Notify(ts.interruptSig, syscall.SIGTERM, syscall.SIGINT)\n\n\tdefer ts.cfg.Sync()\n\n\tawsCfg := &awsapi.Config{\n\t\tLogger: ts.lg,\n\t\tDebugAPICalls: ts.cfg.LogLevel == \"debug\",\n\t\tRegion: ts.cfg.Region,\n\t}\n\tvar stsOutput *sts.GetCallerIdentityOutput\n\tts.awsSession, stsOutput, _, err = awsapi.New(awsCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tts.cfg.Status.AWSAccountID = *stsOutput.Account\n\n\tts.iamAPI = iam.New(ts.awsSession)\n\tts.ssmAPI = ssm.New(ts.awsSession)\n\tts.cfnAPI = cloudformation.New(ts.awsSession)\n\tts.ec2API = ec2.New(ts.awsSession)\n\tts.asgAPI = autoscaling.New(ts.awsSession)\n\tts.elbAPI = elb.New(ts.awsSession)\n\n\t// create a separate session for EKS (for resolver endpoint)\n\tts.eksSession, _, ts.cfg.Status.AWSCredentialPath, err = awsapi.New(&awsapi.Config{\n\t\tLogger: ts.lg,\n\t\tDebugAPICalls: ts.cfg.LogLevel == \"debug\",\n\t\tRegion: ts.cfg.Region,\n\t\tResolverURL: ts.cfg.Parameters.ClusterResolverURL,\n\t\tSigningName: ts.cfg.Parameters.ClusterSigningName,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tts.eksAPI = awseks.New(ts.eksSession)\n\n\t// reuse existing role\n\tif ts.cfg.Parameters.ClusterRoleARN != \"\" {\n\t\tts.lg.Info(\"reuse existing IAM role\", zap.String(\"cluster-role-arn\", ts.cfg.Parameters.ClusterRoleARN))\n\t\tts.cfg.Status.ClusterRoleARN = ts.cfg.Parameters.ClusterRoleARN\n\t}\n\n\treturn ts, nil\n}", "func newInstruments(registerer prometheus.Registerer) (*instruments, error) {\n\tapiCallsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallsTotal,\n\t\tHelp: \"Total number of SDK API calls from the customer's code to AWS services\",\n\t}, []string{labelService, labelOperation, labelStatusCode, labelErrorCode})\n\tapiCallDurationSeconds := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallDurationSeconds,\n\t\tHelp: \"Perceived latency from when your code makes an SDK call, includes retries\",\n\t}, []string{labelService, labelOperation})\n\tapiCallRetries := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallRetries,\n\t\tHelp: \"Number of times the SDK retried requests to AWS services for SDK API calls\",\n\t\tBuckets: []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t}, []string{labelService, labelOperation})\n\n\tapiRequestsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPIRequestsTotal,\n\t\tHelp: \"Total number of HTTP requests that the SDK made\",\n\t}, []string{labelService, labelOperation, labelStatusCode, labelErrorCode})\n\tapiRequestDurationSecond := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPIRequestDurationSeconds,\n\t\tHelp: \"Latency of an individual HTTP request to the service endpoint\",\n\t}, []string{labelService, labelOperation})\n\n\tif err := registerer.Register(apiCallsTotal); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiCallDurationSeconds); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiCallRetries); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiRequestsTotal); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiRequestDurationSecond); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &instruments{\n\t\tapiCallsTotal: apiCallsTotal,\n\t\tapiCallDurationSeconds: apiCallDurationSeconds,\n\t\tapiCallRetries: apiCallRetries,\n\t\tapiRequestsTotal: apiRequestsTotal,\n\t\tapiRequestDurationSecond: apiRequestDurationSecond,\n\t}, nil\n}", "func (p providerServices) EKSCtl() eksctl.EKSCtl {\n\treturn p.eksctl\n}", "func startService(sess *session.Session, subscription APISubscription, tasks []*string) error {\n\n\tsvc := ecs.New(sess)\n\n\tvar varClusterName = os.Getenv(\"CLUSTER_NAME\")\n\n\tfor _, task := range tasks {\n\t\tvTask := &ecs.StopTaskInput{\n\t\t\tCluster: aws.String(varClusterName),\n\t\t\tTask: task,\n\t\t}\n\t\twaiting := &ecs.DescribeTasksInput{\n\t\t\tCluster: varClusterName,\n\t\t\tTasks: tasks,\n\t\t}\n\n\t}\n\n\tupdateECS := &ecs.UpdateServiceInput{\n\t\tCluster: aws.String(varClusterName),\n\t\tDesiredCount: aws.Int64(1),\n\t\tForceNewDeployment: aws.Bool(true),\n\t\tService: aws.String(subscription.ID),\n\t}\n\t_, err := svc.UpdateService(updateECS)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase ecs.ErrCodeServerException:\n\t\t\t\tfmt.Println(ecs.ErrCodeServerException, aerr.Error())\n\t\t\tcase ecs.ErrCodeClientException:\n\t\t\t\tfmt.Println(ecs.ErrCodeClientException, aerr.Error())\n\t\t\tcase ecs.ErrCodeInvalidParameterException:\n\t\t\t\tfmt.Println(ecs.ErrCodeInvalidParameterException, aerr.Error())\n\t\t\tcase ecs.ErrCodeClusterNotFoundException:\n\t\t\t\tfmt.Println(ecs.ErrCodeClusterNotFoundException, aerr.Error())\n\t\t\tcase ecs.ErrCodeServiceNotFoundException:\n\t\t\t\tfmt.Println(ecs.ErrCodeServiceNotFoundException, aerr.Error())\n\t\t\tcase ecs.ErrCodeServiceNotActiveException:\n\t\t\t\tfmt.Println(ecs.ErrCodeServiceNotActiveException, aerr.Error())\n\t\t\tcase ecs.ErrCodePlatformUnknownException:\n\t\t\t\tfmt.Println(ecs.ErrCodePlatformUnknownException, aerr.Error())\n\t\t\tcase ecs.ErrCodePlatformTaskDefinitionIncompatibilityException:\n\t\t\t\tfmt.Println(ecs.ErrCodePlatformTaskDefinitionIncompatibilityException, aerr.Error())\n\t\t\tcase ecs.ErrCodeAccessDeniedException:\n\t\t\t\tfmt.Println(ecs.ErrCodeAccessDeniedException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn err\n\t}\n\n\treturn err\n}", "func NewSAMSARAAPI() SAMSARAAPI {\r\n samsaraAPIClient := new(SAMSARAAPI_IMPL)\r\n samsaraAPIClient.config = configuration_pkg.NewCONFIGURATION()\r\n\r\n return samsaraAPIClient\r\n}", "func NewTeamsAsyncOperation()(*TeamsAsyncOperation) {\n m := &TeamsAsyncOperation{\n Entity: *NewEntity(),\n }\n return m\n}", "func (client JobClient) CreateSasTokenSender(req *http.Request) (future JobCreateSasTokenFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }", "func NewS3Service(accessKey string, secretKey string) (*S3Service,error) {\n return &S3Service{DEFAULT_S3_ENDPOINT, accessKey, secretKey, &http.Client{}}, nil\n}", "func newSandboxes(c *DevopsV1Client) *sandboxes {\n\treturn &sandboxes{\n\t\tclient: c.RESTClient(),\n\t}\n}", "func newStainlessService(context *onet.Context) (onet.Service, error) {\n\tservice := &Stainless{\n\t\tServiceProcessor: onet.NewServiceProcessor(context),\n\t}\n\n\tfor _, srv := range []interface{}{\n\t\tservice.Verify,\n\t\tservice.GenBytecode,\n\t\tservice.DeployContract,\n\t\tservice.ExecuteTransaction,\n\t\tservice.FinalizeTransaction,\n\t\tservice.Call,\n\t} {\n\t\terr := service.RegisterHandler(srv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn service, nil\n}", "func NewAWS(aws config.AWSConfig, bucket config.S3BucketConfig, noLocks, noVersioning bool) *AWS {\n\tif bucket.Bucket == \"\" {\n\t\treturn nil\n\t}\n\n\tsess := session.Must(session.NewSession())\n\tawsConfig := aws_sdk.NewConfig()\n\tvar creds *credentials.Credentials\n\tif len(aws.APPRoleArn) > 0 {\n\t\tlog.Debugf(\"Using %s role\", aws.APPRoleArn)\n\t\tcreds = stscreds.NewCredentials(sess, aws.APPRoleArn, func(p *stscreds.AssumeRoleProvider) {\n\t\t\tif aws.ExternalID != \"\" {\n\t\t\t\tp.ExternalID = aws_sdk.String(aws.ExternalID)\n\t\t\t}\n\t\t})\n\t} else {\n\t\tif aws.AccessKey == \"\" || aws.SecretAccessKey == \"\" {\n\t\t\tlog.Fatal(\"Missing AccessKey or SecretAccessKey for AWS provider. Please check your configuration and retry\")\n\t\t}\n\t\tcreds = credentials.NewStaticCredentials(aws.AccessKey, aws.SecretAccessKey, aws.SessionToken)\n\t}\n\tawsConfig.WithCredentials(creds)\n\n\tif e := aws.Endpoint; e != \"\" {\n\t\tawsConfig.WithEndpoint(e)\n\t}\n\tif e := aws.Region; e != \"\" {\n\t\tawsConfig.WithRegion(e)\n\t}\n\tawsConfig.S3ForcePathStyle = &bucket.ForcePathStyle\n\n\treturn &AWS{\n\t\tsvc: s3.New(sess, awsConfig),\n\t\tbucket: bucket.Bucket,\n\t\tkeyPrefix: bucket.KeyPrefix,\n\t\tfileExtension: bucket.FileExtension,\n\t\tdynamoSvc: dynamodbiface.DynamoDBAPI(dynamodb.New(sess, awsConfig)),\n\t\tdynamoTable: aws.DynamoDBTable,\n\t\tnoLocks: noLocks,\n\t\tnoVersioning: noVersioning,\n\t}\n}", "func newSUT(sdk sdk.Contract) *publisher {\n\treturn newWithIOTA(\n\t\ttestInternal.FactoryRandomSeedString(),\n\t\ttest.FactoryRandomUint64(),\n\t\ttest.FactoryRandomUint64(),\n\t\tsdk,\n\t)\n}", "func (s *TestSuiteIAM) TestLDAPSTSServiceAccountsWithGroups(c *check) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tbucket := getRandomBucketName()\n\terr := s.client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})\n\tif err != nil {\n\t\tc.Fatalf(\"bucket create error: %v\", err)\n\t}\n\n\t// Create policy\n\tpolicy := \"mypolicy\"\n\tpolicyBytes := []byte(fmt.Sprintf(`{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:PutObject\",\n \"s3:GetObject\",\n \"s3:ListBucket\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::%s/*\"\n ]\n }\n ]\n}`, bucket))\n\terr = s.adm.AddCannedPolicy(ctx, policy, policyBytes)\n\tif err != nil {\n\t\tc.Fatalf(\"policy add error: %v\", err)\n\t}\n\n\tgroupDN := \"cn=projecta,ou=groups,ou=swengg,dc=min,dc=io\"\n\terr = s.adm.SetPolicy(ctx, policy, groupDN, true)\n\tif err != nil {\n\t\tc.Fatalf(\"Unable to set policy: %v\", err)\n\t}\n\n\tldapID := cr.LDAPIdentity{\n\t\tClient: s.TestSuiteCommon.client,\n\t\tSTSEndpoint: s.endPoint,\n\t\tLDAPUsername: \"dillon\",\n\t\tLDAPPassword: \"dillon\",\n\t}\n\n\tvalue, err := ldapID.Retrieve()\n\tif err != nil {\n\t\tc.Fatalf(\"Expected to generate STS creds, got err: %#v\", err)\n\t}\n\n\t// Check that the LDAP sts cred is actually working.\n\tminioClient, err := minio.New(s.endpoint, &minio.Options{\n\t\tCreds: cr.NewStaticV4(value.AccessKeyID, value.SecretAccessKey, value.SessionToken),\n\t\tSecure: s.secure,\n\t\tTransport: s.TestSuiteCommon.client.Transport,\n\t})\n\tif err != nil {\n\t\tc.Fatalf(\"Error initializing client: %v\", err)\n\t}\n\n\t// Validate that the client from sts creds can access the bucket.\n\tc.mustListObjects(ctx, minioClient, bucket)\n\n\t// Create an madmin client with user creds\n\tuserAdmClient, err := madmin.NewWithOptions(s.endpoint, &madmin.Options{\n\t\tCreds: cr.NewStaticV4(value.AccessKeyID, value.SecretAccessKey, value.SessionToken),\n\t\tSecure: s.secure,\n\t})\n\tif err != nil {\n\t\tc.Fatalf(\"Err creating user admin client: %v\", err)\n\t}\n\tuserAdmClient.SetCustomTransport(s.TestSuiteCommon.client.Transport)\n\n\t// Create svc acc\n\tcr := c.mustCreateSvcAccount(ctx, value.AccessKeyID, userAdmClient)\n\n\t// 1. Check that svc account appears in listing\n\tc.assertSvcAccAppearsInListing(ctx, userAdmClient, value.AccessKeyID, cr.AccessKey)\n\n\t// 2. Check that svc account info can be queried\n\tc.assertSvcAccInfoQueryable(ctx, userAdmClient, value.AccessKeyID, cr.AccessKey, true)\n\n\t// 3. Check S3 access\n\tc.assertSvcAccS3Access(ctx, s, cr, bucket)\n\n\t// 4. Check that svc account can restrict the policy, and that the\n\t// session policy can be updated.\n\tc.assertSvcAccSessionPolicyUpdate(ctx, s, userAdmClient, value.AccessKeyID, bucket)\n\n\t// 4. Check that service account's secret key and account status can be\n\t// updated.\n\tc.assertSvcAccSecretKeyAndStatusUpdate(ctx, s, userAdmClient, value.AccessKeyID, bucket)\n\n\t// 5. Check that service account can be deleted.\n\tc.assertSvcAccDeletion(ctx, s, userAdmClient, value.AccessKeyID, bucket)\n}", "func newEventSource(opts ...sourceOption) *v1alpha1.AWSSNSSource {\n\tsrc := &v1alpha1.AWSSNSSource{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: tNs,\n\t\t\tName: tName,\n\t\t},\n\t\tStatus: v1alpha1.AWSSNSSourceStatus{\n\t\t\tStatus: commonv1alpha1.Status{\n\t\t\t\tSourceStatus: duckv1.SourceStatus{\n\t\t\t\t\tSinkURI: tSinkURI,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// *reconcilerImpl.Reconcile calls this method before any reconciliation loop. Calling it here ensures that the\n\t// object is initialized in the same manner, and prevents tests from wrongly reporting unexpected status updates.\n\treconciler.PreProcessReconcile(context.Background(), src)\n\n\tfor _, opt := range opts {\n\t\topt(src)\n\t}\n\n\treturn src\n}", "func NewSEManager() *SEManager {\n return &SEManager{\n Engines: []SearchEngine{},\n Default: SearchEngine{\n URL: \"https://duckduckgo.com/?q=%s\",\n Title: \"DuckDuckGo\",\n Keyword: \"duck\",\n },\n }\n}", "func GenerateStakeNewTokensScript(env Environment) []byte {\n\tcode := assets.MustAssetString(stakeNewTokensFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func CreateServiceStatusRequest() (request *ServiceStatusRequest) {\nrequest = &ServiceStatusRequest{\nRpcRequest: &requests.RpcRequest{},\n}\nrequest.InitWithApiInfo(\"Yundun\", \"2015-04-16\", \"ServiceStatus\", \"yundun\", \"openAPI\")\nreturn\n}", "func Init(configPath ...string) {\n\tmgr = newAwsMgr(configPath...)\n}", "func main() {\n\t// 创建ecsClient实例\n\tecsClient, err := ecs.NewClientWithAccessKey(\n\t\t\"cn-shenzhen\", // 地域ID\n\t\t\"LTAI4FkfkEVNFGV7S3294foA\", // 您的Access Key ID\n\t\t\"fzotL4uCygsstuie6WzUs0tIRd1Lfy\") // 您的Access Key Secret\n\tif err != nil {\n\t\t// 异常处理\n\t\tpanic(err)\n\t}\n\t/*\n\t// 创建API请求并设置参数\n\trequest := ecs.CreateDescribeInstancesRequest()\n\t// 等价于 request.PageSize = \"10\"\n\trequest.PageSize = requests.NewInteger(10)\n\t// 发起请求并处理异常\n\tresponse, err := ecsClient.DescribeInstances(request)\n\tif err != nil {\n\t\t// 异常处理\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"类型:%#\\n值:%v\\n\",response.Instances,response.Instances)\n\t */\n\n\trequest := ecs.CreateDescribeInstanceAttributeRequest()\n\trequest.InstanceId = \"i-wz962mggaelnnz3kupfw\"\n\tresponse, err := ecsClient.DescribeInstanceAttribute(request)\n\tfmt.Printf(\"值:%v \\n\", response.ImageId)\n}", "func New(config *aws.Config) *IoT {\n\tservice := &service.Service{\n\t\tServiceInfo: serviceinfo.ServiceInfo{\n\t\t\tConfig: defaults.DefaultConfig.Merge(config),\n\t\t\tServiceName: \"iot\",\n\t\t\tSigningName: \"execute-api\",\n\t\t\tAPIVersion: \"2015-05-28\",\n\t\t},\n\t}\n\tservice.Initialize()\n\n\t// Handlers\n\tservice.Handlers.Sign.PushBack(v4.Sign)\n\tservice.Handlers.Build.PushBack(restjson.Build)\n\tservice.Handlers.Unmarshal.PushBack(restjson.Unmarshal)\n\tservice.Handlers.UnmarshalMeta.PushBack(restjson.UnmarshalMeta)\n\tservice.Handlers.UnmarshalError.PushBack(restjson.UnmarshalError)\n\n\t// Run custom service initialization if present\n\tif initService != nil {\n\t\tinitService(service)\n\t}\n\n\treturn &IoT{service}\n}", "func (rm *resourceManager) sdkCreate(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\tinput, err := rm.newCreateRequestPayload(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.CreateStageWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"CREATE\", \"CreateStage\", respErr)\n\tif respErr != nil {\n\t\treturn nil, respErr\n\t}\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.ApiGatewayManaged != nil {\n\t\tko.Status.APIGatewayManaged = resp.ApiGatewayManaged\n\t}\n\tif resp.CreatedDate != nil {\n\t\tko.Status.CreatedDate = &metav1.Time{*resp.CreatedDate}\n\t}\n\tif resp.LastDeploymentStatusMessage != nil {\n\t\tko.Status.LastDeploymentStatusMessage = resp.LastDeploymentStatusMessage\n\t}\n\tif resp.LastUpdatedDate != nil {\n\t\tko.Status.LastUpdatedDate = &metav1.Time{*resp.LastUpdatedDate}\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\treturn &resource{ko}, nil\n}", "func NewTRANSMITSMS(username string, password string) TRANSMITSMS {\n transmitSMSClient := new(TRANSMITSMS_IMPL)\n transmitSMSClient.config = configuration_pkg.NewCONFIGURATION()\n\n transmitSMSClient.config.SetUsername(username)\n transmitSMSClient.config.SetPassword(password)\n\n return transmitSMSClient\n}", "func newNsSvc() *nsSvc {\n\treturn &nsSvc{\n\t\tNsToSvc: make(map[string]*svcPaths),\n\t}\n}", "func main() {\n\tsession, err := session.NewSession(&aws.Config{Region: aws.String(region)})\n\tif err != nil {\n\t\tlog.Println(\"Failed to connect to AWS:\", err)\n\t} else {\n\t\tdb = dynamodb.New(session)\n\t}\n\n\tlambda.Start(Handler)\n}", "func newTLSCredentials(\n\tmountPath string,\n\tkey corev1.SecretKeySelector,\n\tcert monitoringv1.SecretOrConfigMap,\n\tclientCA monitoringv1.SecretOrConfigMap,\n) *tlsCredentials {\n\treturn &tlsCredentials{\n\t\tmountPath: mountPath,\n\t\tkeySecret: key,\n\t\tcert: cert,\n\t\tclientCA: clientCA,\n\t}\n}", "func NewStow() *Stow {\n\tendpoint := os.Getenv(\"AWS_S3_ENDPOINT\")\n\tid := env.Get(\"AWS_ACCESS_KEY_ID\", os.Getenv(\"AWS_ACCESS_KEY\"))\n\tsecret := env.Get(\"AWS_SECRET_ACCESS_KEY\", os.Getenv(\"AWS_SECRET_KEY\"))\n\tregion := env.Get(\"AWS_REGION\", \"eu-west-1\")\n\tbucket := env.Get(\"AWS_S3_BUCKET\", \"pandora\")\n\n\t// TODO enable aws debug logging\n\tkind := \"s3\"\n\tconfig := stow.ConfigMap{\n\t\ts3.ConfigEndpoint: endpoint,\n\t\ts3.ConfigAccessKeyID: id,\n\t\ts3.ConfigSecretKey: secret,\n\t\ts3.ConfigRegion: region,\n\t\ts3.ConfigDisableSSL: \"true\",\n\t}\n\treturn &Stow{\n\t\tkind: kind,\n\t\tconfig: config,\n\t\tbucket: bucket,\n\t}\n}", "func newEventSource() *v1alpha1.AWSSNSSource {\n\tsrc := &v1alpha1.AWSSNSSource{\n\t\tSpec: v1alpha1.AWSSNSSourceSpec{\n\t\t\tARN: tTopicARN,\n\t\t\tSubscriptionAttributes: map[string]*string{\n\t\t\t\t\"DeliveryPolicy\": aws.String(`{\"healthyRetryPolicy\":{\"numRetries\":5}}`),\n\t\t\t},\n\t\t},\n\t}\n\n\t// assume finalizer is already set to prevent the generated reconciler\n\t// from generating an extra Patch action\n\tsrc.Finalizers = []string{sources.AWSSNSSourceResource.String()}\n\n\tPopulate(src)\n\n\treturn src\n}", "func handler(ctx context.Context, req *events.Request) error {\n\t// Create the config.\n\tc := createConfig(ctx, req)\n\tc.log.Print(l.Input{\"loglevel\": \"info\", \"message\": \"Function started\"})\n\tdefer c.log.Print(l.Input{\"loglevel\": \"info\", \"message\": \"Function finished\"})\n\n\t// Create the Cognit service.\n\tif err := c.createCognitoService(); err != nil {\n\t\treturn c.runError(req, err)\n\t}\n\n\t// Unmarshal the ResourceProperties and OldResourceProperties into the config.\n\tif err := req.Unmarshal(c.resourceProperties, c.oldResourceProperties); err != nil {\n\t\treturn c.runError(req, err)\n\t}\n\n\t// Set physical ID - we need the generate secret as physical id,\n\t// since changing this needs replacement of the resource.\n\tc.physicalID = fmt.Sprintf(\"%s-%t-%s\", c.resourceProperties.UserPoolID, c.resourceProperties.GenerateSecret, c.resourceProperties.ClientName)\n\n\t// create, update or delete the userpool client.\n\tdata, err := c.run(req)\n\tif err != nil {\n\t\treturn c.runError(req, err)\n\t}\n\n\t// Send the result to the pre-signed s3 url.\n\tif err := req.Send(c.physicalID, data, err); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func createDNSManager(cl client.Client, operatorConfig operatorconfig.Config, infraConfig *configv1.Infrastructure, dnsConfig *configv1.DNS, installConfig *installConfig) (dns.Manager, error) {\n\tvar dnsManager dns.Manager\n\tswitch infraConfig.Status.Platform {\n\tcase configv1.AWSPlatformType:\n\t\tawsCreds := &corev1.Secret{}\n\t\terr := cl.Get(context.TODO(), types.NamespacedName{Namespace: operatorConfig.Namespace, Name: cloudCredentialsSecretName}, awsCreds)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get aws creds from secret %s/%s: %v\", awsCreds.Namespace, awsCreds.Name, err)\n\t\t}\n\t\tlog.Info(\"using aws creds from secret\", \"namespace\", awsCreds.Namespace, \"name\", awsCreds.Name)\n\t\tmanager, err := awsdns.NewManager(awsdns.Config{\n\t\t\tAccessID: string(awsCreds.Data[\"aws_access_key_id\"]),\n\t\t\tAccessKey: string(awsCreds.Data[\"aws_secret_access_key\"]),\n\t\t\tDNS: dnsConfig,\n\t\t\tRegion: installConfig.Platform.AWS.Region,\n\t\t}, operatorConfig.OperatorReleaseVersion)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create AWS DNS manager: %v\", err)\n\t\t}\n\t\tdnsManager = manager\n\tcase configv1.AzurePlatformType:\n\t\tazureCreds := &corev1.Secret{}\n\t\terr := cl.Get(context.TODO(), types.NamespacedName{Namespace: operatorConfig.Namespace, Name: cloudCredentialsSecretName}, azureCreds)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get azure creds from secret %s/%s: %v\", azureCreds.Namespace, azureCreds.Name, err)\n\t\t}\n\t\tlog.Info(\"using azure creds from secret\", \"namespace\", azureCreds.Namespace, \"name\", azureCreds.Name)\n\t\tmanager, err := azuredns.NewManager(azuredns.Config{\n\t\t\tEnvironment: \"AzurePublicCloud\",\n\t\t\tClientID: string(azureCreds.Data[\"azure_client_id\"]),\n\t\t\tClientSecret: string(azureCreds.Data[\"azure_client_secret\"]),\n\t\t\tTenantID: string(azureCreds.Data[\"azure_tenant_id\"]),\n\t\t\tSubscriptionID: string(azureCreds.Data[\"azure_subscription_id\"]),\n\t\t\tDNS: dnsConfig,\n\t\t}, operatorConfig.OperatorReleaseVersion)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create Azure DNS manager: %v\", err)\n\t\t}\n\t\tdnsManager = manager\n\tdefault:\n\t\tdnsManager = &dns.NoopManager{}\n\t}\n\treturn dnsManager, nil\n}", "func (c *Config) Client() (*alks.Client, error) {\n\tlog.Println(\"[DEBUG] Validating STS credentials\")\n\n\t// lookup credentials\n\tcreds := getCredentials(c)\n\tcp, cpErr := creds.Get()\n\n\tif cpErr == nil {\n\t\tlog.Printf(\"[DEBUG] Got credentials from provider: %s\\n\", cp.ProviderName)\n\t}\n\n\t// validate we have credentials\n\tif cpErr != nil {\n\t\tif awsErr, ok := cpErr.(awserr.Error); ok && awsErr.Code() == \"NoCredentialProviders\" {\n\t\t\tvar err error\n\t\t\tcreds, err = getCredentialsFromSession(c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcp, cpErr = creds.Get()\n\t\t}\n\t}\n\tif cpErr != nil {\n\t\treturn nil, errNoValidCredentialSources\n\t}\n\n\t// create a new session to test credentails\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-east-1\"),\n\t\tCredentials: creds,\n\t})\n\n\t// validate session\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating session from STS. (%v)\", err)\n\t}\n\n\tvar stsconn *sts.STS\n\t// we need to assume another role before creating an ALKS client\n\tif c.AssumeRole.RoleARN != \"\" {\n\t\tarCreds := stscreds.NewCredentials(sess, c.AssumeRole.RoleARN, func(p *stscreds.AssumeRoleProvider) {\n\t\t\tif c.AssumeRole.SessionName != \"\" {\n\t\t\t\tp.RoleSessionName = c.AssumeRole.SessionName\n\t\t\t}\n\n\t\t\tif c.AssumeRole.ExternalID != \"\" {\n\t\t\t\tp.ExternalID = &c.AssumeRole.ExternalID\n\t\t\t}\n\n\t\t\tif c.AssumeRole.Policy != \"\" {\n\t\t\t\tp.Policy = &c.AssumeRole.Policy\n\t\t\t}\n\t\t})\n\n\t\tcp, cpErr = arCreds.Get()\n\t\tif cpErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"The role %q cannot be assumed. Please verify the role ARN, role policies and your base AWS credentials\", c.AssumeRole.RoleARN)\n\t\t}\n\n\t\tstsconn = sts.New(sess, &aws.Config{\n\t\t\tRegion: aws.String(\"us-east-1\"),\n\t\t\tCredentials: arCreds,\n\t\t})\n\t} else {\n\t\tstsconn = sts.New(sess)\n\t}\n\n\t// make a basic api call to test creds are valid\n\t_, serr := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})\n\t// check for valid creds\n\tif serr != nil {\n\t\treturn nil, serr\n\t}\n\n\t// got good creds, create alks sts client\n\tclient, err := alks.NewSTSClient(c.URL, cp.AccessKeyID, cp.SecretAccessKey, cp.SessionToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 1. Check if calling for a specific account\n\tif len(c.Account) > 0 && len(c.Role) > 0 {\n\t\t// 2. Generate client specified\n\t\tclient, err = generateNewClient(c, client)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclient.SetUserAgent(fmt.Sprintf(\"alks-terraform-provider-%s\", getPluginVersion()))\n\n\tlog.Println(\"[INFO] ALKS Client configured\")\n\n\treturn client, nil\n}", "func newConfigService(sling *sling.Sling) *ConfigService {\n\treturn &ConfigService{\n\t\tsling: sling.Path(\"help/\"),\n\t}\n}", "func createTlsConfig() {\n\n}", "func NewStateManager(etcdEndpoints []string, dialTimeout, requestTimeout time.Duration) (StateManager, error) {\n\n\tsm := stateManager{\n\t\tstopChan: make([]chan interface{}, 0),\n\t\trequestTimeout: requestTimeout,\n\t}\n\n\tif cli, err := clientv3.New(clientv3.Config{\n\t\tDialTimeout: dialTimeout,\n\t\tEndpoints: etcdEndpoints,\n\t}); err == nil {\n\t\tsm.cli = cli\n\t} else {\n\t\treturn nil, err\n\t}\n\tsm.kv = clientv3.NewKV(sm.cli)\n\n\treturn &sm, nil\n}", "func NewSdkT(connectSDK, cmsSDK *SDKConnector) *Sdk {\n\tconnectConfig := NewCustomRequesterConfig(\n\t\tconnectSDK.BaseURL,\n\t\t\"x-app-id\",\n\t\t\"x-secret\",\n\t\tconnectSDK.AppID,\n\t\tconnectSDK.AppSecret,\n\t\tconnectSDK.RequestTimeout)\n\tcmsConfig := NewCustomRequesterConfig(\n\t\tcmsSDK.BaseURL,\n\t\t\"x-app-id\",\n\t\t\"x-secret\",\n\t\tcmsSDK.AppID,\n\t\tcmsSDK.AppSecret,\n\t\tcmsSDK.RequestTimeout)\n\tlogger := NewLoggerSimple()\n\tconr := NewRequester(connectConfig, logger)\n\tcmsr := NewRequester(cmsConfig, logger)\n\treturn &Sdk{\n\t\tconnect: &RequestLogger{rq: conr, logger: logger},\n\t\tcms: &RequestLogger{rq: cmsr, logger: logger},\n\t}\n}", "func (rm *resourceManager) newCreateRequestPayload(\n\tr *resource,\n) (*svcsdk.CreateStageInput, error) {\n\tres := &svcsdk.CreateStageInput{}\n\n\tif r.ko.Spec.AccessLogSettings != nil {\n\t\tf0 := &svcsdk.AccessLogSettings{}\n\t\tif r.ko.Spec.AccessLogSettings.DestinationARN != nil {\n\t\t\tf0.SetDestinationArn(*r.ko.Spec.AccessLogSettings.DestinationARN)\n\t\t}\n\t\tif r.ko.Spec.AccessLogSettings.Format != nil {\n\t\t\tf0.SetFormat(*r.ko.Spec.AccessLogSettings.Format)\n\t\t}\n\t\tres.SetAccessLogSettings(f0)\n\t}\n\tif r.ko.Spec.APIID != nil {\n\t\tres.SetApiId(*r.ko.Spec.APIID)\n\t}\n\tif r.ko.Spec.AutoDeploy != nil {\n\t\tres.SetAutoDeploy(*r.ko.Spec.AutoDeploy)\n\t}\n\tif r.ko.Spec.ClientCertificateID != nil {\n\t\tres.SetClientCertificateId(*r.ko.Spec.ClientCertificateID)\n\t}\n\tif r.ko.Spec.DefaultRouteSettings != nil {\n\t\tf4 := &svcsdk.RouteSettings{}\n\t\tif r.ko.Spec.DefaultRouteSettings.DataTraceEnabled != nil {\n\t\t\tf4.SetDataTraceEnabled(*r.ko.Spec.DefaultRouteSettings.DataTraceEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled != nil {\n\t\t\tf4.SetDetailedMetricsEnabled(*r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.LoggingLevel != nil {\n\t\t\tf4.SetLoggingLevel(*r.ko.Spec.DefaultRouteSettings.LoggingLevel)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit != nil {\n\t\t\tf4.SetThrottlingBurstLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit != nil {\n\t\t\tf4.SetThrottlingRateLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit)\n\t\t}\n\t\tres.SetDefaultRouteSettings(f4)\n\t}\n\tif r.ko.Spec.DeploymentID != nil {\n\t\tres.SetDeploymentId(*r.ko.Spec.DeploymentID)\n\t}\n\tif r.ko.Spec.Description != nil {\n\t\tres.SetDescription(*r.ko.Spec.Description)\n\t}\n\tif r.ko.Spec.RouteSettings != nil {\n\t\tf7 := map[string]*svcsdk.RouteSettings{}\n\t\tfor f7key, f7valiter := range r.ko.Spec.RouteSettings {\n\t\t\tf7val := &svcsdk.RouteSettings{}\n\t\t\tif f7valiter.DataTraceEnabled != nil {\n\t\t\t\tf7val.SetDataTraceEnabled(*f7valiter.DataTraceEnabled)\n\t\t\t}\n\t\t\tif f7valiter.DetailedMetricsEnabled != nil {\n\t\t\t\tf7val.SetDetailedMetricsEnabled(*f7valiter.DetailedMetricsEnabled)\n\t\t\t}\n\t\t\tif f7valiter.LoggingLevel != nil {\n\t\t\t\tf7val.SetLoggingLevel(*f7valiter.LoggingLevel)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingBurstLimit != nil {\n\t\t\t\tf7val.SetThrottlingBurstLimit(*f7valiter.ThrottlingBurstLimit)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingRateLimit != nil {\n\t\t\t\tf7val.SetThrottlingRateLimit(*f7valiter.ThrottlingRateLimit)\n\t\t\t}\n\t\t\tf7[f7key] = f7val\n\t\t}\n\t\tres.SetRouteSettings(f7)\n\t}\n\tif r.ko.Spec.StageName != nil {\n\t\tres.SetStageName(*r.ko.Spec.StageName)\n\t}\n\tif r.ko.Spec.StageVariables != nil {\n\t\tf9 := map[string]*string{}\n\t\tfor f9key, f9valiter := range r.ko.Spec.StageVariables {\n\t\t\tvar f9val string\n\t\t\tf9val = *f9valiter\n\t\t\tf9[f9key] = &f9val\n\t\t}\n\t\tres.SetStageVariables(f9)\n\t}\n\tif r.ko.Spec.Tags != nil {\n\t\tf10 := map[string]*string{}\n\t\tfor f10key, f10valiter := range r.ko.Spec.Tags {\n\t\t\tvar f10val string\n\t\t\tf10val = *f10valiter\n\t\t\tf10[f10key] = &f10val\n\t\t}\n\t\tres.SetTags(f10)\n\t}\n\n\treturn res, nil\n}", "func newFakeTracerProviderStore() *fakeTracerProviderStore {\n\texps := []sdktrace.SpanExporter{}\n\treturn &fakeTracerProviderStore{exps, nil, nil}\n}", "func Start(input *StartInput) error {\n\tprovider := aws.Provider{}\n\terr := provider.NewWithConfig(&aws.Config{\n\t\tFilters: *input.Filters,\n\t\tRegion: *input.Region,\n\t\tProfile: *input.Profile,\n\t\tMFAToken: *input.MFAToken,\n\t\tTrace: *input.Trace,\n\t})\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tswitch *input.Type {\n\tcase TypeListInstances:\n\t\terr := input.listInstances(&provider)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase TypeListSessions:\n\t\terr := input.listSessions(&provider)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\terr := fmt.Errorf(\"unsupported list type: %s\", *input.Type)\n\t\tlog.WithField(\"type\", *input.Type).Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func GenerateDynamoDBSvc() {\n\t// sess := session.Must(session.NewSession())\n\t// svc = dynamodb.New(sess)\n}", "func newOpentelemetryTracerProviderStore() *opentelemetryTracerProviderStore {\n\texps := []sdktrace.SpanExporter{}\n\treturn &opentelemetryTracerProviderStore{exps, nil, nil}\n}", "func newTeamService(store storage.DataStore) teamService {\n\treturn teamService{\n\t\tstore: store,\n\t\tdefaultGrpcAuth: defaultGrpcAuth{Store: store},\n\t}\n}", "func main() {\n\tvar settingsFile string\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tif len(os.Args) >= 2 {\n\t\tsettingsFile = os.Args[1]\n\t} else {\n\t\tsettingsFile = \"appsettings.json\"\n\t}\n\n\tc := swift.NewConfig(settingsFile)\n\ts := swift.NewStore(c)\n\tsvc := swift.NewStorageService(c, s...)\n\n\tfmt.Println(\"Add or update a node...\")\n\n\tvar r swift.Register\n\tr.Store = \"\"\n\tr.Network = \"\"\n\tr.Domain = \"\"\n\tr.Starts = time.Now().UTC().AddDate(0, 0, 1)\n\tr.Expires = time.Now().UTC().AddDate(0, 3, 0)\n\tr.Role = 1\n\n\tsuccess := false\n\tisUpdate := false\n\tfor !success {\n\n\t\t// Get the store to use\n\t\tif r.StoreError != \"\" {\n\t\t\tfmt.Println(r.StoreError)\n\t\t}\n\t\tfmt.Println(\"Select a store to use in the add or update operation:\")\n\t\tfor _, s := range svc.GetStoreNames() {\n\t\t\tfmt.Printf(\"\\t- %s\\r\\n\", s)\n\t\t}\n\t\tfmt.Printf(\"Store [%s]: \", r.Store)\n\t\tstore, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Store = store\n\n\t\t// Get the network name\n\t\tif r.NetworkError != \"\" {\n\t\t\tfmt.Println(r.NetworkError)\n\t\t}\n\t\tfmt.Printf(\"Node network name [%s]: \", r.Network)\n\t\tnetwork, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Network = network\n\n\t\t// Get the node domain\n\t\tfmt.Printf(\"Node domain [%s]: \", r.Domain)\n\t\tdomain, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Domain = domain\n\n\t\t// get the node startdate\n\n\t\tfmt.Printf(\"Start date [%s]: \", r.Starts.Format(time.RFC3339))\n\t\tstarts, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif starts != \"\" {\n\t\t\tr.Starts, err = time.Parse(time.RFC3339, starts)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\t// get the node expiry date\n\t\tif r.ExpiresError != \"\" {\n\t\t\tfmt.Println(r.ExpiresError)\n\t\t}\n\t\tfmt.Printf(\"Expires date [%s]: \", r.Expires.Format(time.RFC3339))\n\t\texpires, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif expires != \"\" {\n\t\t\tr.Expires, err = time.Parse(time.RFC3339, expires)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\t// get the node role\n\t\tfmt.Println(\"Select a node role:\")\n\t\tprintNodeTypes()\n\t\tfmt.Printf(\"Role [%d]: \", r.Role)\n\t\trole, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif role != \"\" {\n\t\t\ti, err := strconv.Atoi(role)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tr.Role = i\n\t\t}\n\n\t\t// check if details are correct\n\t\tfmt.Println()\n\t\tfmt.Println(\"Confirm the details are correct!:\")\n\t\tfmt.Printf(\"\\tStore: %s\\r\\n\", r.Store)\n\t\tfmt.Printf(\"\\tNetwork Name: %s\\r\\n\", r.Network)\n\t\tfmt.Printf(\"\\tDomain Name: %s\\r\\n\", r.Domain)\n\t\tfmt.Printf(\"\\tStart Date: %s\\r\\n\", r.Starts.Format(time.RFC3339))\n\t\tfmt.Printf(\"\\tExpiry Date: %s\\r\\n\", r.Expires.Format(time.RFC3339))\n\t\tfmt.Printf(\"\\tRole: %d\\r\\n\", r.Role)\n\t\tfmt.Printf(\"Correct? (Y/n) [Y]: \")\n\t\tcorrect, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif correct != \"y\" &&\n\t\t\tcorrect != \"Y\" &&\n\t\t\tcorrect != \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// set the node\n\t\tsuccess, isUpdate = svc.SetNode(&r)\n\t\tif !success {\n\t\t\tfmt.Println(\"There were some errors, check your values:\")\n\t\t}\n\t}\n\n\t// confirmation\n\tif isUpdate {\n\t\tfmt.Println(\"Node updated!\")\n\t} else {\n\t\tfmt.Println(\"Node added!\")\n\t}\n}", "func AWSScale() {\n\tSetClusterName()\n\t// Scale the AWS infrastructure\n\tfmt.Printf(\"\\t\\t===============Starting AWS Scaling====================\\n\\n\")\n\tsshUser, osLabel := distSelect()\n\tprepareConfigFiles(osLabel)\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\tmvHost := exec.Command(\"mv\", \"./inventory/hosts\", \"./inventory/\"+common.Name+\"/provisioner/hosts\")\n\tmvHost.Run()\n\tmvHost.Wait()\n\t// waiting for Infrastructure\n\ttime.Sleep(30)\n\t// Scale the Kubernetes cluster\n\tfmt.Printf(\"\\n\\n\\t\\t===============Starting Kubernetes Scaling====================\\n\\n\")\n\t_, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/hosts\")\n\tcommon.ErrorCheck(\"No host file found.\", err)\n\tcpHost := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/provisioner/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\tcpHost.Run()\n\tcpHost.Wait()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"scale.yml\", sshUser, osLabel)\n\n\treturn\n}", "func registerSTSRouter(router *mux.Router) {\n\t// Initialize STS.\n\tsts := &stsAPIHandlers{}\n\n\t// STS Router\n\tstsRouter := router.NewRoute().PathPrefix(\"/\").Subrouter()\n\n\t// AssumeRoleWithClientGrants\n\tstsRouter.Methods(\"POST\").HandlerFunc(httpTraceAll(sts.AssumeRoleWithClientGrants)).\n\t\tQueries(\"Action\", \"AssumeRoleWithClientGrants\").\n\t\tQueries(\"Version\", stsAPIVersion).\n\t\tQueries(\"Token\", \"{Token:.*}\")\n\n\t// AssumeRoleWithWebIdentity\n\tstsRouter.Methods(\"POST\").HandlerFunc(httpTraceAll(sts.AssumeRoleWithWebIdentity)).\n\t\tQueries(\"Action\", \"AssumeRoleWithWebIdentity\").\n\t\tQueries(\"Version\", stsAPIVersion).\n\t\tQueries(\"WebIdentityToken\", \"{Token:.*}\")\n\n}", "func (client JobClient) CreateSasTokenResponder(resp *http.Response) (result JobSasTokenDescription, err error) {\n err = autorest.Respond(\n resp,\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusCreated),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func NewStudio(ctx *pulumi.Context,\n\tname string, args *StudioArgs, opts ...pulumi.ResourceOption) (*Studio, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AuthMode == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AuthMode'\")\n\t}\n\tif args.DefaultS3Location == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DefaultS3Location'\")\n\t}\n\tif args.EngineSecurityGroupId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EngineSecurityGroupId'\")\n\t}\n\tif args.ServiceRole == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ServiceRole'\")\n\t}\n\tif args.SubnetIds == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SubnetIds'\")\n\t}\n\tif args.VpcId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'VpcId'\")\n\t}\n\tif args.WorkspaceSecurityGroupId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'WorkspaceSecurityGroupId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Studio\n\terr := ctx.RegisterResource(\"aws-native:emr:Studio\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (ts *tester) createClient() (cli k8s_client.EKS, err error) {\n\tfmt.Print(ts.cfg.EKSConfig.Colorize(\"\\n\\n[yellow]*********************************\\n\"))\n\tfmt.Printf(ts.cfg.EKSConfig.Colorize(\"[light_green]createClient [default](%q)\\n\"), ts.cfg.EKSConfig.ConfigPath)\n\tts.cfg.EKSConfig.AuthenticationAPIVersion =\"client.authentication.k8s.io/v1alpha1\"\n\n\tif ts.cfg.EKSConfig.AWSIAMAuthenticatorPath != \"\" && ts.cfg.EKSConfig.AWSIAMAuthenticatorDownloadURL != \"\" {\n\t\ttpl := template.Must(template.New(\"tmplKUBECONFIG\").Parse(tmplKUBECONFIG))\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tif err = tpl.Execute(buf, kubeconfig{\n\t\t\tClusterAPIServerEndpoint: ts.cfg.EKSConfig.Status.ClusterAPIServerEndpoint,\n\t\t\tClusterCA: ts.cfg.EKSConfig.Status.ClusterCA,\n\t\t\tAWSIAMAuthenticatorPath: ts.cfg.EKSConfig.AWSIAMAuthenticatorPath,\n\t\t\tClusterName: ts.cfg.EKSConfig.Name,\n\t\t\tAuthenticationAPIVersion: ts.cfg.EKSConfig.AuthenticationAPIVersion,\n\t\t}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tts.cfg.Logger.Info(\"writing KUBECONFIG with aws-iam-authenticator\", zap.String(\"kubeconfig-path\", ts.cfg.EKSConfig.KubeConfigPath))\n\t\tif err = ioutil.WriteFile(ts.cfg.EKSConfig.KubeConfigPath, buf.Bytes(), 0777); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = aws_s3.Upload(\n\t\t\tts.cfg.Logger,\n\t\t\tts.cfg.S3API,\n\t\t\tts.cfg.EKSConfig.S3.BucketName,\n\t\t\tpath.Join(ts.cfg.EKSConfig.Name, \"kubeconfig.yaml\"),\n\t\t\tts.cfg.EKSConfig.KubeConfigPath,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tts.cfg.Logger.Info(\"wrote KUBECONFIG with aws-iam-authenticator\", zap.String(\"kubeconfig-path\", ts.cfg.EKSConfig.KubeConfigPath))\n\t} else {\n\t\targs := []string{\n\t\t\tts.cfg.EKSConfig.AWSCLIPath,\n\t\t\t\"eks\",\n\t\t\tfmt.Sprintf(\"--region=%s\", ts.cfg.EKSConfig.Region),\n\t\t\t\"update-kubeconfig\",\n\t\t\tfmt.Sprintf(\"--name=%s\", ts.cfg.EKSConfig.Name),\n\t\t\tfmt.Sprintf(\"--kubeconfig=%s\", ts.cfg.EKSConfig.KubeConfigPath),\n\t\t\t\"--verbose\",\n\t\t}\n\t\tif ts.cfg.EKSConfig.ResolverURL != \"\" {\n\t\t\targs = append(args, fmt.Sprintf(\"--endpoint=%s\", ts.cfg.EKSConfig.ResolverURL))\n\t\t}\n\t\tcmd := strings.Join(args, \" \")\n\t\tts.cfg.Logger.Info(\"writing KUBECONFIG with 'aws eks update-kubeconfig'\",\n\t\t\tzap.String(\"kubeconfig-path\", ts.cfg.EKSConfig.KubeConfigPath),\n\t\t\tzap.String(\"cmd\", cmd),\n\t\t)\n\t\tretryStart, waitDur := time.Now(), 3*time.Minute\n\t\tvar output []byte\n\t\tfor time.Since(retryStart) < waitDur {\n\t\t\tselect {\n\t\t\tcase <-ts.cfg.Stopc:\n\t\t\t\treturn nil, errors.New(\"update-kubeconfig aborted\")\n\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)\n\t\t\toutput, err = exec.New().CommandContext(ctx, args[0], args[1:]...).CombinedOutput()\n\t\t\tcancel()\n\t\t\tout := string(output)\n\t\t\tfmt.Fprintf(ts.cfg.LogWriter, \"\\n'%s' output:\\n\\n%s\\n\\n\", cmd, out)\n\t\t\tif err != nil {\n\t\t\t\tts.cfg.Logger.Warn(\"'aws eks update-kubeconfig' failed\", zap.Error(err))\n\t\t\t\tif !strings.Contains(out, \"Cluster status not active\") || !strings.Contains(err.Error(), \"exit\") {\n\t\t\t\t\treturn nil, fmt.Errorf(\"'aws eks update-kubeconfig' failed (output %q, error %v)\", out, err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tts.cfg.Logger.Info(\"'aws eks update-kubeconfig' success\", zap.String(\"kubeconfig-path\", ts.cfg.EKSConfig.KubeConfigPath))\n\t\t\tif err = aws_s3.Upload(\n\t\t\t\tts.cfg.Logger,\n\t\t\t\tts.cfg.S3API,\n\t\t\t\tts.cfg.EKSConfig.S3.BucketName,\n\t\t\t\tpath.Join(ts.cfg.EKSConfig.Name, \"kubeconfig.yaml\"),\n\t\t\t\tts.cfg.EKSConfig.KubeConfigPath,\n\t\t\t); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tts.cfg.Logger.Warn(\"failed 'aws eks update-kubeconfig'\", zap.Error(err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\tts.cfg.Logger.Info(\"ran 'aws eks update-kubeconfig'\")\n\t\tfmt.Fprintf(ts.cfg.LogWriter, \"\\n\\n'%s' output:\\n\\n%s\\n\\n\", cmd, strings.TrimSpace(string(output)))\n\t}\n\n\tts.cfg.Logger.Info(\"creating k8s client\")\n\tkcfg := &k8s_client.EKSConfig{\n\t\tLogger: ts.cfg.Logger,\n\t\tRegion: ts.cfg.EKSConfig.Region,\n\t\tClusterName: ts.cfg.EKSConfig.Name,\n\t\tKubeConfigPath: ts.cfg.EKSConfig.KubeConfigPath,\n\t\tKubectlPath: ts.cfg.EKSConfig.KubectlPath,\n\t\tServerVersion: ts.cfg.EKSConfig.Version,\n\t\tEncryptionEnabled: ts.cfg.EKSConfig.Encryption.CMKARN != \"\",\n\t\tS3API: ts.cfg.S3API,\n\t\tS3BucketName: ts.cfg.EKSConfig.S3.BucketName,\n\t\tS3MetricsRawOutputDirKubeAPIServer: path.Join(ts.cfg.EKSConfig.Name, \"metrics-kube-apiserver\"),\n\t\tMetricsRawOutputDirKubeAPIServer: filepath.Join(filepath.Dir(ts.cfg.EKSConfig.ConfigPath), ts.cfg.EKSConfig.Name+\"-metrics-kube-apiserver\"),\n\t\tClients: ts.cfg.EKSConfig.Clients,\n\t\tClientQPS: ts.cfg.EKSConfig.ClientQPS,\n\t\tClientBurst: ts.cfg.EKSConfig.ClientBurst,\n\t\tClientTimeout: ts.cfg.EKSConfig.ClientTimeout,\n\t}\n\tif ts.cfg.EKSConfig.IsEnabledAddOnClusterVersionUpgrade() {\n\t\tkcfg.UpgradeServerVersion = ts.cfg.EKSConfig.AddOnClusterVersionUpgrade.Version\n\t}\n\tif ts.cfg.EKSConfig.Status != nil {\n\t\tkcfg.ClusterAPIServerEndpoint = ts.cfg.EKSConfig.Status.ClusterAPIServerEndpoint\n\t\tkcfg.ClusterCADecoded = ts.cfg.EKSConfig.Status.ClusterCADecoded\n\t}\n\tcli, err = k8s_client.NewEKS(kcfg)\n\tif err != nil {\n\t\tts.cfg.Logger.Warn(\"failed to create k8s client\", zap.Error(err))\n\t} else {\n\t\tts.cfg.Logger.Info(\"created k8s client\")\n\t}\n\treturn cli, err\n}", "func init() {\n\ttoken = os.Getenv(\"SLACK_TOKEN\")\n\tif token == \"\" {\n\t\tpanic(errors.New(\"SLACK_TOKEN must be provided\"))\n\t}\n\n\tchrisifyPath = os.Getenv(\"CHRISIFY_PATH\")\n\thaarPath = os.Getenv(\"HAAR_FILE\")\n\n\taccessKeyID = os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\tsecretKeyID = os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\n\ts3Bucket = os.Getenv(\"S3_BUCKET_NAME\")\n\n\tvar err error\n\tsess, err = session.NewSession(&aws.Config{\n\t\tRegion: aws.String(defaultRegion),\n\t\tCredentials: credentials.NewEnvCredentials(),\n\t})\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tsvc = s3.New(sess)\n\n}", "func CreateMSDPStorageServer(nbmaster string, httpClient *http.Client, jwt string)(int, string) {\n fmt.Printf(\"\\nSending a POST request to create with defaults...\\n\")\t\n\tif strings.Compare(apiUtil.TakeInput(\"Want to create new MSDP storage server?(Or you can use existing)(Yes/No):\"), \"Yes\") != 0 {\n\t stsName := apiUtil.TakeInput(\"Enter MSDP/CloudCatalyst Storage Server Name for other operations:\")\n\t\treturn 201, stsName;\n\t}\n\n stsName := apiUtil.TakeInput(\"Enter Storage/Media Server Name:\")\n\tmediaServerName = stsName\n\t\n\tstoragePath := apiUtil.TakeInput(\"Enter Storage Path:\")\n\n MSDPstorageServer := map[string]interface{}{\n \"data\": map[string]interface{}{\n \"type\": \"storageServer\",\n \"id\": stsName,\n \"attributes\": map[string]interface{}{\n \"name\":stsName,\n\t\t\t\t\"storageCategory\":\"MSDP\",\n\t\t\t\t\"mediaServerDetails\": map[string]interface{}{\n \"name\": mediaServerName},\n\t\t\t\t\"msdpAttributes\": map[string]interface{}{\n\t\t\t\t\t\"storagePath\": storagePath,\n \"credentials\":map[string]interface{}{\n \"userName\": \"a\",\n\t\t\t\t\t\"password\": \"a\"}}}}}\n\t\t\t\t\n\n\n stsRequest, _ := json.Marshal(MSDPstorageServer)\n\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + storageUri + storageServerUri\n\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(stsRequest))\n request.Header.Add(\"Content-Type\", contentType);\n request.Header.Add(\"Authorization\", jwt);\n\n response, err := httpClient.Do(request)\n\n if err != nil {\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\n panic(\"Unable to create storage server.\\n\")\n } else {\n if response.StatusCode != 201 {\n responseBody, _ := ioutil.ReadAll(response.Body)\n fmt.Printf(\"%s\\n\", responseBody)\n panic(\"Unable to create MSDP Sts.\\n\")\n } else {\n fmt.Printf(\"%s created successfully.\\n\", stsName);\n //responseDetails, _ := httputil.DumpResponse(response, true);\n apiUtil.AskForResponseDisplay(response.Body)\n }\n }\n\t\n\treturn response.StatusCode, mediaServerName;\n}", "func getAWSClient(ctx context.Context, conf *config.Config, sess *session.Session, region config.Region) (*cziAWS.Client, error) {\n\t// for things meant to be run as a user\n\tuserConf := &aws.Config{\n\t\tRegion: aws.String(region.AWSRegion),\n\t}\n\n\tlambdaConf := userConf\n\tif conf.LambdaConfig.RoleARN != nil {\n\t\t// for things meant to be run as an assumed role\n\t\tlambdaConf = &aws.Config{\n\t\t\tRegion: aws.String(region.AWSRegion),\n\t\t\tCredentials: stscreds.NewCredentials(\n\t\t\t\tsess,\n\t\t\t\t*conf.LambdaConfig.RoleARN, func(p *stscreds.AssumeRoleProvider) {\n\t\t\t\t\tp.TokenProvider = stscreds.StdinTokenProvider\n\t\t\t\t},\n\t\t\t),\n\t\t}\n\t}\n\tawsClient := cziAWS.New(sess).\n\t\tWithIAM(userConf).\n\t\tWithKMS(userConf).\n\t\tWithSTS(userConf).\n\t\tWithLambda(lambdaConf)\n\treturn awsClient, nil\n}", "func setupSpinmint(prNumber int, prRef string, repo *Repository, upgrade bool) (*ec2.Instance, error) {\n\tLogInfo(\"Setting up spinmint for PR: \" + strconv.Itoa(prNumber))\n\n\tsvc := ec2.New(session.New(), Config.GetAwsConfig())\n\n\tvar setupScript string\n\tif upgrade {\n\t\tsetupScript = repo.InstanceSetupUpgradeScript\n\t} else {\n\t\tsetupScript = repo.InstanceSetupScript\n\t}\n\n\tdata, err := ioutil.ReadFile(path.Join(\"config\", setupScript))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdata := string(data)\n\tsdata = strings.Replace(sdata, \"BUILD_NUMBER\", strconv.Itoa(prNumber), -1)\n\tsdata = strings.Replace(sdata, \"BRANCH_NAME\", prRef, -1)\n\tbsdata := []byte(sdata)\n\tsdata = base64.StdEncoding.EncodeToString(bsdata)\n\n\tvar one int64 = 1\n\tparams := &ec2.RunInstancesInput{\n\t\tImageId: &Config.AWSImageId,\n\t\tMaxCount: &one,\n\t\tMinCount: &one,\n\t\tInstanceType: &Config.AWSInstanceType,\n\t\tUserData: &sdata,\n\t\tSecurityGroupIds: []*string{&Config.AWSSecurityGroup},\n\t}\n\n\tresp, err := svc.RunInstances(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add tags to the created instance\n\ttime.Sleep(time.Second * 10)\n\t_, errtag := svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{resp.Instances[0].InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(\"Spinmint-\" + prRef),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Created\"),\n\t\t\t\tValue: aws.String(time.Now().Format(\"2006-01-02/15:04:05\")),\n\t\t\t},\n\t\t},\n\t})\n\tif errtag != nil {\n\t\tLogError(\"Could not create tags for instance: \" + *resp.Instances[0].InstanceId + \" Error: \" + errtag.Error())\n\t}\n\n\treturn resp.Instances[0], nil\n}", "func AWSDestroy() {\n\tSetClusterName()\n\t// Check if credentials file exist, if it exists skip asking to input the AWS values\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/credentials.tfvars\"); err == nil {\n\t\tfmt.Println(\"Credentials file already exists, creation skipped\")\n\t} else {\n\n\t\ttemplates.ParseTemplate(templates.Credentials, \"./inventory/\"+common.Name+\"/provisioner/credentials.tfvars\", GetCredentials())\n\t}\n\tcpHost := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/hosts\", \"./inventory/hosts\")\n\tcpHost.Run()\n\tcpHost.Wait()\n\n\tprovisioner.ExecuteTerraform(\"destroy\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\n\texec.Command(\"rm\", \"./inventory/hosts\").Run()\n\texec.Command(\"rm\", \"-rf\", \"./inventory/\"+common.Name).Run()\n\n\treturn\n}", "func AWSInstall() {\n\t// check if ansible is installed\n\tcommon.DependencyCheck(\"ansible\")\n\tSetClusterName()\n\t// Copy the configuraton files as indicated in the kubespray docs\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/installer\"); err == nil {\n\t\tfmt.Println(\"Configuration folder already exists\")\n\t} else {\n\t\tos.MkdirAll(\"./inventory/\"+common.Name+\"/installer\", 0755)\n\t\tmvHost := exec.Command(\"mv\", \"./inventory/hosts\", \"./inventory/\"+common.Name+\"/hosts\")\n\t\tmvHost.Run()\n\t\tmvHost.Wait()\n\t\tmvShhBastion := exec.Command(\"cp\", \"./kubespray/ssh-bastion.conf\", \"./inventory/\"+common.Name+\"/ssh-bastion.conf\")\n\t\tmvShhBastion.Run()\n\t\tmvShhBastion.Wait()\n\t\t//os.MkdirAll(\"./inventory/\"+common.Name+\"/installer/group_vars\", 0755)\n\t\tcpSample := exec.Command(\"cp\", \"-rfp\", \"./kubespray/inventory/sample/.\", \"./inventory/\"+common.Name+\"/installer/\")\n\t\tcpSample.Run()\n\t\tcpSample.Wait()\n\n\t\tcpKube := exec.Command(\"cp\", \"-rfp\", \"./kubespray/.\", \"./inventory/\"+common.Name+\"/installer/\")\n\t\tcpKube.Run()\n\t\tcpKube.Wait()\n\n\t\tmvInstallerHosts := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\t\tmvInstallerHosts.Run()\n\t\tmvInstallerHosts.Wait()\n\t\tmvProvisionerHosts := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\t\tmvProvisionerHosts.Run()\n\t\tmvProvisionerHosts.Wait()\n\n\t\t//Start Kubernetes Installation\n\t\t//Enable load balancer api access and copy the kubeconfig file locally\n\t\tloadBalancerName, err := exec.Command(\"sh\", \"-c\", \"grep apiserver_loadbalancer_domain_name= ./inventory/\"+common.Name+\"/installer/hosts | cut -d'=' -f2\").CombinedOutput()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Problem getting the load balancer domain name\", err)\n\t\t} else {\n\t\t\tvar groupVars *os.File\n\t\t\t//Make a copy of kubeconfig on Ansible host\n\t\t\tif kubesprayVersion == \"develop\" || kubesprayVersion == \"version-0-7\" {\n\t\t\t\t// Set Kube Network Proxy\n\t\t\t\tSetNetworkPlugin(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster\")\n\t\t\t\tprepareInventoryClusterFile(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster/k8s-cluster.yml\")\n\t\t\t\tgroupVars = prepareInventoryGroupAllFile(\"./inventory/\" + common.Name + \"/installer/group_vars/all/all.yml\")\n\t\t\t} else {\n\t\t\t\t// Set Kube Network Proxy\n\t\t\t\tSetNetworkPlugin(\"./inventory/\" + common.Name + \"/installer/group_vars\")\n\t\t\t\tprepareInventoryClusterFile(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster.yml\")\n\t\t\t\tgroupVars = prepareInventoryGroupAllFile(\"./inventory/\" + common.Name + \"/installer/group_vars/all.yml\")\n\t\t\t}\n\t\t\tdefer groupVars.Close()\n\t\t\t// Resolve Load Balancer Domain Name and pick the first IP\n\n\t\t\telbNameRaw, _ := exec.Command(\"sh\", \"-c\", \"grep apiserver_loadbalancer_domain_name= ./inventory/\"+common.Name+\"/installer/hosts | cut -d'=' -f2 | sed 's/\\\"//g'\").CombinedOutput()\n\n\t\t\t// Convert the Domain name to string, strip all spaces so that Lookup does not return errors\n\t\t\telbName := strings.TrimSpace(string(elbNameRaw))\n\t\t\tfmt.Println(elbName)\n\t\t\tnode, err := net.LookupHost(elbName)\n\t\t\tcommon.ErrorCheck(\"Error resolving ELB name: %v\", err)\n\t\t\telbIP := node[0]\n\t\t\tfmt.Println(node)\n\n\t\t\tDomainName := strings.TrimSpace(string(loadBalancerName))\n\t\t\tloadBalancerDomainName := \"apiserver_loadbalancer_domain_name: \" + DomainName\n\n\t\t\tfmt.Fprintf(groupVars, \"#Set cloud provider to AWS\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"cloud_provider: 'aws'\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"#Load Balancer Configuration\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"loadbalancer_apiserver_localhost: false\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"%s\\n\", loadBalancerDomainName)\n\t\t\tfmt.Fprintf(groupVars, \"loadbalancer_apiserver:\\n\")\n\t\t\tfmt.Fprintf(groupVars, \" address: %s\\n\", elbIP)\n\t\t\tfmt.Fprintf(groupVars, \" port: 6443\\n\")\n\t\t}\n\t}\n\n\tsshUser, osLabel := distSelect()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"cluster.yml\", sshUser, osLabel)\n\n\treturn\n}", "func newServiceStarter(api *API) *serviceStarter {\n\treturn &serviceStarter{\n\t\tapi: api,\n\t}\n}", "func init() {\n\tawsSession := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"REGION\")),\n\t}))\n\n\tif len(os.Getenv(\"DYNAMO_URL\")) > 0 {\n\t\tawsSession.Config.Endpoint = aws.String(os.Getenv(\"DYNAMO_URL\"))\n\t}\n\n\tdbs = dynamodb.New(awsSession)\n}", "func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata {\n\tif !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) {\n\t\t// If the http client is unmodified and this feature is not disabled\n\t\t// set custom timeouts for EC2Metadata requests.\n\t\tcfg.HTTPClient = &http.Client{\n\t\t\t// use a shorter timeout than default because the metadata\n\t\t\t// service is local if it is running, and to fail faster\n\t\t\t// if not running on an ec2 instance.\n\t\t\tTimeout: 1 * time.Second,\n\t\t}\n\t\t// max number of retries on the client operation\n\t\tcfg.MaxRetries = aws.Int(2)\n\t}\n\n\tif u, err := url.Parse(endpoint); err == nil {\n\t\t// Remove path from the endpoint since it will be added by requests.\n\t\t// This is an artifact of the SDK adding `/latest` to the endpoint for\n\t\t// EC2 IMDS, but this is now moved to the operation definition.\n\t\tu.Path = \"\"\n\t\tu.RawPath = \"\"\n\t\tendpoint = u.String()\n\t}\n\n\tsvc := &EC2Metadata{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceName,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"latest\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\t// token provider instance\n\ttp := newTokenProvider(svc, defaultTTL)\n\n\t// NamedHandler for fetching token\n\tsvc.Handlers.Sign.PushBackNamed(request.NamedHandler{\n\t\tName: fetchTokenHandlerName,\n\t\tFn: tp.fetchTokenHandler,\n\t})\n\t// NamedHandler for enabling token provider\n\tsvc.Handlers.Complete.PushBackNamed(request.NamedHandler{\n\t\tName: enableTokenProviderHandlerName,\n\t\tFn: tp.enableTokenProviderHandler,\n\t})\n\n\tsvc.Handlers.Unmarshal.PushBackNamed(unmarshalHandler)\n\tsvc.Handlers.UnmarshalError.PushBack(unmarshalError)\n\tsvc.Handlers.Validate.Clear()\n\tsvc.Handlers.Validate.PushBack(validateEndpointHandler)\n\n\t// Disable the EC2 Metadata service if the environment variable is set.\n\t// This short-circuits the service's functionality to always fail to send\n\t// requests.\n\tif strings.ToLower(os.Getenv(disableServiceEnvVar)) == \"true\" {\n\t\tsvc.Handlers.Send.SwapNamed(request.NamedHandler{\n\t\t\tName: corehandlers.SendHandler.Name,\n\t\t\tFn: func(r *request.Request) {\n\t\t\t\tr.HTTPResponse = &http.Response{\n\t\t\t\t\tHeader: http.Header{},\n\t\t\t\t}\n\t\t\t\tr.Error = awserr.New(\n\t\t\t\t\trequest.CanceledErrorCode,\n\t\t\t\t\t\"EC2 IMDS access disabled via \"+disableServiceEnvVar+\" env var\",\n\t\t\t\t\tnil)\n\t\t\t},\n\t\t})\n\t}\n\n\t// Add additional options to the service config\n\tfor _, option := range opts {\n\t\toption(svc.Client)\n\t}\n\treturn svc\n}", "func main() {\n\n\topts, err :=openstack.AuthOptionsFromEnv()\n\tif err!= nil {\n\t\tpanic(err)\n\t}\n\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnovac, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(novaList(novac,&servers.ListOpts{AllTenants:true}))\n\t//fmt.Println(deleteNova(novac,\"fee074ee-6d88-4b07-ad47-625d46b9fce6\"))\n\theatc ,err := openstack.NewOrchestrationV1(provider, gophercloud.EndpointOpts{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(HeatList(heatc,&stacks.ListOpts{AllTenants:true}))\n}", "func NewManager(endPoint, slug, shConnStr, fetcherBackendVersion, enricherBackendVersion string, fetch bool, enrich bool, eSUrl string, esUser string, esPassword string, esIndex string, fromDate *time.Time, project string, fetchSize int, enrichSize int, affBaseURL, esCacheURL, esCacheUsername, esCachePassword, authGrantType, authClientID, authClientSecret, authAudience, auth0URL, env, webHookURL string) (*Manager, error) {\n\tmng := &Manager{\n\t\tEndpoint: endPoint,\n\t\tSlug: slug,\n\t\tSHConnString: shConnStr,\n\t\tFetcherBackendVersion: fetcherBackendVersion,\n\t\tEnricherBackendVersion: enricherBackendVersion,\n\t\tFetch: fetch,\n\t\tEnrich: enrich,\n\t\tESUrl: eSUrl,\n\t\tESUsername: esUser,\n\t\tESPassword: esPassword,\n\t\tESIndex: esIndex,\n\t\tFromDate: fromDate,\n\t\tHTTPTimeout: 60 * time.Second,\n\t\tProject: project,\n\t\tFetchSize: fetchSize,\n\t\tEnrichSize: enrichSize,\n\t\tAffBaseURL: affBaseURL,\n\t\tESCacheURL: esCacheURL,\n\t\tESCacheUsername: esCacheUsername,\n\t\tESCachePassword: esCachePassword,\n\t\tAuthGrantType: authGrantType,\n\t\tAuthClientID: authClientID,\n\t\tAuthClientSecret: authClientSecret,\n\t\tAuthAudience: authAudience,\n\t\tAuth0URL: auth0URL,\n\t\tEnvironment: env,\n\t\tesClientProvider: nil,\n\t\tfetcher: nil,\n\t\tenricher: nil,\n\t\tWebHookURL: webHookURL,\n\t\tMaxWorkers: 1000,\n\t}\n\n\tfetcher, enricher, esClientProvider, err := buildServices(mng)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroupName, err := getGroupName(endPoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmng.fetcher = fetcher\n\tmng.enricher = enricher\n\tmng.esClientProvider = esClientProvider\n\tmng.GroupName = groupName\n\tmng.workerPool = &workerPool{\n\t\tMaxWorker: MaxConcurrentRequests,\n\t\tqueuedTaskC: make(chan func()),\n\t}\n\n\treturn mng, nil\n}", "func main() {\n // Initialize a session\n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n\n // Create Lambda service client\n svc := lambda.New(sess, &aws.Config{Region: aws.String(\"us-west-2\")})\n\n result, err := svc.ListFunctions(nil)\n if err != nil {\n fmt.Println(\"Cannot list functions\")\n os.Exit(0)\n }\n\n fmt.Println(\"Functions:\")\n\n for _, f := range result.Functions {\n fmt.Println(\"Name: \" + aws.StringValue(f.FunctionName))\n fmt.Println(\"Description: \" + aws.StringValue(f.Description))\n fmt.Println(\"\")\n }\n}", "func setupS3(ctx context.Context, s3 *s3Config, forETL bool) (res fileservice.FileService, readPath string, err error) {\n\treturn setupFileservice(ctx, &pathConfig{\n\t\tisS3: true,\n\t\tforETL: forETL,\n\t\ts3Config: *s3,\n\t})\n}", "func newSession(roleARN, region string, qps int, burst int) *session.Session {\n\tsess := session.Must(session.NewSession())\n\tsess.Handlers.Build.PushFrontNamed(request.NamedHandler{\n\t\tName: \"authenticatorUserAgent\",\n\t\tFn: request.MakeAddToUserAgentHandler(\n\t\t\t\"aws-iam-authenticator\", pkg.Version),\n\t})\n\tif aws.StringValue(sess.Config.Region) == \"\" {\n\t\tsess.Config.Region = aws.String(region)\n\t}\n\n\tif roleARN != \"\" {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"roleARN\": roleARN,\n\t\t}).Infof(\"Using assumed role for EC2 API\")\n\n\t\trateLimitedClient, err := httputil.NewRateLimitedClient(qps, burst)\n\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Getting error = %s while creating rate limited client \", err)\n\t\t}\n\n\t\tap := &stscreds.AssumeRoleProvider{\n\t\t\tClient: sts.New(sess, aws.NewConfig().WithHTTPClient(rateLimitedClient).WithSTSRegionalEndpoint(endpoints.RegionalSTSEndpoint)),\n\t\t\tRoleARN: roleARN,\n\t\t\tDuration: time.Duration(60) * time.Minute,\n\t\t}\n\n\t\tsess.Config.Credentials = credentials.NewCredentials(ap)\n\t}\n\treturn sess\n}", "func New(auth aws.Auth, region aws.Region) *SES {\n\treturn &SES{\n\t\tAuth: auth,\n\t\tRegion: region,\n\t}\n}", "func NewService(config ...*aws.Config) Service {\n\n\tsess := session.Must(session.NewSession(config...))\n\tcsvc := cognitoidentityprovider.New(sess)\n\n\treturn &cognitoService{csvc: csvc}\n}", "func newIVDProtectedEntityTypeManagerFromURL(url *url.URL, s3Config astrolabe.S3Config, insecure bool, logger logrus.FieldLogger) (*IVDProtectedEntityTypeManager, error) {\n\tctx := context.Background()\n\tclient, err := newKeepAliveClient(ctx, url, insecure)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvslmClient, err := vslm.NewClient(ctx, client.Client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = client.UseServiceVersion(\"vsan\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcnsClient, err := cns.NewClient(ctx, client.Client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newIVDProtectedEntityTypeManagerWithClient(client, s3Config, vslmClient, cnsClient, logger)\n}", "func main() {\n\t// Env Vars\n\tawsRegion := os.Getenv(\"awsRegion\")\n\n\tsourceRDS := os.Getenv(\"sourceRDS\")\n\trestoreRDS := os.Getenv(\"restoreRDS\")\n\trdsSubnetGroup := os.Getenv(\"rdsSubnetGroup\")\n\trdsSecurityGroupId := os.Getenv(\"rdsSecurityGroupId\")\n\n\t// Optional restore date and time - defaults to latest available point in time\n\trestoreDate := os.Getenv(\"restoreDate\")\n\trestoreTime := os.Getenv(\"restoreTime\")\n\n\t// Optional instance type - defaults to db.t3.small\n\trdsInstanceType := os.Getenv(\"rdsInstanceType\")\n\n\t// Optional rds engine - defaults to aurora-mysql\n\trdsEngine := os.Getenv(\"rdsEngine\")\n\n\t// TODO: figure out how to add this to created cluster without too many conditionals\n\t // both on - db_cluster_parameter_group_name and db_parameter_group_name\n\n\t// Optional parameter group - defaults to default.aurora-mysql5.7\n\t//rdsParameterGroup := os.Getenv(\"rdsParameterGroup\")\n\n\t// Params\n\tvar restoreParams = map[string]string{\n\t\t\"awsRegion\": awsRegion,\n\t\t\"sourceRDS\": sourceRDS,\n\t\t\"restoreRDS\": restoreRDS,\n\t\t\"rdsSubnetGroup\": rdsSubnetGroup,\n\t\t\"rdsSecurityGroupId\": rdsSecurityGroupId,\n\t}\n\n\t// Init AWS Session and RDS Client\n\trdsClient, initErr := initRDSClient(awsRegion)\n\tif initErr != nil {\n\t\tfmt.Printf(\"Init Err: %v\", initErr)\n\t\tos.Exit(1)\n\t}\n\n\t// If date and time provided use it instead of last restorable time\n\tif restoreDate != \"\" {\n\t\tif restoreTime != \"\" {\n\t\t\trestoreParams[\"restoreFromTime\"] = restoreDate + \"T\" + restoreTime + \".000Z\"\n\t\t} else {\n\t\t\trestoreParams[\"restoreFromTime\"] = restoreDate + \"T01:00:00.000Z\"\n\t\t}\n\t\tfmt.Printf(\"Restore time set to %v\\n\", restoreParams[\"restoreFromTime\"])\n\t} else {\n\t\tfmt.Printf(\"Restore time set to latest available\\n\")\n\t}\n\n\t// If instance type provided change default\n\tif rdsInstanceType != \"\" {\n\t\trestoreParams[\"rdsInstanceType\"] = rdsInstanceType\n\t} else {\n\t\trestoreParams[\"rdsInstanceType\"] = \"db.t3.small\"\n\t}\n\n\t// If rds engine provided change default\n\tif rdsEngine != \"\" {\n\t\trestoreParams[\"rdsEngine\"] = rdsEngine\n\t} else {\n\t\trestoreParams[\"rdsEngine\"] = \"aurora-mysql\"\n\t}\n\n\t//// If rds parameter group provided change default\n\t//if rdsEngine != \"\" {\n\t\t//restoreParams[\"rdsParameterGroup\"] = rdsParameterGroup\n\t//} else {\n\t\t//restoreParams[\"rdsParameterGroup\"] = \"default.aurora-mysql5.7\"\n\t//}\n\n\t// Check if RDS instance exists, if it doesn't, skip Instance delete step\n\trdsInstanceExists, checkRDSInstanceExistsErr := rdsInstanceExists(rdsClient, restoreParams)\n\tif checkRDSInstanceExistsErr != nil {\n\t\tfmt.Printf(\"Check if RDS Instance exists Err: %v\", checkRDSInstanceExistsErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Check if RDS instance exists, if it doesn't skip Instance delete step\n\tif rdsInstanceExists {\n\t\t// Delete RDS instance\n\t\tdeleteInstanceErr := deleteRDSInstance(rdsClient, restoreParams)\n\t\tif deleteInstanceErr != nil {\n\t\t\tfmt.Printf(\"Delete RDS Instance Err: %v\", deleteInstanceErr)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\twaitDeleteInstanceErr := waitUntilRDSInstanceDeleted(rdsClient, restoreParams)\n\t\tif waitDeleteInstanceErr != nil {\n\t\t\tfmt.Printf(\"Wait RDS Instance delete Err : %v\", waitDeleteInstanceErr)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Check if RDS cluster exists, if it doesn't, skip Cluster delete step\n\t// Should be executed only if Instance is deleted first, as instance deletion actually deletes cluster as well\n\trdsClusterExists, checkRDSClusterExistsErr := rdsClusterExists(rdsClient, restoreParams)\n\tif checkRDSClusterExistsErr != nil {\n\t\tfmt.Printf(\"Check if RDS Cluster exists Err: %v\", checkRDSClusterExistsErr)\n\t\tos.Exit(1)\n\t}\n\n\tif rdsClusterExists {\n\t\t// Delete RDS cluster\n\t\tdeleteClusterErr := deleteRDSCluster(rdsClient, restoreParams)\n\t\tif deleteClusterErr != nil {\n\t\t\tfmt.Printf(\"Delete RDS Cluster Err: %v\", deleteClusterErr)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Wait until RDS Cluster is deleted\n\t\twaitDeleteClusterErr := waitUntilRDSClusterDeleted(rdsClient, restoreParams)\n\t\tif waitDeleteClusterErr != nil {\n\t\t\tfmt.Printf(\"Wait RDS Cluster delete Err : %v\", waitDeleteClusterErr)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Restore point in time RDS into a new cluster\n\trestoreErr := restorePointInTimeRDS(rdsClient, restoreParams)\n\tif restoreErr != nil {\n\t\tfmt.Printf(\"Restore Point-In-Time RDS Err: %v\", restoreErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Wait until DB instance created\n\twaitClusterCreateErr := waitUntilRDSClusterCreated(rdsClient, restoreParams)\n\tif waitClusterCreateErr != nil {\n\t\tfmt.Printf(\"Wait RDS Cluster create Err: %v\", waitClusterCreateErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Create RDS Instance in RDS Cluster\n\tcreateRDSInstanceErr := createRDSInstance(rdsClient, restoreParams)\n\tif createRDSInstanceErr != nil {\n\t\tfmt.Printf(\"Create RDS Instance Err: %v\", createRDSInstanceErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Wait until DB instance created in RDS cluster\n\twaitInstanceCreateErr := waitUntilRDSInstanceCreated(rdsClient, restoreParams)\n\tif waitInstanceCreateErr != nil {\n\t\tfmt.Printf(\"Wait RDS Instance create Err: %v\", waitInstanceCreateErr)\n\t\tos.Exit(1)\n\t}\n}", "func newClusterToolSet(federationClient federationclientset.Interface) clusterToolSetInterface {\n\treturn nil\n}" ]
[ "0.61317915", "0.58017105", "0.55611104", "0.5475019", "0.5471191", "0.54304373", "0.5389638", "0.52249086", "0.5190177", "0.51850677", "0.5169422", "0.51638", "0.50995004", "0.5093693", "0.5084769", "0.50710386", "0.50554657", "0.5037815", "0.5034028", "0.5019643", "0.50195193", "0.49946144", "0.49917257", "0.49896905", "0.49513838", "0.49322042", "0.49312705", "0.4913705", "0.48993233", "0.48802537", "0.48783654", "0.48771283", "0.48642147", "0.48632932", "0.4848928", "0.48474923", "0.4838622", "0.48377538", "0.483459", "0.4827287", "0.48067185", "0.47934455", "0.47803363", "0.47780854", "0.47701836", "0.47686112", "0.47659692", "0.4760019", "0.47566566", "0.47485843", "0.47373", "0.4731582", "0.47271943", "0.47218385", "0.4711026", "0.4706602", "0.46927506", "0.46920416", "0.46920228", "0.46918148", "0.46889082", "0.46878564", "0.4687694", "0.4681821", "0.46699053", "0.466923", "0.4665991", "0.4663262", "0.46621573", "0.46537715", "0.46499944", "0.46490288", "0.46337226", "0.46175858", "0.46164265", "0.46130067", "0.4610022", "0.46063802", "0.46034104", "0.459923", "0.4598807", "0.4582208", "0.45797318", "0.45769742", "0.45760933", "0.45746937", "0.4573128", "0.4572449", "0.4572262", "0.4568209", "0.456568", "0.45629472", "0.45611262", "0.45602053", "0.45557496", "0.455143", "0.45501158", "0.45474675", "0.4545065", "0.45421723" ]
0.55637866
2
MiddleRow takes a slice of 3 string slices (each representing a row in a 2d matrix, with each element position respresenting a column), and interpolates "nan" values as the average of nondiagonal adjacent values, which must be string representations of numbers, or "nan". There must be 3 rows. All rows must be equal length. It returns a copy of the middle row with any "nan" values interpolated and rounded to decimalPlaces decimal places.
func MiddleRow(rows [][]string, decimalPlaces int) []string { middleRow := rows[1] result := make([]string, len(middleRow)) for i, val := range middleRow { if isNaN(val) { result[i] = averageOf( decimalPlaces, valueAt(rows[0], i), valueAt(rows[2], i), valueLeftOf(middleRow, i), valueRightOf(middleRow, i), ) } else { result[i] = val } } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetMiddleValue(array []float64) float64 {\n\t//Create a variable of float64 (it will be middle value)\n\tvar number float64\n\t//This a loop like foreach(...) in C#\n\t//renge return index and value of each element from time row\n\t//here number will had a sum of all element\n\tfor _, v := range array {\n\t\tnumber += v\n\t}\n\t//here we will divide a sum on count\n\tnumber /= float64(len(array))\n\treturn number\n}", "func Average(slice []float64) (float64, error) {\n\n\tif len(slice) == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Empty\")\n\t}\n\n\tvar sum float64\n\tfor _, n := range slice {\n\t\tsum += n\n\t}\n\n\tavg := sum / float64(len(slice))\n\t// log.Println(\"Slice average\", avg)\n\treturn math.Round(avg*100) / 100, nil\n}", "func ReduceMedian(values []interface{}) interface{} {\n\tvar data []float64\n\t// Collect all the data points\n\tfor _, value := range values {\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdata = append(data, value.([]float64)...)\n\t}\n\n\tlength := len(data)\n\tif length < 2 {\n\t\tif length == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn data[0]\n\t}\n\tmiddle := length / 2\n\tvar sortedRange []float64\n\tif length%2 == 0 {\n\t\tsortedRange = getSortedRange(data, middle-1, 2)\n\t\tvar low, high = sortedRange[0], sortedRange[1]\n\t\treturn low + (high-low)/2\n\t} else {\n\t\tsortedRange = getSortedRange(data, middle, 1)\n\t\treturn sortedRange[0]\n\t}\n}", "func Middle(img image.Image) (int, error) {\n\trect := img.Bounds()\n\treturn (rect.Max.X - rect.Min.X) / 2, nil\n}", "func Middle(ghash string) []float64 {\n\tbox := geohash.BoundingBox(ghash)\n\tlat, lng := box.Center()\n\treturn []float64{lng, lat}\n}", "func (q *QQwry) getMiddleOffset(start uint32, end uint32) uint32 {\n\trecords := ((end - start) / INDEX_LEN) >> 1\n\treturn start + records*INDEX_LEN\n}", "func getMiddle(x int, y int) int {\n\tif x > y {\n\t\treturn ((x - y) / 2) + y\n\t} else {\n\t\treturn ((y - x) / 2) + x\n\t}\n}", "func calcRowMeans(mtxX, mtxRes [][]float64, c, r int) {\n\tfor k := 0; k < r; k++ {\n\t\tvar fSum float64\n\t\tfor i := 0; i < c; i++ {\n\t\t\tfSum += mtxX[i][k]\n\t\t}\n\t\tmtxRes[k][0] = fSum / float64(c)\n\t}\n}", "func Median3(a []int) (int, int) {\n\ti, j := len(a)/2, len(a)-1\n\tlo, mid, hi := a[0], a[i], a[j]\n\tswitch {\n\tcase mid <= lo && lo <= hi:\n\t\treturn 0, lo\n\tcase lo <= mid && mid <= hi:\n\t\treturn i, mid\n\tdefault:\n\t\treturn j, hi\n\t}\n}", "func initializeMiddleZone() [][]Piece {\n\trows := make([][]Piece, 3)\n\tfor i := range rows {\n\t\trows[i] = []Piece{nil, nil, nil, nil, nil, nil, nil, nil, nil}\n\t}\n\treturn rows\n}", "func (a *Array64) NaNMean(axis ...int) *Array64 {\n\tswitch {\n\tcase a.valAxis(&axis, \"Sum\"):\n\t\treturn a\n\t}\n\treturn a.NaNSum(axis...).Div(a.NaNCount(axis...))\n}", "func CenteredAvg(xi []int) float64 {\n\tsort.Ints(xi) //=> arrange in ascending order\n\txi = xi[1 : len(xi)-1] //=> select whole data Except: first, last\n\n\tn := 0 //=> total\n\tfor _, v := range xi {\n\t\tn += v\n\t}\n\n\tf := float64(n) / float64(len(xi)) //=> total/number\n\treturn f\n}", "func (m *Mantle) truncatedMidGap() uint64 {\n\tmidGap := midGap(m.book(), rateStep)\n\treturn truncate(int64(midGap), int64(rateStep))\n}", "func (o *WObj) GetMiddle() (float64, float64, int8) {\n\tpnt := o.Hitbox.GetMiddle()\n\treturn pnt.X, pnt.Y, o.layer\n}", "func SquareMiddle(x, numDigits int) int {\n\tstringX := strconv.Itoa(x * x)\n\tif numDigits%2 != 0 || CountNumDigits(x) > 2*numDigits || x < 0 || numDigits <= 0 {\n\t\tpanic(\"Error! Please check your arguments\")\n\t}\n\tskipper := numDigits / 2\n\tbeginner := skipper\n\tend := len(stringX) - skipper\n\tfmt.Println(stringX)\n\tif len(stringX) == (2*numDigits)-1 {\n\t\tbeginner = skipper - 1\n\t}\n\tfmt.Println(len(stringX))\n\tres, err := strconv.Atoi(stringX[beginner:end])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn res\n}", "func Mean(values []float64) float64 {\n\tvar sum float64 = 0.0\n\tcount := 0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t\tcount++\n\t\t}\n\t}\n\treturn sum / float64(count)\n}", "func (r *Range) GetMidVal() float64 {\n\treturn 0.5 * (r.minVal + r.maxVal)\n}", "func TestCenteredAvg(t *testing.T) {\n\ttype test struct {\n\t\tdata []int\n\t\tresult float64\n\t}\n\n\ttests := []test{\n\t\ttest{\n\t\t\t[]int{1, 3, 5, 7, 9},\n\t\t\t5,\n\t\t},\n\t\ttest{\n\t\t\t[]int{2, 4, 6, 8, 10},\n\t\t\t6,\n\t\t},\n\t\ttest{\n\t\t\t[]int{11, 13, 15, 17, 19},\n\t\t\t15,\n\t\t},\n\t\ttest{\n\t\t\t[]int{20, 22, 24, 26, 28, 30},\n\t\t\t25,\n\t\t},\n\t}\n\n\tfor _, v := range tests {\n\t\tr := CenteredAvg(v.data)\n\t\tif r != v.result {\n\t\t\tt.Error(\"Expected\", v.result, \"Got\", r)\n\t\t}\n\t}\n}", "func Median(values []float64) (median float64, err error) {\n\n\tl := len(values)\n\tif l == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Value can't be empty slice\")\n\t} else if l%2 == 0 {\n\t\tmedian, _ = Average(values[l/2-1 : l/2+1])\n\t} else {\n\t\tmedian = float64(values[l/2])\n\t}\n\n\t// log.Println(\"Slice median\", median)\n\treturn median, nil\n}", "func middleNodeBrute(head *ListNode) *ListNode {\n\t// brute force\n\tnode := head\n\tslice := []*ListNode{}\n\n\tfor node != nil {\n\t\tslice = append(slice, node)\n\n\t\tnode = node.Next\n\t}\n\n\treturn slice[len(slice)/2]\n}", "func (fn *formulaFuncs) TRIMMEAN(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"TRIMMEAN requires 2 arguments\")\n\t}\n\tpercent := argsList.Back().Value.(formulaArg).ToNumber()\n\tif percent.Type != ArgNumber {\n\t\treturn percent\n\t}\n\tif percent.Number < 0 || percent.Number >= 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)\n\t}\n\tvar arr []float64\n\tarrArg := argsList.Front().Value.(formulaArg).ToList()\n\tfor _, cell := range arrArg {\n\t\tif cell.Type != ArgNumber {\n\t\t\tcontinue\n\t\t}\n\t\tarr = append(arr, cell.Number)\n\t}\n\tdiscard := math.Floor(float64(len(arr)) * percent.Number / 2)\n\tsort.Float64s(arr)\n\tfor i := 0; i < int(discard); i++ {\n\t\tif len(arr) > 0 {\n\t\t\tarr = arr[1:]\n\t\t}\n\t\tif len(arr) > 0 {\n\t\t\tarr = arr[:len(arr)-1]\n\t\t}\n\t}\n\n\targs := list.New().Init()\n\tfor _, ele := range arr {\n\t\targs.PushBack(newNumberFormulaArg(ele))\n\t}\n\treturn fn.AVERAGE(args)\n}", "func median3(data sort.Interface, a, b, c int) {\n\tif data.Less(b, a) {\n\t\tdata.Swap(b, a)\n\t}\n\tif data.Less(c, b) {\n\t\tdata.Swap(c, b)\n\t\tif data.Less(b, a) {\n\t\t\tdata.Swap(b, a)\n\t\t}\n\t}\n}", "func SquareMiddle(x int, numDigits int) int {\n\tif numDigits%2 != 0 || x <= 0 || numDigits <= 0 || NumDigits(x) > 2*numDigits {\n\t\tpanic(\"incorrect input\")\n\t}\n\n\tx = x * x\n\n\tnum := strconv.Itoa(x)\n\tnum = num[len(num)/2-numDigits/2 : len(num)/2+numDigits/2]\n\tret, _ := strconv.Atoi(num)\n\treturn ret\n\n}", "func average(arr []float64) float64 {\n\treturn sum(arr) / float64(len(arr))\n}", "func ReduceMean(values []interface{}) interface{} {\n\tout := &meanMapOutput{}\n\tvar countSum int\n\tfor _, v := range values {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tval := v.(*meanMapOutput)\n\t\tcountSum = out.Count + val.Count\n\t\tout.Mean = val.Mean*(float64(val.Count)/float64(countSum)) + out.Mean*(float64(out.Count)/float64(countSum))\n\t\tout.Count = countSum\n\t}\n\tif out.Count > 0 {\n\t\treturn out.Mean\n\t}\n\treturn nil\n}", "func AdjustedMean(n int) func(s []float64) []float64 {\n\treturn func(s []float64) []float64 {\n\t\tres := make([]float64, len(s)-n+1)\n\t\tfor i := range res {\n\t\t\tv := 0.0\n\t\t\tfor j := 0; j < n; j++ {\n\t\t\t\tv += s[i+j] * float64(j+1)\n\t\t\t}\n\t\t\tres[i] = v / float64(n*(n+1)/2)\n\t\t}\n\n\t\treturn res\n\t}\n}", "func Average(xs []float64) float64 {\n total := float64(0)\n if len(xs) == 0 {\n return total\n }\n for _, x := range xs {\n total += x\n }\n return total / float64(len(xs))\n}", "func CenteredAvg(xi []int) float64 {\n\tsort.Ints(xi)\n\tx := xi[1:(len(xi) - 1)]\n\ts := 0\n\tfor _, v := range x {\n\t\ts += v\n\t}\n\treturn float64(s) / float64(len(x))\n}", "func naiveMean(i int, j int64, k *int, l *int64, meanValue *float64, w float64, intervallLength int)(){\n\t*meanValue = 6.3\n}", "func TakeLast(values ts.Datapoints) float64 {\n\tfor i := len(values) - 1; i >= 0; i-- {\n\t\tif !math.IsNaN(values[i].Value) {\n\t\t\treturn values[i].Value\n\t\t}\n\t}\n\n\treturn math.NaN()\n}", "func (ema *Ema) Last3() float64 {\n\treturn ema.points[len(ema.points)-3].Ema\n}", "func getMedianPivot(data []int, left, right, groupSize int) int {\n\tfor {\n\t\tsize := right - left\n\n\t\tif size < groupSize {\n\t\t\treturn partitionN(data, left, right, groupSize)\n\t\t}\n\n\t\t// index is increased by a group size\n\t\tfor index := left; index < right; index += groupSize {\n\t\t\tsubRight := index + groupSize\n\n\t\t\t// check boundary\n\t\t\tif subRight > right {\n\t\t\t\tsubRight = right\n\t\t\t}\n\n\t\t\t// get median\n\t\t\tmedian := partitionN(data, index, subRight, groupSize)\n\n\t\t\t// move each median to the front of container\n\t\t\tdata[median], data[left+(index-left)/groupSize] =\n\t\t\t\tdata[left+(index-left)/groupSize], data[median]\n\t\t}\n\n\t\t// update the end of medians\n\t\tright = left + (right-left)/groupSize\n\t}\n}", "func Ninther(a []int) (int, int) {\n\tif len(a) < 3 {\n\t\treturn Median3(a)\n\t}\n\n\tmidStart, midEnd := len(a)/3, 2*len(a)/3\n\tvar i, m [3]int\n\ti[0], m[0] = Median3(a[:midStart])\n\ti[1], m[1] = Median3(a[midStart:midEnd])\n\ti[2], m[2] = Median3(a[midEnd:])\n\ti[1] += midStart\n\ti[2] += midEnd\n\tj, p := Median3(m[:])\n\treturn i[j], p\n}", "func Average(arr []float64) float64 {\n\tvar total float64\n\tfor _, value := range arr {\n\t\ttotal += value\n\t}\n\treturn total / float64(len(arr))\n}", "func (m *Matrix) SepRow(start, end int) (matrix *Matrix) {\n\tmatrix = Copy(m)\n\tif end < start {\n\t\tmatrix.err = errors.New(\"The argument values are invalid\")\n\t\treturn\n\t} else if end > m.row || start < 1 {\n\t\tmatrix.err = errors.New(\"The value are out of matrix\")\n\t\treturn\n\t}\n\ts := (start - 1) * m.column\n\te := (end - 1) * m.column\n\tmatrix = New(end-start+1, m.column, m.matrix[s:e+m.column])\n\treturn\n}", "func medianOfThreeWeeks(rcv Weeks, less func(Weeks, int, int) bool, a, b, c int) {\n\tm0 := b\n\tm1 := a\n\tm2 := c\n\t// bubble sort on 3 elements\n\tif less(rcv, m1, m0) {\n\t\tswapWeeks(rcv, m1, m0)\n\t}\n\tif less(rcv, m2, m1) {\n\t\tswapWeeks(rcv, m2, m1)\n\t}\n\tif less(rcv, m1, m0) {\n\t\tswapWeeks(rcv, m1, m0)\n\t}\n\t// now rcv[m0] <= rcv[m1] <= rcv[m2]\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func ExampleCenteredAvg() {\n\txi := []int{2, 3, 4, 5, 6, 7}\n\tfmt.Println(CenteredAvg(xi))\n\t//Output:\n\t//4.5\n}", "func (tr Row) FloatErr(nn int) (val float64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase float64, float32:\n\t\tval = reflect.ValueOf(data).Float()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i >= 2<<53 || i <= -(2<<53) {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(i)\n\t\t}\n\tcase uint64, uint32, uint16, uint8:\n\t\tu := reflect.ValueOf(data).Uint()\n\t\tif u >= 2<<53 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(u)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseFloat(string(data), 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}", "func Average(values ...float64) float64 {\n\tsum := Sum(values...)\n\treturn sum / float64(len(values))\n}", "func (o *SignalPersonName) GetMiddleName() string {\n\tif o == nil || o.MiddleName.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.MiddleName.Get()\n}", "func average(data []float64) float64 {\n\tvar average float64\n\tif len(data) == 0 {\n\t\treturn average\n\t}\n\tfor index := 0; index < len(data); index++ {\n\t\taverage += data[index]\n\t}\n\treturn average / float64(len(data))\n}", "func ThirdQuartile(values []float64) float64 {\n\treturn Percentile(values, 75.0)\n}", "func (s *Simplex) GetMinRatioRow(pivotColumn int) int {\n\tminRatio := maxRatio\n\tposition := -1\n\tfor i := 1; i < s.RowsSize; i++ {\n\t\telementValue := s.Tableau[i][pivotColumn]\n\t\tif elementValue > 0 && s.Tableau[i][s.ColumnsSize-1] > 0 {\n\t\t\tratio := s.Tableau[i][s.ColumnsSize-1] / elementValue\n\t\t\tif ratio < minRatio { //Bland's rule (always choose the lower index)\n\t\t\t\tminRatio = ratio\n\t\t\t\tposition = i\n\t\t\t}\n\t\t}\n\t}\n\treturn position\n}", "func Get_range_median(c []int, l int) (int, int){\n s := 0\n e := 0\n if (len(c) > 2 * l){\n if(len(c) % 2 == 1){\n s = (len(c)/2) - l\n e = (len(c)/2) + l + 1\n }else{\n s = (len(c)/2) -l\n e = (len(c)/2) + l \n }\n }else{\n s = 0\n e = len(c)\n }\n\n return s, e\n}", "func negMeanRows(in anydiff.Res, cols int) anydiff.Res {\n\tif in.Output().Len()%cols != 0 {\n\t\tpanic(\"column count must divide input size\")\n\t}\n\trows := in.Output().Len() / cols\n\tscaler := in.Output().Creator().MakeNumeric(-1 / float64(rows))\n\tout := anyvec.SumRows(in.Output().Copy(), cols)\n\tout.Scale(scaler)\n\treturn &meanRowsRes{\n\t\tIn: in,\n\t\tScaler: scaler,\n\t\tOut: out,\n\t}\n}", "func Average(xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\treturn 0\n\t}\n\n\ttotal := 0.0\n\tfor _, v := range xs {\n\t\ttotal += v\n\t}\n\treturn total / float64(len(xs))\n}", "func median(nums []int) (float64, error) {\n\tisEven := len(nums)%2 == 0\n\tmidpoint := len(nums) / 2\n\n\tif len(nums) == 0 {\n\t\treturn 0.0, errors.New(\"given list cannot be empty\")\n\t} else if isEven {\n\t\treturn (float64(nums[midpoint-1]) + float64(nums[midpoint])) / 2, nil\n\t} else {\n\t\treturn float64(nums[midpoint]), nil\n\t}\n}", "func FillMean(ts TimeSeries) (TimeSeries, error) {\n\tif len(ts) < 3 {\n\t\tlog.Printf(\"not enough data to impute\")\n\t\treturn ts, nil\n\t}\n\tkeys := make([]string, 0)\n\tvar mean float64 = 0\n\tfor k, v := range ts {\n\t\tkeys = append(keys, k)\n\t\tmean += v\n\t}\n\tmean = mean / float64(len(keys))\n\n\tvar parseFormat string\n\tswitch len(keys[0]) {\n\tcase 4:\n\t\tparseFormat = yearfmt\n\tcase 7:\n\t\tparseFormat = monthfmt\n\tcase 10:\n\t\tparseFormat = dayfmt\n\t}\n\n\tif parseFormat == \"\" {\n\t\treturn ts, errors.New(\"date format is not ISO 8601\")\n\t}\n\n\tyStep, mStep, dStep := diff(keys, parseFormat)\n\n\tlog.Printf(\"Step is equal to : %v years, %v months, %v days \\n\", yStep, mStep, dStep)\n\n\tsort.Strings(keys)\n\n\t//TODO(eftekhari-mhs): Handle errors.\n\tstartDate, _ := time.Parse(parseFormat, keys[0])\n\tendDate, _ := time.Parse(parseFormat, keys[len(keys)-1])\n\n\tfor d := startDate; d.After(endDate) == false; d = d.AddDate(yStep, mStep, dStep) {\n\t\tif _, ok := ts[fmt.Sprint(d.Format(parseFormat))]; !ok {\n\t\t\tts[fmt.Sprint(d.Format(parseFormat))] = mean\n\t\t}\n\t}\n\treturn ts, nil\n}", "func avgInterpolateAt(src image.Image, x, y, kw, kh int) color.Color {\n\tymin := max(y-kh/2, src.Bounds().Min.Y)\n\tymax := min(y+kh/2+1, src.Bounds().Max.Y)\n\txmin := max(x-kw/2, src.Bounds().Min.X)\n\txmax := min(x+kw/2+1, src.Bounds().Max.X)\n\n\treturn averager(src, image.Rect(xmin, ymin, xmax, ymax))\n}", "func NewMedian() MovingAverage {\n\treturn &median{\n\t\tdst: make([]float64, 3),\n\t}\n}", "func Mean(xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\treturn math.NaN()\n\t}\n\tm := 0.0\n\tfor i, x := range xs {\n\t\tm += (x - m) / float64(i+1)\n\t}\n\treturn m\n}", "func average(arg1, arg2, arg3 float64) float64 {\n\ttotal := arg1 + arg2 + arg3\n\treturn total/3\n}", "func FindMedian(array []float64) float64 {\n\tlength := len(array)\n\tisOdd := (length % 2) == 1\n\n\tif isOdd {\n\t\treturn quickselect(length/2, array)\n\t}\n\treturn 0.5 * (quickselect(length/2, array) + quickselect(length/2-1, array))\n}", "func (tr Row) Float(nn int) (val float64) {\n\tval, err := tr.FloatErr(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (ph *PHash) mean(img [][]float32) float32 {\n\tvar c int\n\tvar s float32\n\tfor i := range img {\n\t\tc += len(img[i])\n\t\tfor j := range img[i] {\n\t\t\ts += img[i][j]\n\t\t}\n\t}\n\treturn s / float32(c)\n}", "func calcMeanOverAll(mtx [][]float64, n int) float64 {\n\tvar sum float64\n\tfor i := 0; i < len(mtx); i++ {\n\t\tfor j := 0; j < len(mtx[i]); j++ {\n\t\t\tsum += mtx[i][j]\n\t\t}\n\t}\n\treturn sum / float64(n)\n}", "func (me TxsdPresentationAttributesTextContentElementsAlignmentBaseline) IsMiddle() bool {\n\treturn me.String() == \"middle\"\n}", "func computeAverage(array []float64) float64 {\n\tresult := 0.0\n\tfor _, item := range array {\n\t\tresult += item\n\t}\n\treturn result / float64(len(array))\n}", "func valueLeftOf(row []string, position int) *float64 {\n\tif position <= 0 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position-1])\n}", "func Average(series []Series) (Series, error) {\n\treturn applyOperator(series, OperatorAverage)\n}", "func calculateCombinedMetric(nodeValues [][][]float64, isAverage bool) [][]float64 {\n numNodes := len(nodeValues)\n if numNodes == 0 {\n return [][]float64{}\n }\n if numNodes == 1 {\n return nodeValues[0]\n }\n // we assume all nodes have value array of same length\n numIntervals := len(nodeValues[0])\n newValues := make([][]float64, numIntervals)\n for i := 0; i < numIntervals; i++ {\n newValues[i] = []float64{nodeValues[0][i][0]}\n for j := 0; j < numNodes; j++ {\n value := nodeValues[j][i]\n if len(value) >= 2 {\n if len(newValues[i]) >= 2 {\n newValues[i][1] += value[1]\n } else {\n newValues[i] = append(newValues[i], value[1])\n }\n }\n }\n }\n if isAverage {\n for i := 0; i < numIntervals; i++ {\n if len(newValues[i]) >= 2 {\n newValues[i][1] = newValues[i][1] / float64(numNodes)\n }\n }\n }\n return newValues\n}", "func cdivSlice(out, a []float64, c float64)", "func MinAvgTwoSlice(A []int) int {\n\t// Get A length\n\tn := len(A)\n\n\t// New variables\n\tminAvg := float64(10000)\n\tresult := 0\n\n\tfor i := 0; i < n-1; i++ {\n\t\t// The minimal of 2 consecutive slices\n\t\tif i+1 < n {\n\t\t\tavg := float64(A[i]+A[i+1]) / float64(2.0)\n\t\t\tif minAvg > avg {\n\t\t\t\tminAvg = avg\n\t\t\t\tresult = i\n\t\t\t}\n\t\t}\n\n\t\t// The minimal of 3 consecutive slices\n\t\tif i+2 < n {\n\t\t\tavg := float64(A[i]+A[i+1]+A[i+2]) / float64(3.0)\n\t\t\tif minAvg > avg {\n\t\t\t\tminAvg = avg\n\t\t\t\tresult = i\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func middleNode(head *ListNode) *ListNode {\r\n\tvar (\r\n\t\tp *ListNode\r\n\t\tl, i, m int\r\n\t)\r\n\tfor l, p = 0, head; p != nil; p = p.Next {\r\n\t\tl += 1\r\n\t}\r\n\t\r\n\tfor m, i, p = l / 2, 0, head; i < m; i++ {\r\n\t\tp = p.Next\r\n\t}\r\n\treturn p\r\n}", "func avgAggregatedMeasurement(agg []AggregatedMeasurement) AggregatedMeasurement {\n avg := AggregatedMeasurement{}\n t := int64(0)\n for _,v := range agg {\n avg.Name = v.Name\n avg.Jaccard += v.Jaccard\n t += int64(v.ElapsedTime)\n }\n avg.Jaccard = avg.Jaccard / float64(len(agg))\n avg.ElapsedTime = time.Duration(t / int64(len(agg)))\n return avg\n}", "func getFirstNonEmptyStringOrNA(first string, second string) string {\n\tif strings.TrimSpace(first) != \"\" {\n\t\treturn first\n\t} else if strings.TrimSpace(second) != \"\" {\n\t\treturn second\n\t} else {\n\t\treturn \"N/A\"\n\t}\n}", "func (f *Flex) AlignMiddle() (out *Flex) {\n\tf.Alignment = Middle\n\treturn f\n}", "func Mean(v []float64) float64 {\n\ttotal := Sum(v)\n\treturn total / float64(len(v))\n}", "func FindMiddle(head *linkedlist.Node) int {\n\n\tslowNode, fastNode := head, head\n\n\tif head != nil {\n\t\tfor fastNode != nil && fastNode.Next != nil {\n\t\t\tfastNode = fastNode.Next.Next\n\t\t\tslowNode = slowNode.Next\n\t\t}\n\t}\n\treturn slowNode.Data\n}", "func minSlice(out, a, b []float64)", "func (s *GeomSuite) TestCrossParallellIsNaN(c *C) {\n\tx, y := CrossLines(1., 1., 4., 1., 2., 2., 4., 2.)\n\tc.Check(math.IsNaN(x), Equals, true)\n\tc.Check(math.IsNaN(y), Equals, true)\n}", "func NewMean(metadata JSONString) (*Mean, error) {\n\t// fetch band name\n\tresult := gjson.Get(string(metadata), \"bands.0.id\")\n\tif result.String() == \"\" {\n\t\treturn nil, errors.Errorf(\"failed to find band ID in metadata\")\n\t}\n\n\treturn &Mean{ColumnName: result.String()}, nil\n}", "func (c *Client) GetMid(uid int) (int64, error) {\n\tpath := fmt.Sprintf(\"mid/%d\", uid)\n\traw, err := c.sendRequest(path, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar resp midResult\n\terr = json.Unmarshal(raw, &resp)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif resp.Status != 0 {\n\t\treturn 0, newError(resp.Status)\n\t}\n\n\treturn resp.Mid, nil\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 median(vec []float64) (float64, bool) {\n\tn := len(vec)\n\tn_2 := n / 2\n\tif n%2 == 0 {\n\t\treturn (vec[n_2-1] + vec[n_2]) / 2, false\n\t} else {\n\t\treturn vec[n_2], true\n\t}\n\n}", "func EvalCaptchaMid(captcha string) int {\n\tlen := utf8.RuneCountInString(captcha)\n\tvar runeList []rune\n\truneList = make([]rune, len+1, len+1)\n\tpos := 0\n\tfor _, rune := range captcha {\n\t\truneList[pos] = rune\n\t\tpos++\n\t}\n\truneList[len] = runeList[0]\n\tsum := 0\n\tfor i := 0; i < len; i++ {\n\t\tif unicode.IsDigit(runeList[i]) && (runeList[i] == runeList[(i+(len/2))%len]) {\n\t\t\tsum += int(runeList[i] - '0')\n\t\t}\n\t}\n\treturn sum\n}", "func (o *WObj) SetMiddle(x, y float64) {\n\tw, h := o.Bounds()\n\to.SetTopLeft(x-w/2, y-h/2)\n}", "func average(n ...float64) float64 {\n\tvar total float64\n\tfor _, v := range n {\n\t\ttotal += v\n\t}\n\n\treturn total / float64(len(n))\n}", "func minSliceElement(a []float64) float64", "func Average(input []float64) float64 {\n\treturn SumFloat64s(input) / float64(len(input))\n}", "func Average(numbers []float64) float64 {\n\tif len(numbers) == 0 {\n\t\treturn 0\n\t}\n\ttotal := float64(0)\n\tfor _, x := range numbers {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(numbers))\n}", "func (m *Matrix) Row(cur int) []qrvalue {\n\tif cur >= m.height || cur < 0 {\n\t\treturn nil\n\t}\n\n\tcol := make([]qrvalue, m.height)\n\tfor w := 0; w < m.width; w++ {\n\t\tcol[w] = m.mat[w][cur]\n\t}\n\treturn col\n}", "func Average(items []Value) float64 {\n\tif len(items) == 0 {\n\t\treturn 0\n\t}\n\treturn float64(Sum(items)) / float64(len(items))\n}", "func calcApplyRowsHouseholderTransformation(mtxA [][]float64, c int, mtxY [][]float64, n int) {\n\tdenominator := calcRowsSumProduct(mtxA, c, mtxA, c, c, n)\n\tnumerator := calcRowsSumProduct(mtxA, c, mtxY, 0, c, n)\n\tfactor := 2 * (numerator / denominator)\n\tfor row := c; row < n; row++ {\n\t\tputDouble(mtxY, row, getDouble(mtxY, row)-factor*mtxA[c][row])\n\t}\n}", "func TestAverageSeriesWithWildcards(t *testing.T) {\n\tnow32 := int64(time.Now().Unix())\n\n\ttests := []th.MultiReturnEvalTestItem{\n\t\t{\n\t\t\t\"averageSeriesWithWildcards(metric1.foo.*.*,1,2)\",\n\t\t\tmap[parser.MetricRequest][]*types.MetricData{\n\t\t\t\t{\"metric1.foo.*.*\", 0, 1}: {\n\t\t\t\t\ttypes.MakeMetricData(\"metric1.foo.bar1.baz\", []float64{1, 2, 3, 4, 5}, 1, now32),\n\t\t\t\t\ttypes.MakeMetricData(\"metric1.foo.bar1.qux\", []float64{6, 7, 8, 9, 10}, 1, now32),\n\t\t\t\t\ttypes.MakeMetricData(\"metric1.foo.bar2.baz\", []float64{11, 12, 13, 14, 15}, 1, now32),\n\t\t\t\t\ttypes.MakeMetricData(\"metric1.foo.bar2.qux\", []float64{7, 8, 9, 10, 11}, 1, now32),\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"averageSeriesWithWildcards\",\n\t\t\tmap[string][]*types.MetricData{\n\t\t\t\t\"metric1.baz\": {types.MakeMetricData(\"metric1.baz\", []float64{6, 7, 8, 9, 10}, 1, now32).SetTag(\"aggregatedBy\", \"average\").SetNameTag(\"metric1.foo.*.*\")},\n\t\t\t\t\"metric1.qux\": {types.MakeMetricData(\"metric1.qux\", []float64{6.5, 7.5, 8.5, 9.5, 10.5}, 1, now32).SetTag(\"aggregatedBy\", \"average\").SetNameTag(\"metric1.foo.*.*\")},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\ttestName := tt.Target\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\tth.TestMultiReturnEvalExpr(t, &tt)\n\t\t})\n\t}\n\n}", "func NewMedianExpr(scanner parser.Scanner, a, b Expr) Expr {\n\ttype Agg struct {\n\t\th float64Heap\n\t\tn int\n\t}\n\treturn NewReduceExpr(\n\t\tscanner, a, ExprAsFunction(b), \"%s min ???\",\n\t\tfunc(s Set) (interface{}, error) {\n\t\t\tif n := s.Count(); n > 0 {\n\t\t\t\treturn Agg{h: make(float64Heap, 0, n/2+2), n: n}, nil\n\t\t\t}\n\t\t\treturn nil, errors.Errorf(\"Empty set has no mean\")\n\t\t},\n\t\tfunc(acc interface{}, v Value) (interface{}, error) {\n\t\t\tagg := acc.(Agg)\n\t\t\tswitch v := v.(type) {\n\t\t\tcase Number:\n\t\t\t\theap.Push(&agg.h, v.Float64())\n\t\t\t\tif len(agg.h) == cap(agg.h) {\n\t\t\t\t\theap.Pop(&agg.h)\n\t\t\t\t}\n\t\t\t\treturn agg, nil\n\t\t\t}\n\t\t\treturn nil, errors.Errorf(\"Non-numeric value used in mean\")\n\t\t},\n\t\tfunc(acc interface{}) (Value, error) {\n\t\t\tif acc != nil {\n\t\t\t\tagg := acc.(Agg)\n\t\t\t\ta := heap.Pop(&agg.h).(float64)\n\t\t\t\tif agg.n%2 == 0 {\n\t\t\t\t\tb := heap.Pop(&agg.h).(float64)\n\t\t\t\t\treturn NewNumber(0.5 * (a + b)), nil\n\t\t\t\t}\n\t\t\t\treturn NewNumber(a), nil\n\t\t\t}\n\t\t\treturn nil, errors.Errorf(\"Empty input to min\")\n\t\t},\n\t)\n}", "func (s *fakeSub) inMiddleThird() bool {\n\telapsed := time.Since(s.start)\n\treturn elapsed > runFor/3 && elapsed < runFor*2/3\n}", "func (ss SliceType) Median() ElementType {\n\tl := len(ss)\n\n\tswitch {\n\tcase l == 0:\n\t\treturn ElementZeroValue\n\n\tcase l == 1:\n\t\treturn ss[0]\n\t}\n\n\tsorted := ss.Sort()\n\n\tif l%2 != 0 {\n\t\treturn sorted[l/2]\n\t}\n\n\treturn (sorted[l/2-1] + sorted[l/2]) / 2\n}", "func (o *MicrosoftGraphEducationUser) GetMiddleName() string {\n\tif o == nil || o.MiddleName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.MiddleName\n}", "func divideMetricForAllNodes(\n nodeValuesNumerator [][][]float64,\n nodeValuesDenominator [][][]float64,\n) [][][]float64 {\n // we will take minimum lengths just in case the lengths do not match up\n numNodes := len(nodeValuesNumerator)\n if len(nodeValuesDenominator) < numNodes {\n numNodes = len(nodeValuesDenominator)\n }\n resultMetric := make([][][]float64, numNodes)\n for i := 0; i < numNodes; i++ {\n numIntervals := len(nodeValuesNumerator[i])\n if len(nodeValuesDenominator[i]) < numIntervals {\n numIntervals = len(nodeValuesDenominator[i])\n }\n resultMetric[i] = make([][]float64, numIntervals)\n for j := 0; j < numIntervals; j++ {\n if len(nodeValuesNumerator[i][j]) < 2 ||\n len(nodeValuesDenominator[i][j]) < 2 {\n // Handle case where data at window is empty\n resultMetric[i][j] = []float64{nodeValuesNumerator[i][j][0]}\n } else if nodeValuesDenominator[i][j][1] != 0 {\n // Handle divide by 0 case\n // Note: we are comparing a float to 0 to avoid dividing by 0.\n // This will only catch the cases where the float value is exactly 0\n resultMetric[i][j] = []float64{\n nodeValuesNumerator[i][j][0],\n nodeValuesNumerator[i][j][1] /\n nodeValuesDenominator[i][j][1]}\n } else {\n resultMetric[i][j] = []float64{nodeValuesNumerator[i][j][0], 0}\n }\n }\n }\n return resultMetric\n}", "func main() {\n xs := []float64{98,93,77,82,83}\n fmt.Println(average(xs))\n}", "func SimpleMean(x []float64) (float64, error) {\n\tif len(x) == 0 {\n\t\treturn 0.0, errors.New(\"cannot calculate the average of an empty slice\")\n\t}\n\ts := 0.0\n\tfor _, v := range x {\n\t\ts += v\n\t}\n\treturn s / float64(len(x)), nil\n}", "func Average(tas ...*TA) *TA {\n\tln := tas[0].Len()\n\tfor i := 1; i < len(tas); i++ {\n\t\tif n := tas[i].Len(); n > ln {\n\t\t\tln = n\n\t\t}\n\t}\n\n\tout := NewSize(ln, true)\n\tfor i := 0; i < ln; i++ {\n\t\tvar v Decimal\n\t\tfor _, ta := range tas {\n\t\t\tif i < ta.Len() {\n\t\t\t\tv = v.Add(ta.Get(i))\n\t\t\t}\n\t\t}\n\t\tout.Append(v / Decimal(ln))\n\t}\n\n\treturn out\n}", "func divideMetricByConstant(metricValues [][]float64, constant float64) {\n for _, metric := range metricValues {\n if len(metric) >= 2 {\n metric[1] = metric[1] / constant\n }\n }\n}", "func divSlice(out, a, b []float64)", "func searchMidoffset(r io.ReaderAt, left, right int64) (s string, offset int64, err error) {\n\toffset, err = findBeginOfLine(r, left+(right-left)/2)\n\tif err != nil && err != io.EOF {\n\t\treturn\n\t}\n\n\ts, err = readLine(r, offset)\n\tif err != nil && err != io.EOF {\n\t\treturn\n\t}\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\treturn\n}", "func (o *MicrosoftGraphEducationUser) SetMiddleNameExplicitNull(b bool) {\n\to.MiddleName = nil\n\to.isExplicitNullMiddleName = b\n}", "func (records DataRecs) Median() (float64) {\n\n\n\tmedianValue := 0.0\n\n\t// sort the numbers from lowest to highest\n\tsort.Sort(records)\n\n\tnumberOfItems := len(records)\n\n\t// For an even number of values, calculate the average of the two central numbers\n\tif numberOfItems % 2 == 0 {\n\n\t\tfirstIdx := numberOfItems / 2\n\t\tsecondIdx := firstIdx + 1\n\n\t\t//fmt.Printf(\" numberOfItems %d idx1st %d 2ndidx %d\\n\", numberOfItems, firstIdx, secondIdx)\n\t\trecordedValueFirst := fromStringToFloat(records[firstIdx].RecordedValue)\n\t\trecordedValueSecond := fromStringToFloat(records[secondIdx].RecordedValue)\n\n\t\tif recordedValueSecond == 0.0 { // To avoid Division by Zero just return 0.0\n\t\t\treturn 0.0\n\t\t}\n\t\t//fmt.Printf(\"Odd number Median %f %f\\n\", recordedValueFirst, recordedValueSecond)\n\t\tmedianValue = (recordedValueFirst + recordedValueSecond) / float64(2)\n\t\t//fmt.Printf(\"Meian value is %f \\n\", medianValue)\n\n\n\t} else { // For an odd number of values, just take the middle number\n\n\t\tidx := (numberOfItems / 2) + 1\n\t\t//fmt.Printf(\" numberOfItems %d idx %d\", numberOfItems, idx)\n\t\tmedianValue = fromStringToFloat(records[idx].RecordedValue)\n\t\t//fmt.Printf(\"Meian value is %f \\n\", medianValue)\n\t}\n\n\tmedianValue = fromStringToFloat(fmt.Sprintf(\"%.2f\", medianValue))\n\n\treturn medianValue\n}" ]
[ "0.51766354", "0.46247548", "0.44273514", "0.440374", "0.42990997", "0.40641436", "0.40119344", "0.39859194", "0.39596558", "0.39416143", "0.39316308", "0.39045584", "0.38995808", "0.38463324", "0.38020673", "0.37773892", "0.3768565", "0.3753118", "0.37261394", "0.37159556", "0.37135485", "0.36960196", "0.36809084", "0.36772695", "0.36698884", "0.3668051", "0.36599848", "0.36400536", "0.3624898", "0.36214957", "0.36100438", "0.3593585", "0.35835615", "0.35819706", "0.35689083", "0.3566735", "0.35443798", "0.35443798", "0.3542533", "0.3540013", "0.35282147", "0.35281596", "0.35188758", "0.35174096", "0.35067463", "0.35048094", "0.350253", "0.35014442", "0.3501175", "0.34956", "0.34949827", "0.34934983", "0.3492038", "0.34887975", "0.34850496", "0.3480329", "0.34779027", "0.3454668", "0.34355032", "0.34223494", "0.34155762", "0.34121332", "0.3408515", "0.3407734", "0.34063607", "0.34059715", "0.34049398", "0.34005424", "0.33966792", "0.33938715", "0.33938643", "0.33881953", "0.33848396", "0.33803338", "0.33800727", "0.33742857", "0.33736286", "0.33683348", "0.3359115", "0.335152", "0.33504835", "0.33250082", "0.33241457", "0.33125007", "0.3312282", "0.33111203", "0.33060443", "0.32970768", "0.32768974", "0.32750863", "0.32712877", "0.32642496", "0.32604405", "0.32582024", "0.32566965", "0.32533172", "0.3251588", "0.32513648", "0.32479885", "0.32420948" ]
0.72314984
0
isNaN returns true if the given string can't be interpreted as a number.
func isNaN(val string) bool { if val == nan { return true } _, err := strconv.ParseFloat(val, 64) return err != nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isNum(str string) bool {\n\t_, err := strconv.Atoi(str)\n\treturn err == nil\n}", "func IsNumber(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tfor _, r := range s {\n\t\tif !unicode.IsDigit(r) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsNumeric(str string) bool {\n\tif IsNull(str) {\n\t\treturn true\n\t}\n\treturn rxNumeric.MatchString(str)\n}", "func (v *validator) isNumeric(s string) error {\n\tif numericRegex.MatchString(s) {\n\t\t// [^ 0-9]\n\t\treturn ErrNonNumeric\n\t}\n\treturn nil\n}", "func StringIsNumeric(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\treturn err == nil\n}", "func IsNumber(str string) bool {\n\treg, _ := regexp.Compile(`^(\\-)?\\d+(\\.)?(\\d+)?$`)\n\treturn reg.MatchString(str)\n}", "func IsNumeric(s string) bool {\n\tvar (\n\t\tdotCount = 0\n\t\tlength = len(s)\n\t)\n\tif length == 0 {\n\t\treturn false\n\t}\n\tfor i := 0; i < length; i++ {\n\t\tif s[i] == '-' && i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif s[i] == '.' {\n\t\t\tdotCount++\n\t\t\tif i > 0 && i < length-1 {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif s[i] < '0' || s[i] > '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\tif dotCount > 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsNumeric(v any) bool {\n\tif v == nil {\n\t\treturn false\n\t}\n\n\tif s, err := strutil.ToString(v); err == nil {\n\t\treturn s != \"\" && rxNumber.MatchString(s)\n\t}\n\treturn false\n}", "func IsStringNumber(s string) bool {\n\treturn s != \"\" && rxNumeric.MatchString(s)\n}", "func isNumeric(s string) (bool, int) {\n\tconverted, err := strconv.ParseFloat(s, 64)\n\treturn err == nil, int(converted)\n}", "func isNum(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\tisFloat := (err == nil)\n\t_, err = strconv.ParseInt(s, 0, 64)\n\tisInt := (err == nil)\n\treturn isFloat || isInt\n}", "func isNumber(s string) bool {\n\tfor _, r := range s {\n\t\tif !unicode.IsNumber(r) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsNumeric(str string) bool {\n\tfor _, c := range str {\n\t\tif !unicode.IsDigit(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (s String) IsNumeric() bool {\n\treturn govalidator.IsFloat(s.String())\n}", "func Numeric(s string) bool {\n\tfor _, v := range s {\n\t\tif '9' < v || v < '0' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsNumber(v any) bool {\n\tif v == nil {\n\t\treturn false\n\t}\n\n\tif s, err := strutil.ToString(v); err == nil {\n\t\treturn s != \"\" && rxNumber.MatchString(s)\n\t}\n\treturn false\n}", "func IsStringNumber(s string) bool {\n\treturn s != \"\" && rxNumber.MatchString(s)\n}", "func isNumeric(t string) bool {\n\treturn strings.Contains(t, \"int\") || strings.Contains(t, \"bool\") || strings.Contains(t, \"float\") || strings.Contains(t, \"byte\")\n}", "func IsNumericValue(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\treturn err == nil\n}", "func ValidateStrNumeric(str string) bool { //\n\tvar re = regexp.MustCompile(`^[0-9]+$`)\n\tif len(re.FindStringIndex(str)) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func IsNumber(c rune) bool {\r\n\tvar cIsANum bool = false\r\n\tif c >= '0' && c <= '9' {\r\n\t\tcIsANum = true\r\n\t}\r\n\treturn cIsANum\r\n}", "func IsNumber(v interface{}) bool {\n\treturn rxNumeric.MatchString(ToString(v))\n}", "func IsUTFLetterNumeric(str string) bool {\n\tif IsNull(str) {\n\t\treturn true\n\t}\n\tfor _, c := range str {\n\t\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (i *Interpreter) IsNumeric() bool {\n\tif _, err := strconv.Atoi(i.currentChar); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func CheckNumber(str string) bool {\n\tminus := false\n\tif len(str) == 0 {\n\t\treturn false\n\t}\n\tif str[0] == '-' && len(str) == 1 {\n\t\treturn false\n\t}\n\ti := 0\n\tfor i < len(str) && str[i] == '-' {\n\t\tif minus == true && str[i] == '-' {\n\t\t\treturn false\n\t\t}\n\t\tif str[i] == '-' {\n\t\t\tminus = true\n\t\t}\n\t}\n\tfor i < len(str) && str[i] >= '0' && str[i] <= '9' {\n\t\ti++\n\t}\n\tif i != len(str) {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsNumber(r rune) bool", "func (s *Scanner) isNumeric(c byte) bool {\n\tre := regexp.MustCompile(numeric)\n\treturn re.MatchString(string(c))\n}", "func IsNumber(character string) bool {\n\tnumberRegex := regexp.MustCompile(`\\d`)\n\n\treturn numberRegex.Match([]byte(character))\n}", "func IsntLetterOrNumber(c rune) bool {\n\treturn !unicode.IsLetter(c) && !unicode.IsNumber(c)\n}", "func IsDigit(s string) bool {\n\t_, err := strconv.Atoi(s)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func validateNumericLiteral(literal string) bool {\n\t// strip minus for negative number\n\tif literal[0] == '-' {\n\t\tliteral = literal[1:]\n\t}\n\n\tif len(literal) > 1 && literal[0] == '0' && literal[1] != '.' {\n\t\treturn false\n\t}\n\tif literal[len(literal)-1] == '.' {\n\t\treturn false\n\t}\n\treturn true\n}", "func Valid(s string) bool {\n\n\ts = stripAllBlanks(s)\n\n\tre := regexp.MustCompile(`[^\\d\\s]`)\n\tif re.MatchString(s) || len(s) <= 1 {\n\t\treturn false\n\t}\n\n\tsplit := strings.Split(s, \"\")\n\n\tfor i := len(split) - 2; i >= 0; i = i - 2 {\n\t\tsplit[i] = doubleDigit(split[i])\n\t}\n\n\tvalid := checkValidDigits(split)\n\n\treturn valid\n}", "func (v *validator) HasNotDigit(str, errorMessage string) bool {\n\tif _, ok := v.Errors[\"error\"]; ok {\n\t\treturn false\n\t}\n\n\tisMatched, _ := regexp.MatchString(`[\\d]`, str)\n\n\tif isMatched {\n\t\tv.Errors[\"error\"] = errMessage{message: errorMessage}.Error()\n\t\treturn false\n\t}\n\n\treturn true\n}", "func IsNumericSpace(str string) bool {\n\tfor _, c := range str {\n\t\tif !unicode.IsDigit(c) && !unicode.IsSpace(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsDigit(s string) bool {\n\tfor _, r := range s {\n\t\tif !unicode.IsDigit(r) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t *KValidator) IsNumeric() bool {\n\tswitch t.data.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:\n\t\treturn true\n\tdefault:\n\t\treturn numericRegex.MatchString(t.data.String())\n\t}\n}", "func IsNumeric(val interface{}) bool {\n\tswitch val.(type) {\n\tcase int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, json.Number:\n\t\treturn true\n\t}\n\treturn false\n}", "func UTFLetterNumeric(s string) bool {\n\tfor _, v := range s {\n\t\tif !unicode.IsLetter(v) && !unicode.IsNumber(v) { //letters && numbers are ok\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (e stringElement) IsNaN() bool {\n\tif !e.valid {\n\t\treturn true\n\t}\n\tf, err := strconv.ParseFloat(e.e, 64)\n\tif err == nil {\n\t\treturn math.IsNaN(f)\n\t}\n\treturn true\n}", "func String(s string) bool {\n\tfor i := 0; i < len(s); i++ {\n\t\tif b := s[i]; b < '0' || b > '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isNaN(f float64) bool {\n\treturn f != f\n}", "func isNaN(f float64) bool {\n\treturn f != f\n}", "func Valid(s string) bool {\n\t// Invalidate if the string contains invalid characters.\n\tif invalidChars.MatchString(s) {\n\t\treturn false\n\t}\n\n\ts = numericOnly.ReplaceAllString(s, \"\")\n\tlength := len(s)\n\n\t// Invalidate if the string has less than 2 characters.\n\tif length <= 1 {\n\t\treturn false\n\t}\n\n\tsum := 0\n\tfor i := 0; i < length; i++ {\n\t\td := string(s[length-i-1])\n\n\t\t// Disregards error because it is not being tested in the test cases.\n\t\tn, _ := strconv.Atoi(d)\n\n\t\tif i%2 != 0 {\n\t\t\tn *= 2\n\t\t\tif n > 9 {\n\t\t\t\tn -= 9\n\t\t\t}\n\t\t}\n\t\tsum += n\n\t}\n\n\treturn sum%10 == 0\n}", "func isInt(s string) bool {\n\tfor _, c := range s {\n\t\tif !unicode.IsDigit(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t *KValidator) IsNumber() bool {\n\tswitch t.data.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:\n\t\treturn true\n\tdefault:\n\t\treturn numberRegex.MatchString(t.data.String())\n\t}\n}", "func HasOnlyNumbers(yourString string) bool {\n\treturn checkForMatch(numbersMatch, yourString) &&\n\t\t!checkForMatch(lettersMatch, yourString) &&\n\t\t!checkForMatch(punctuationMatch, yourString)\n}", "func (me TxsdConfidenceRating) IsNumeric() bool { return me.String() == \"numeric\" }", "func isNumber(c byte) bool {\n\tif _, err := asciiToNumber(c); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func Valid(s string) bool {\n\ts = strings.Replace(s, \" \", \"\", -1)\n\tif len(s) < 2 {\n\t\treturn false\n\t}\n\n\tfor _, v := range s {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tvar sum int\n\tvar temp int\n\n\ttarget := len(s) % 2\n\tfor i := len(s) - 1; i > -1; i-- {\n\t\ttemp = int(s[i]) - 48\n\t\tif i%2 == target {\n\t\t\ttemp *= 2\n\t\t\tif temp > 9 {\n\t\t\t\ttemp -= 9\n\t\t\t}\n\t\t}\n\t\tsum += temp\n\t}\n\n\treturn (sum % 10) == 0\n}", "func containsOnlyDigits(s string) bool {\n\tisNotDigit := func(c rune) bool { return c < '0' || c > '9' }\n\n\treturn strings.IndexFunc(s, isNotDigit) == -1\n}", "func Valid(str string) bool {\n\tvar sum, count int\n\tvar secondNumberFlipper bool\n\tfor i := len(str) - 1; i >= 0; i-- {\n\t\t// Can be space.\n\t\tif str[i] == ' ' {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Returning false if containing non-digits.\n\t\tif str[i] < '0' || '9' < str[i] {\n\t\t\treturn false\n\t\t}\n\n\t\tnum := int(str[i] - '0')\n\t\tif secondNumberFlipper {\n\t\t\t// Double every second digit.\n\t\t\tnum += num\n\t\t\tif num > 9 {\n\t\t\t\tnum -= 9\n\t\t\t}\n\t\t}\n\t\tsum += num\n\t\tcount++\n\n\t\t// Flip the flipper.\n\t\tsecondNumberFlipper = !secondNumberFlipper\n\t}\n\treturn count > 1 && sum%10 == 0\n}", "func IsNumeric(dataType DataType) bool {\n\treturn (dataType >= Int8 && dataType <= Float32) || dataType == Int64\n}", "func (l *Lexer) isNumber(char rune) bool {\n\treturn char >= '0' && char <= '9'\n}", "func Valid(number string) bool {\n\tnumber = strings.ReplaceAll(number, \" \", \"\")\n\tlength := len(number)\n\tif length <= 1 {\n\t\treturn false\n\t}\n\trunes := []rune(number)\n\ttotal, d := 0, 0\n\tdouble := length%2 == 0\n\n\tfor _, r := range runes {\n\t\tif !unicode.IsDigit(r) {\n\t\t\treturn false\n\t\t}\n\t\td = int(r - '0')\n\t\tif double {\n\t\t\td *= 2\n\t\t\tif d > 9 {\n\t\t\t\td -= 9\n\t\t\t}\n\t\t}\n\t\ttotal += d\n\t\tdouble = !double\n\t}\n\treturn total%10 == 0\n}", "func (t Token) IsNumeric() bool {\n\tfor _, v := range t.Value {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Valid(s string) bool {\n\ts = strings.ReplaceAll(s, \" \", \"\")\n\tresult := 0\n\tif len(s) <= 1 {\n\t\treturn false\n\t}\n\toddLength := len(s) % 2\n\tfor i, digit := range s {\n\t\tnumber := int(digit - '0')\n\t\tif number >= 0 && number <= 9 {\n\t\t\tif i%2 == oddLength {\n\t\t\t\tnumber *= 2\n\t\t\t\tif number > 9 {\n\t\t\t\t\tnumber -= 9\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult += number\n\t\t} else { // if it's not a number return false\n\t\t\treturn false\n\t\t}\n\t}\n\treturn result%10 == 0\n}", "func IsNumber(n int) bool {\n\tif n < 10 {\n\t\treturn true\n\t}\n\tdigits := strconv.Itoa(n)\n\tp := len(digits)\n\tfor _, d := range digits {\n\t\tx, _ := strconv.Atoi(string(d))\n\t\tn -= int(math.Pow(float64(x), float64(p)))\n\t}\n\treturn n == 0\n}", "func (t Token) IsNumeric() bool {\n\treturn tNumStart <= t.Kind && t.Kind <= tNumEnd\n}", "func Valid(number string) bool {\n\tnumber = strings.Replace(number, \" \", \"\", -1)\n\n\t// Check to see if the string length is <= 1\n\tif len(number) < 2 {\n\t\treturn false\n\t}\n\n\tvar sum int64\n\tisOdd := len(number)%2 != 0\n\n\tfor i := len(number) - 1; i >= 0; i-- {\n\t\tnum, err := strconv.ParseInt(number[i:i+1], 0, 64)\n\t\t// Check to see if all values in string are valid digits\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif isOdd {\n\t\t\tif i%2 != 0 {\n\t\t\t\tnum *= 2\n\t\t\t\tif num > 9 {\n\t\t\t\t\tnum -= 9\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tif i%2 == 0 {\n\t\t\t\tnum *= 2\n\t\t\t\tif num > 9 {\n\t\t\t\t\tnum -= 9\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsum += num\n\t}\n\treturn (sum%10 == 0)\n}", "func IsNumeric(c *Call) bool {\n\tswitch c.Name {\n\tcase \"count\", \"first\", \"last\", \"distinct\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func isvalid(s string) bool {\n\tif string(s[0]) == \"0\" {\n\t\treturn s == \"0\" // Discard \"00\" and \"000\"\n\t}\n\tvalue, _ := strconv.ParseInt(s, 10, 0)\n\treturn value >= 0 && value <= 255\n}", "func isDigit(r rune) bool {\n\tswitch r {\n\tcase '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (v *validator) isAmountImplied(s string) error {\n\tif numericRegex.MatchString(s) {\n\t\t// [^ 0-9]\n\t\treturn ErrNonAmount\n\t}\n\treturn nil\n}", "func (t *Text) IsDigit(str string) bool {\n\tfor _, v := range str {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Valid(sin string) bool {\n\tstr := strings.ReplaceAll(sin, \" \", \"\")\n\n\t// return if the string isn't of sufficient length\n\tif len(str) < 2 {\n\t\treturn false\n\t}\n\n\tmod := len(str)%2 == 0\n\ttotal := 0\n\n\tfor _, v := range str {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t\tv := int(v - '0')\n\n\t\tif mod {\n\t\t\tv *= 2\n\t\t\tif v > 9 {\n\t\t\t\tv -= 9\n\t\t\t}\n\t\t}\n\n\t\tmod = !mod\n\t\ttotal += v\n\t}\n\n\treturn total%10 == 0\n}", "func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') }", "func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') }", "func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') }", "func Valid(s string) bool {\n\ts = strings.ReplaceAll(s, \" \", \"\")\n\tif len(s) <= 1 {\n\t\treturn false\n\t}\n\tcheckDigit, err := checkSum(s)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn checkDigit%10 == 0\n}", "func IsDigit(r rune) bool {\n\tif r <= MaxLatin1 {\n\t\treturn '0' <= r && r <= '9'\n\t}\n\treturn isExcludingLatin(Digit, r)\n}", "func Valid(s string) bool {\n\tcounter, total := 0, 0\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tr := rune(s[i])\n\n\t\tif r == ' ' {\n\t\t\tcontinue\n\t\t} else if r < '0' || r > '9' {\n\t\t\treturn false\n\t\t} else {\n\t\t\ttotal += calculateValue(counter, r)\n\t\t\tcounter++\n\t\t}\n\t}\n\n\tif counter < 2 {\n\t\treturn false\n\t}\n\treturn isEvenlyDivisibleByTen(total)\n}", "func isDigit(char byte) bool {\n\treturn '0' <= char && char <= '9'\n}", "func isAlphaNum(b byte) bool {\n\treturn isAlpha(b) || (b >= '0' && b <= '9')\n}", "func Float(str string) bool {\n\t_, err := strconv.ParseFloat(str, 0)\n\treturn err == nil\n}", "func isNumber(t Type) bool {\n\treturn IsIntegral(t) || IsFloat(t) || t == Decimal\n}", "func IsDigit(r rune) bool", "func isDigit(b rune) bool {\n\treturn b >= '0' && b <= '9'\n}", "func isDigit(ch rune) bool {\n\treturn '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)\n}", "func isDigit(ch byte) bool {\n\treturn '0' <= ch && ch <= '9'\n}", "func isDigit(ch byte) bool {\n\treturn '0' <= ch && ch <= '9'\n}", "func (v *Base) parseNumber(s string) (ok bool) {\n\tnum, err := strconv.ParseFloat(s, 64)\n\tif err == nil {\n\t\t*v = Base(num)\n\t\treturn v.IsValid()\n\t}\n\treturn false\n}", "func isDigit(ch rune) bool {\n\treturn (ch >= '0' && ch <= '9')\n}", "func isNaN64(f float64) bool { return f != f }", "func Valid(number string) bool {\n\tvar total int\n\tvar count int\n\n\tfor index := len(number) - 1; index >= 0; index-- {\n\t\tr := rune(number[index])\n\t\tif r == ' ' {\n\t\t\tcontinue\n\t\t}\n\t\tif !unicode.IsDigit(r) {\n\t\t\treturn false\n\t\t}\n\t\tdigit := int(r - '0')\n\t\tif count&1 == 1 {\n\t\t\tdigit = digit * 2\n\t\t\tif digit > 9 {\n\t\t\t\tdigit -= 9\n\t\t\t}\n\t\t}\n\t\ttotal += digit\n\t\tcount++\n\t}\n\n\tif count < 2 {\n\t\treturn false\n\t}\n\n\treturn total%10 == 0\n}", "func isDigit(r rune) bool {\r\n\tif r > unicode.MaxASCII {\r\n\t\treturn false\r\n\t}\r\n\treturn r >= '0' && r <= '9'\r\n}", "func notAlphanumeric(x byte) bool {\n\treturn (((x > 57 || x < 48) && (x < 97)) || x > 122)\n}", "func validateNumber(str string) float64 {\n\tif netCharge, err := strconv.ParseFloat(str, 64); err == nil {\n\t\treturn netCharge\n\t}\n\treturn float64(-1.0)\n}", "func IsFloat(str string) bool {\n\treturn str != \"\" && rxFloat.MatchString(str)\n}", "func EsNumerico(valor string) bool {\n\t_, err := strconv.ParseInt(valor, 10, 64)\n\treturn err == nil\n}", "func (l *Lexer) isDigit(ch byte) bool {\n\treturn '0' <= ch && ch <= '9'\n}", "func validateNumber(str string) float64 {\r\n\tif netCharge, err := strconv.ParseFloat(str, 64); err == nil {\r\n\t\treturn netCharge\r\n\t}\r\n\treturn float64(-1.0)\r\n}", "func (Integer) IsNaN() bool {\n\treturn false\n}", "func isAlphaNumeric(t rune) bool {\n\treturn unicode.IsLetter(t)\n}", "func isNumeric(fl FieldLevel) bool {\n\tswitch fl.Field().Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:\n\t\treturn true\n\tdefault:\n\t\treturn numericRegex.MatchString(fl.Field().String())\n\t}\n}", "func Valid(num string) bool {\n\tvar isValid bool\n\tvar total float64\n\tvar secondDigitTotal float64\n\tvar eventDigit int\n\tnum = strings.Replace(num, \" \", \"\", -1)\n\tif len(num) > 1 {\n\t\tfor i := len(num) - 1; i >= 0; i-- { //start from last num and go backwards\n\t\t\tnumber, error := strconv.Atoi(string(num[i]))\n\t\t\t// Check to make sure it is int otherwise exit loop\n\t\t\tif error != nil {\n\t\t\t\treturn isValid\n\t\t\t}\n\t\t\tif eventDigit%2 != 0 { //check if it 2nd digit otherwise add num to total\n\t\t\t\tif number*2 > 9 {\n\t\t\t\t\tsecondDigitTotal += float64(number)*2 - 9\n\t\t\t\t} else {\n\t\t\t\t\tsecondDigitTotal += float64(number) * 2\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttotal += float64(number)\n\t\t\t}\n\t\t\teventDigit++\n\t\t}\n\t\ttotal += secondDigitTotal\n\t\tif math.Mod(total, 10) == 0 {\n\t\t\tisValid = true\n\t\t}\n\t}\n\treturn isValid\n}", "func Valid(input string) bool {\n\tsum := 0\n\tk := 0\n\tinput = reverse(input)\n\tfor i := range input {\n\t\tr := input[i]\n\t\tif r >= 48 && r <= 57 { // we only care about digits\n\t\t\tnum := int(r - '0') // convert to int\n\t\t\tif k%2 == 1 { // position where we duplicate the number\n\t\t\t\tnum = num + num\n\t\t\t\tif num > 9 {\n\t\t\t\t\tnum -= 9\n\t\t\t\t}\n\t\t\t}\n\t\t\tsum += num\n\t\t\tk++\n\t\t} else if r != ' ' { // if not space (which is ignored)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn k > 1 && sum%10 == 0\n\n}", "func (*BigInt) IsNaN() bool {\n\treturn false\n}", "func Int(str string) bool {\n\tif len(str) == 0 {\n\t\treturn true\n\t}\n\t_, err := strconv.Atoi(str)\n\n\treturn err == nil\n}", "func ValidFloatStr(val string) bool {\n\tvar validFloat = regexp.MustCompile(`^[-+]?([0-9]+(\\.[0-9]+)?)$`)\n\treturn validFloat.MatchString(val)\n}", "func (d NoDigits) Valid(v interface{}) error {\n\tstr, ok := v.(string)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"expected a string, got %T\", v))\n\t}\n\n\tif digitRegexp.MatchString(str) {\n\t\treturn d.Err\n\t}\n\n\treturn nil\n}" ]
[ "0.7339016", "0.7253218", "0.7231997", "0.7182083", "0.71742797", "0.71524066", "0.71469444", "0.7066914", "0.7063223", "0.70044315", "0.69450045", "0.69221175", "0.69198877", "0.6898566", "0.68668354", "0.67863667", "0.6740267", "0.6620472", "0.6603828", "0.65644425", "0.6504904", "0.64806145", "0.6409418", "0.6370731", "0.63336635", "0.6317643", "0.62864697", "0.6278987", "0.62468755", "0.6238702", "0.61733264", "0.6122006", "0.61153704", "0.6110263", "0.60676336", "0.6032662", "0.60313666", "0.60114044", "0.60049677", "0.59916896", "0.59266037", "0.59266037", "0.590026", "0.58759373", "0.58450526", "0.58352995", "0.583342", "0.58117557", "0.579638", "0.57891506", "0.57882726", "0.578056", "0.5770674", "0.5755343", "0.57346255", "0.5709608", "0.5666727", "0.56278634", "0.5614796", "0.5609809", "0.5598499", "0.5578393", "0.5576781", "0.5549268", "0.55444765", "0.5518087", "0.5518087", "0.5518087", "0.5475311", "0.547459", "0.54612297", "0.5444403", "0.54407036", "0.54375744", "0.54227275", "0.54172486", "0.5411508", "0.541062", "0.5408202", "0.5408202", "0.53930503", "0.53896487", "0.5387693", "0.5384738", "0.5384482", "0.5375714", "0.5363928", "0.53625786", "0.53548795", "0.53492534", "0.5347646", "0.53433174", "0.5338598", "0.53335166", "0.53327036", "0.5321626", "0.5319053", "0.5318786", "0.5317456", "0.5315469" ]
0.7575007
0
averageOf returns the average of the given floats as a string, rounded to decimalPlaces decimal places. You can supply nil floats and they will be ignored. If you only supply nils, nan will be returned.
func averageOf(decimalPlaces int, floats ...*float64) string { var total, num float64 for _, f := range floats { if f == nil { continue } num++ total += *f } if num == 0 { return nan } return strconv.FormatFloat(total/num, 'f', decimalPlaces, 64) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func average(sf ...float64) float64 {\n\ttotal := 0.0\n\tfor _, v := range sf {\n\t\ttotal = total + v\n\n\t}\n\treturn total / float64(len(sf))\n}", "func Average(values ...float64) float64 {\n\tsum := Sum(values...)\n\treturn sum / float64(len(values))\n}", "func main() {\n xs := []float64{98,93,77,82,83}\n fmt.Println(average(xs))\n}", "func ExampleAverage() {\n\tvar f float64\n\tf = Average([]float64{1, 2})\n\tfmt.Println(f)\n\t// Output:\n\t// 1.5\n}", "func Average(slice []float64) (float64, error) {\n\n\tif len(slice) == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Empty\")\n\t}\n\n\tvar sum float64\n\tfor _, n := range slice {\n\t\tsum += n\n\t}\n\n\tavg := sum / float64(len(slice))\n\t// log.Println(\"Slice average\", avg)\n\treturn math.Round(avg*100) / 100, nil\n}", "func average(arr []float64) float64 {\n\treturn sum(arr) / float64(len(arr))\n}", "func Average(numbers []float64) float64 {\n\tif len(numbers) == 0 {\n\t\treturn 0\n\t}\n\ttotal := float64(0)\n\tfor _, x := range numbers {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(numbers))\n}", "func Average(input []float64) float64 {\n\treturn SumFloat64s(input) / float64(len(input))\n}", "func ComputeAverage(dataPoints []float64) (float64, error) {\n\tif !(len(dataPoints) > 0) {\n\t\treturn 0.0, fmt.Errorf(\"Must provide a non empty collection of data points\")\n\t}\n\n\treturn stat.Mean(dataPoints, nil), nil\n}", "func Average(items []Value) float64 {\n\tif len(items) == 0 {\n\t\treturn 0\n\t}\n\treturn float64(Sum(items)) / float64(len(items))\n}", "func average(numbers ...float64) float64 {\n\tvar sum float64 = 0\n\n\tfor _, number := range numbers {\n\t\tsum += number\n\t}\n\n\treturn sum / float64(len(numbers))\n}", "func average(n ...float64) float64 {\n\tvar total float64\n\tfor _, v := range n {\n\t\ttotal += v\n\t}\n\n\treturn total / float64(len(n))\n}", "func Average(xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\treturn 0\n\t}\n\n\ttotal := 0.0\n\tfor _, v := range xs {\n\t\ttotal += v\n\t}\n\treturn total / float64(len(xs))\n}", "func average(sf ...float64) float64 {\n fmt.Println(sf, \"\\n\")\n fmt.Printf(\"%T\", sf)\n fmt.Println(\"\\n\")\n total := 0.0\n for _ , v := range sf {\n total += v\n }\n return total / float64(len(sf))\n}", "func average(data []float64) float64 {\n\tvar average float64\n\tif len(data) == 0 {\n\t\treturn average\n\t}\n\tfor index := 0; index < len(data); index++ {\n\t\taverage += data[index]\n\t}\n\treturn average / float64(len(data))\n}", "func Average(xs []float64) float64 {\n total := float64(0)\n if len(xs) == 0 {\n return total\n }\n for _, x := range xs {\n total += x\n }\n return total / float64(len(xs))\n}", "func Average(nums []float64) float64 {\n\ttotal := float64(0)\n\tfor _, num := range nums {\n\t\ttotal += num\n\t}\n\treturn total / float64(len(nums))\n}", "func average(arg1, arg2, arg3 float64) float64 {\n\ttotal := arg1 + arg2 + arg3\n\treturn total/3\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func (m *Model) FieldAvg(column string, as ...string) *Model {\n\tasStr := \"\"\n\tif len(as) > 0 && as[0] != \"\" {\n\t\tasStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))\n\t}\n\treturn m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.QuoteWord(column), asStr))\n}", "func TestAverageSingleValue(t *testing.T) {\n\tvar v float64\n\tv = Average([]float64{1, 2})\n\tif v != 1.5 {\n\t\tt.Error(\"expected 1.5, got \", v)\n\t}\n}", "func Average(arr []float64) float64 {\n\tvar total float64\n\tfor _, value := range arr {\n\t\ttotal += value\n\t}\n\treturn total / float64(len(arr))\n}", "func avg(dps Series, args ...float64) (a float64) {\n\tfor _, v := range dps {\n\t\ta += float64(v)\n\t}\n\ta /= float64(len(dps))\n\treturn\n}", "func calculateAverage(sSum float64, sLen float64) (float64) {\n var avg float64 = sSum / sLen\n return avg\n}", "func Average(s *discordgo.Session, m *discordgo.MessageCreate) {\n\tnums := strings.Split(m.Content, \" \")[1:]\n\tvar actualNums []float64\n\n\t// Get numbers\n\tfor _, num := range nums {\n\t\tactualNum, err := strconv.ParseFloat(num, 64)\n\t\tif err == nil {\n\t\t\tactualNums = append(actualNums, actualNum)\n\t\t}\n\t}\n\n\t// Check for more than 1 number\n\tif len(actualNums) <= 1 {\n\t\ts.ChannelMessageSend(m.ChannelID, \"Please provide 2 or more numbers to get the average for!\")\n\t}\n\n\tharmonicMean := mathtools.HarmonicMean(actualNums)\n\tgeometricMean := mathtools.GeometricMean(actualNums)\n\tarithmeticMean := mathtools.ArithmeticMean(actualNums)\n\n\ttext := \"Averages for: \"\n\tfor _, num := range actualNums {\n\t\ttext += strconv.FormatFloat(num, 'f', 2, 64) + \", \"\n\t}\n\ttext = strings.TrimSuffix(text, \", \") + \"\\n\\n\"\n\n\ttext += \"Arithmetic Mean: **\" + strconv.FormatFloat(arithmeticMean, 'f', 2, 64) + \"**\\n\" +\n\t\t\"Geometric Mean: **\" + strconv.FormatFloat(geometricMean, 'f', 2, 64) + \"**\\n\" +\n\t\t\"Harmonic Mean: **\" + strconv.FormatFloat(harmonicMean, 'f', 2, 64) + \"**\\n\"\n\n\ts.ChannelMessageSend(m.ChannelID, text)\n}", "func TestMyInts_Average(t *testing.T) {\n\tassert.Equal(t, 0.0, myInts(nil).Average())\n\tassert.Equal(t, 4.333333333333333, myInts{1, 5, 7}.Average())\n}", "func Average(arg1 float64, arg2 float64) float64 { // take arguments from the main go program and returns average value in float64\n fmt.Println(\"Calculating Average:\")\n avg := (arg1 + arg2)/2\n return avg\n}", "func (t *TTFB) Average(group string) float64 {\n\tvar total float64\n\tvar values []float64\n\n\tfor _, data := range t.Results {\n\t\tif group == connectionTime {\n\t\t\tvalues = append(values, data.Output.ConnectTime)\n\t\t\tcontinue\n\t\t}\n\n\t\tif group == timeToFirstByte {\n\t\t\tvalues = append(values, data.Output.FirstByteTime)\n\t\t\tcontinue\n\t\t}\n\n\t\tif group == totalTime {\n\t\t\tvalues = append(values, data.Output.TotalTime)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// There is no enough data to average.\n\tif len(values) < 3 {\n\t\treturn 0.0\n\t}\n\n\tsort.Float64s(values)\n\n\t// Drop first and last values for accuracy.\n\tfor i := 1; i < len(values)-1; i++ {\n\t\ttotal += values[i]\n\t}\n\n\treturn total / float64(len(values)-2)\n}", "func computeAverage(array []float64) float64 {\n\tresult := 0.0\n\tfor _, item := range array {\n\t\tresult += item\n\t}\n\treturn result / float64(len(array))\n}", "func TestFindAverage(t *testing.T) {\n\tinput := []int{1, 3, 2, 6, -1, 4, 1, 8, 2}\n\tk := 5\n\texpectedOutput := []float64{2.2, 2.8, 2.4, 3.6, 2.8}\n\n\toutput := FindAverage(input, k)\n\tfmt.Println(\"Output : \", output)\n\n\tif !reflect.DeepEqual(output, expectedOutput) {\n\t\tt.Error(\"Output and expected output do not match : \", output, expectedOutput)\n\t}\n}", "func (c *Clac) Avg() error {\n\treturn c.applyFloat(variadic, func(vals []value.Value) (value.Value, error) {\n\t\tsum, _ := reduceFloat(zero, vals, func(a, b value.Value) (value.Value, error) {\n\t\t\treturn binary(a, \"+\", b)\n\t\t})\n\t\treturn binary(sum, \"/\", value.Int(len(vals)))\n\t})\n}", "func main() {\n xs := []float64{1,2,3,4}\n avg := m.Average(xs)\n fmt.Println(avg)\n}", "func Average(series []Series) (Series, error) {\n\treturn applyOperator(series, OperatorAverage)\n}", "func FloatOrPanic(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func Avg(n int64) Option {\n\treturn func(opts *Options) {\n\t\topts.AvgDiv = n\n\t}\n}", "func Avg(first Decimal, rest ...Decimal) Decimal {\n\tcount := New(int64(len(rest)+1), 0)\n\tsum := Sum(first, rest...)\n\treturn sum.Div(count)\n}", "func Mean(values []float64) float64 {\n\tvar sum float64 = 0.0\n\tcount := 0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t\tcount++\n\t\t}\n\t}\n\treturn sum / float64(count)\n}", "func CalculateMean(appNum int, zoneNum int) float64 {\n\tx := float64(appNum / zoneNum)\n\treturn x\n}", "func Avg(first Decimal, rest ...Decimal) Decimal {\n\tcount := NewDec(int64(len(rest)+1), 0)\n\tsum := Sum(first, rest...)\n\treturn sum.Div(count)\n}", "func loadavg(contents string) (loadaverage string, err error) {\n\tloadavg := strings.Fields(contents)\n\tif len(loadavg) < 3 {\n\t\treturn \"\", fmt.Errorf(\"error:invalid contents:the contents of proc/loadavg we are trying to process contain less than the required 3 loadavgs\")\n\t}\n\treturn loadavg[0] + \",\" + loadavg[1] + \",\" + loadavg[2], nil\n}", "func average(data []int64) string {\n var total int64\n for _, n := range data {\n total += n\n }\n duration, _ := time.ParseDuration(fmt.Sprintf(\"%dns\", (total / int64(len(data)))))\n return fmt.Sprintf(\"%.3f\", duration.Seconds())\n}", "func mean(numbers ...float64) float64{\n\n\tvar total float64\n\n\tfor _, v := range numbers{\n\t\ttotal += v\n\t}\n\n\ttotal /= float64(len(numbers))\n\n\treturn total\n\n}", "func Average(audiences []db.Audience) int64 {\n\tvar rv int64\n\tfor _, a := range audiences {\n\t\trv += int64(a.Audience)\n\t}\n\n\tif len(audiences) == 0 {\n\t\treturn 0\n\t}\n\n\treturn rv / int64(len(audiences))\n}", "func (m *MovingAverage) Average(dur time.Duration) float64 {\n\taverages := m.Averages(dur)\n\tif len(averages) == 0 {\n\t\treturn 0\n\t}\n\tsum := 0.0\n\tfor _, avg := range averages {\n\t\tsum += avg\n\t}\n\treturn sum / float64(len(averages))\n}", "func Mean(xs ...float64) float64 {\n\treturn Sum(xs...) / float64(len(xs))\n}", "func Mean(v []float64) float64 {\n\ttotal := Sum(v)\n\treturn total / float64(len(v))\n}", "func Mean(field string) AggregateFunc {\n\treturn func(start, end string) (string, *dsl.Traversal) {\n\t\tif end == \"\" {\n\t\t\tend = DefaultMeanLabel\n\t\t}\n\t\treturn end, __.As(start).Unfold().Values(field).Mean().As(end)\n\t}\n}", "func (records DataRecs) Mean() (float64) {\n\n\ttotal := 0.0\n\tfor _, record := range records {\n\t\t//fmt.Printf(\"converting to float: %s\", record.RecordedValue)\n\t\trecordedValue := fromStringToFloat(record.RecordedValue)\n\t\ttotal += recordedValue\n\t}\n\n\tif total == 0.0 {\n\t\treturn total\n\t}\n\n\tmeanValue := total / float64(len(records))\n\tmeanValue = fromStringToFloat(fmt.Sprintf(\"%.2f\", meanValue))\n\treturn meanValue\n}", "func (data *Data) Float(s ...string) float64 {\n\treturn data.Interface(s...).(float64)\n}", "func average(x ...float64) (float64, float64) {\n\t// variables for average and total\n\tvar sum, avg float64\n\t// looping for total value\n\tfor _, i := range x {\n\t\tsum += i\n\t}\n\n\t// return total values and average with len function\n\tavg = sum / float64(len(x))\n\treturn sum, avg\n}", "func Average(tas ...*TA) *TA {\n\tln := tas[0].Len()\n\tfor i := 1; i < len(tas); i++ {\n\t\tif n := tas[i].Len(); n > ln {\n\t\t\tln = n\n\t\t}\n\t}\n\n\tout := NewSize(ln, true)\n\tfor i := 0; i < ln; i++ {\n\t\tvar v Decimal\n\t\tfor _, ta := range tas {\n\t\t\tif i < ta.Len() {\n\t\t\t\tv = v.Add(ta.Get(i))\n\t\t\t}\n\t\t}\n\t\tout.Append(v / Decimal(ln))\n\t}\n\n\treturn out\n}", "func averFunc(argv [] string) {\r\n if(len(argv)!=2) {\r\n fmt.Println(\"Not a correct input\")\r\n customPause()\r\n return\r\n }\r\n some := selVar(argv[1])\r\n var aver[samp_len] float64\r\n\r\n //Opening file and scanner to read values from the file\r\n fileHandle, err := os.Open(fileName)\r\n check(err)\r\n defer fileHandle.Close()\r\n\r\n fileScanner := bufio.NewScanner(fileHandle)\r\n var i int = 0\r\n for j:=1; fileScanner.Scan(); j++ {\r\n tmp, err := strconv.ParseFloat(fileScanner.Text(), 64)\r\n check(err)\r\n aver[i%samp_len] += tmp\r\n i++\r\n }\r\n for j := 0; j < samp_len; j++ {\r\n if some[j] {\r\n fmt.Printf(\"Average of Variable %d: %f\", (j+1), (aver[j]/(float64(i/samp_len))))\r\n fmt.Println()\r\n }\r\n }\r\n customPause()\r\n}", "func ArithmeticAverage(data []float64) float64 {\r\n\treturn Accumulate(data, 0, func(a float64, b float64) float64 {\r\n\t\treturn a + b\r\n\t}) / float64(len(data))\r\n}", "func (ff Features) AverageScore() float64 {\n\tif len(ff) == 0 {\n\t\treturn 0\n\t}\n\n\ttotalScore := 0.0\n\tfor _, f := range ff {\n\t\ttotalScore += f.Score\n\t}\n\n\tif totalScore == 0 {\n\t\treturn 0\n\t}\n\n\treturn totalScore / float64(len(ff))\n}", "func getExamData(number string) (float64, []Record){\n log.Print(\"getExamData(): number :> \", number)\n\n // trim special chars and convert to float64\n numberFloat, _ := strconv.ParseFloat(strings.TrimSpace(number), 64)\n\n scores := make([]Record, 0) // create a new slice\n for _, d := range data {\n if d.Exam == numberFloat {\n scores = append(scores, d)\n }\n }\n\n var scoresLen int = len(scores) // calculate average\n var scoresSum float64 = 0\n for _, s := range scores {\n scoresSum = scoresSum + s.Score\n }\n\n var scoresAvg float64 = calculateAverage(scoresSum, float64(scoresLen))\n\n return scoresAvg, scores // return slice and average\n}", "func (s FloatList) Mean() float64 {\n\tif s.size == 0 {\n\t\treturn 0\n\t}\n\treturn s.total / float64(s.size)\n}", "func LooksLikeAFloat(inputStr string) (matched bool, value float64) {\n\tmatched = floatRe.MatchString(inputStr)\n\tif matched {\n\t\tvalue, _ = strconv.ParseFloat(inputStr, 64)\n\t\treturn true, value\n\t}\n\treturn\n}", "func PostAvg(w http.ResponseWriter, r *http.Request) {\n\n\t// Very basic parameter checking.\n\tif r.Body == nil {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"missing parameter\")))\n\t\treturn\n\t}\n\n\tvar dataBody mytypes.DataBody\n\tjsonErr := json.NewDecoder(r.Body).Decode(&dataBody)\n\tif jsonErr != nil {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"no data given\")))\n\t\treturn\n\t}\n\n\t// FIXME: Error handling.\n\tdataRaw := dataBody.Data[:]\n\tdata := convert.StringtoFloat64(dataRaw)\n\n\tl := len(data)\n\tif l > 0 {\n\t\tavg := stat.Mean(data, nil)\n\t\tw.Write([]byte(fmt.Sprintf(\"%f\", avg)))\n\t} else {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"invalid data\")))\n\t\treturn\n\t}\n}", "func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64 {\n\tif s == \"\" {\n\t\treturn 0.0\n\t}\n\n\tconst maxLength = 20\n\n\tif len([]rune(s)) > maxLength {\n\t\ts = s[0:maxLength]\n\t}\n\n\ts = strings.Replace(s, string(thousandsSeparator), \"\", -1)\n\n\ts = strings.Replace(s, string(decimalSeparator), \".\", -1)\n\n\tif f, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn f\n\t}\n\n\treturn 0.0\n}", "func ListAverageValue(values []float64) float64 {\n\ttotal := float64(0)\n\tfor _, value := range values {\n\t\ttotal += value\n\t}\n\n\t//result := total / float64(len(values))\n\n\treturn total\n\t//return result\n}", "func (c *AverageDuration) Average() int64 {\n\tcount := c.Count()\n\tif count > 0 {\n\t\treturn c.Sum() / count\n\t}\n\treturn 0\n}", "func mean(a []float64) (m float64) {\n\tfor _, v := range a {\n\t\tm += v / float64(len(a))\n\t}\n\treturn\n}", "func (r *ImageRef) Average() (float64, error) {\n\tout, err := vipsAverage(r.image)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn out, nil\n}", "func SimpleMean(x []float64) (float64, error) {\n\tif len(x) == 0 {\n\t\treturn 0.0, errors.New(\"cannot calculate the average of an empty slice\")\n\t}\n\ts := 0.0\n\tfor _, v := range x {\n\t\ts += v\n\t}\n\treturn s / float64(len(x)), nil\n}", "func parseFloat(emp []string, key, fileType string) (float64, error) {\n\tvalueStr := emp[headersMap[fileType][key]]\n\tif valueStr == \"\" {\n\t\treturn 0.0, nil\n\t} else {\n\t\tvalueStr = strings.Trim(valueStr, \" \")\n\t\tvalueStr = strings.Replace(valueStr, \",\", \".\", 1)\n\t\tif n := strings.Count(valueStr, \".\"); n > 1 {\n\t\t\tvalueStr = strings.Replace(valueStr, \".\", \"\", n-1)\n\t\t}\n\t}\n\treturn strconv.ParseFloat(valueStr, 64)\n}", "func (ws Weights) Avg() float64 {\n\tavg := 0.0\n\tfor _, w := range ws {\n\t\tavg += float64(len(w.Bits)) * w.Value\n\t}\n\treturn avg\n}", "func TestAverageSet(t *testing.T) {\n\tfor _, pair := range testsAVG {\n\t\tv := Average(pair.values)\n\t\tif v != pair.result {\n\t\t\tt.Error(\n\t\t\t\t\"For\", pair.values,\n\t\t\t\t\"expected\", pair.result,\n\t\t\t\t\"got\", v,\n\t\t\t)\n\t\t}\n\t}\n}", "func TestParseLoadAverage15MinBasic(t *testing.T) {\n\tcontent, err := ioutil.ReadFile(\"../test_resources/loadavg\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ts := string(content)\n\n\tloadavg, _ := parseLoadAverage15Min(&s)\n\n\tif loadavg != 0.05 {\n\t\tt.Errorf(\"json value returned unexpected: got %f want %f\",\n\t\t\tloadavg, 0.05)\n\t}\n}", "func FindAverage(data []int) float64 {\n\tsize := len(data)\n\tsum := 0\n\tfor _, v := range data {\n\t\tsum += v\n\t}\n\treturn float64(sum) / float64(size)\n}", "func getAverage(points []Point) Point {\n\tnewPoint := make(Point, len(points[0]))\n\tfor _, point := range points {\n\t\tfor j, val := range point {\n\t\t\tnewPoint[j] += val\n\t\t}\n\t}\n\tfor i := range newPoint {\n\t\tnewPoint[i] = newPoint[i]/float64(len(points))\n\t}\n\treturn newPoint\n}", "func (indis Individuals) FitAvg() float64 {\n\treturn meanFloat64s(indis.getFitnesses())\n}", "func (s *SpeedInfo) Average() float64 {\n\tsum := 0.0\n\ti := 0\n\ts.reports.Do(func(rep interface{}) {\n\t\tif rep == nil {\n\t\t\treturn\n\t\t}\n\n\t\tsum += rep.(float64)\n\t\ti++\n\t})\n\n\tif i == 0 {\n\t\treturn 0\n\t}\n\n\treturn sum / float64(i)\n}", "func (o ObjectMetricSourcePatchPtrOutput) AverageValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AverageValue\n\t}).(pulumi.StringPtrOutput)\n}", "func (m mathUtil) Mean(values ...float64) float64 {\n\treturn m.Sum(values...) / float64(len(values))\n}", "func (o ObjectMetricSourcePatchOutput) AverageValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *string { return v.AverageValue }).(pulumi.StringPtrOutput)\n}", "func funcAvgOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tif len(vals[0].(Matrix)[0].Floats) > 0 && len(vals[0].(Matrix)[0].Histograms) > 0 {\n\t\t// TODO(zenador): Add warning for mixed floats and histograms.\n\t\treturn enh.Out\n\t}\n\tif len(vals[0].(Matrix)[0].Floats) == 0 {\n\t\t// The passed values only contain histograms.\n\t\treturn aggrHistOverTime(vals, enh, func(s Series) *histogram.FloatHistogram {\n\t\t\tcount := 1\n\t\t\tmean := s.Histograms[0].H.Copy()\n\t\t\tfor _, h := range s.Histograms[1:] {\n\t\t\t\tcount++\n\t\t\t\tleft := h.H.Copy().Div(float64(count))\n\t\t\t\tright := mean.Copy().Div(float64(count))\n\t\t\t\t// The histogram being added/subtracted must have\n\t\t\t\t// an equal or larger schema.\n\t\t\t\tif h.H.Schema >= mean.Schema {\n\t\t\t\t\ttoAdd := right.Mul(-1).Add(left)\n\t\t\t\t\tmean.Add(toAdd)\n\t\t\t\t} else {\n\t\t\t\t\ttoAdd := left.Sub(right)\n\t\t\t\t\tmean = toAdd.Add(mean)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mean\n\t\t})\n\t}\n\treturn aggrOverTime(vals, enh, func(s Series) float64 {\n\t\tvar mean, count, c float64\n\t\tfor _, f := range s.Floats {\n\t\t\tcount++\n\t\t\tif math.IsInf(mean, 0) {\n\t\t\t\tif math.IsInf(f.F, 0) && (mean > 0) == (f.F > 0) {\n\t\t\t\t\t// The `mean` and `f.F` values are `Inf` of the same sign. They\n\t\t\t\t\t// can't be subtracted, but the value of `mean` is correct\n\t\t\t\t\t// already.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !math.IsInf(f.F, 0) && !math.IsNaN(f.F) {\n\t\t\t\t\t// At this stage, the mean is an infinite. If the added\n\t\t\t\t\t// value is neither an Inf or a Nan, we can keep that mean\n\t\t\t\t\t// value.\n\t\t\t\t\t// This is required because our calculation below removes\n\t\t\t\t\t// the mean value, which would look like Inf += x - Inf and\n\t\t\t\t\t// end up as a NaN.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tmean, c = kahanSumInc(f.F/count-mean/count, mean, c)\n\t\t}\n\n\t\tif math.IsInf(mean, 0) {\n\t\t\treturn mean\n\t\t}\n\t\treturn mean + c\n\t})\n}", "func (baseball_player *BaseballPlayer) average() float32 {\n\treturn float32(baseball_player.hits) / float32(baseball_player.atBats)\n}", "func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {}", "func HandleAvg(w http.ResponseWriter, req *http.Request) {\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar numbers Numbers\n\n\terr := decoder.Decode(&numbers)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prevent division by zero\n\tvar average float64 = 0\n\n\tif len(numbers.Numbers) != 0 {\n\t\taverage = Average(numbers.Numbers)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tjsonRes, _ := json.Marshal(&Response{Result: average})\n\n\tw.Write(jsonRes)\n}", "func TestSumAndAvg(t *testing.T) {\n\n\tdataset := dparval.ValueCollection{\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"marty\",\n\t\t\t\"score\": 20.0,\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"gerald\",\n\t\t\t\"score\": nil,\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"steve\",\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"siri\",\n\t\t\t\"score\": \"thirty\",\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"deep\",\n\t\t\t\"score\": 10.0,\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"ketaki\",\n\t\t\t\"score\": \"false\",\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"pratap\",\n\t\t\t\"score\": []interface{}{5.5},\n\t\t}),\n\t\tdparval.NewValue(map[string]interface{}{\n\t\t\t\"name\": \"karen\",\n\t\t\t\"score\": map[string]interface{}{\"score\": 5.5},\n\t\t}),\n\t}\n\n\ttests := AggregateTestSet{\n\t\t// test expression (eliminiates null and missing)\n\t\t{\n\t\t\tNewFunctionCall(\"SUM\", FunctionArgExpressionList{NewFunctionArgExpression(NewProperty(\"score\"))}),\n\t\t\tdparval.NewValue(30.0),\n\t\t},\n\t\t{\n\t\t\tNewFunctionCall(\"AVG\", FunctionArgExpressionList{NewFunctionArgExpression(NewProperty(\"score\"))}),\n\t\t\tdparval.NewValue(15.0),\n\t\t},\n\t}\n\n\ttests.Run(t, dataset)\n\n}", "func (c *TimeAvgAggregator) Mean() float64 {\n\tif !c.initialized {\n\t\treturn math.NaN()\n\t}\n\tif c.startTime == c.endTime {\n\t\treturn float64(c.endValue)\n\t}\n\treturn float64(c.integral) / float64(c.endTime-c.startTime)\n}", "func (r *FloatMeanReducer) AggregateFloat(p *FloatPoint) {\n\tif p.Aggregated >= 2 {\n\t\tr.sum += p.Value * float64(p.Aggregated)\n\t\tr.count += p.Aggregated\n\t} else {\n\t\tr.sum += p.Value\n\t\tr.count++\n\t}\n}", "func avgAggregatedMeasurement(agg []AggregatedMeasurement) AggregatedMeasurement {\n avg := AggregatedMeasurement{}\n t := int64(0)\n for _,v := range agg {\n avg.Name = v.Name\n avg.Jaccard += v.Jaccard\n t += int64(v.ElapsedTime)\n }\n avg.Jaccard = avg.Jaccard / float64(len(agg))\n avg.ElapsedTime = time.Duration(t / int64(len(agg)))\n return avg\n}", "func GetLoadAverage() (float64, error) {\n\td, err := ioutil.ReadFile(\"/proc/loadavg\")\n\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\tparts := strings.Split(string(d), \" \")\n\n\tload, err := strconv.ParseFloat(parts[0], 64)\n\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\treturn load, nil\n}", "func Mean(list []float64) float64 {\n\tsum := 0.0\n\tfor _, v := range list {\n\t\tsum += v\n\t}\n\treturn sum / float64(len(list))\n}", "func (sma *SimpleMovingAverage) GetAverage() float64 {\n\treturn sma.average\n}", "func (m *movingAverage) average() (float64, error) {\n\n\tsum := .0\n\n\tif !m.samplingComplete {\n\t\treturn sum, fmt.Errorf(\"cannot compute average without a full sampling\")\n\t}\n\n\tfor _, value := range m.ring {\n\t\tsum += value\n\t}\n\n\treturn sum / float64(m.sampleSize), nil\n}", "func Avg(field string) *AggrItem {\n\treturn NewAggrItem(field, AggrAvg, field)\n}", "func main() {\n\tif (len(os.Args ) == 1) {\n\t\tfmt.Println(\"Please give one or more numbers.\")\n\t\tos.Exit(1)\n\t}\n\t\n\targs := os.Args \n\tsum := 0.0\n\tvar err error = errors.New(\"All inputs must be numbers.\")\n\n\tfor i := 1; i < len(args); i ++ {\n\t\tn, er := strconv.ParseFloat(args[i], 64)\n\t\tif er != nil {\n\t\t\tfmt.Printf(\"%s (custom: %s)\\n\", err.Error(), er)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tsum += n\n\t}\n\tvar k float64 = (float64) ((len(args) - 1))\n\tvar avg float64 = sum / k\n\tfmt.Printf(\"Average of all numbers is: %f \\n\", avg)\n}", "func (o ObjectMetricSourceOutput) AverageValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) *string { return v.AverageValue }).(pulumi.StringPtrOutput)\n}", "func ParseFloat(operand string) (f float64, err error) { return strconv.ParseFloat(operand, 64) }", "func (o ObjectMetricSourcePtrOutput) AverageValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AverageValue\n\t}).(pulumi.StringPtrOutput)\n}", "func WeightedMean(values, weights []float64) float64 {\n\tif len(values) != len(weights) {\n\t\treturn math.NaN()\n\t}\n\tvar sum float64 = 0.0\n\tvar count float64 = 0.0\n\tfor i := range values {\n\t\tif !math.IsNaN(values[i]) && !math.IsNaN(weights[i]) {\n\t\t\tsum += values[i] * weights[i]\n\t\t\tcount += weights[i]\n\t\t}\n\t}\n\treturn sum / count\n}", "func Mean(field string) Aggregate {\n\treturn Aggregate{\n\t\tSQL: func(s *sql.Selector) string {\n\t\t\treturn sql.Avg(s.C(field))\n\t\t},\n\t}\n}", "func (fn *formulaFuncs) TRIMMEAN(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"TRIMMEAN requires 2 arguments\")\n\t}\n\tpercent := argsList.Back().Value.(formulaArg).ToNumber()\n\tif percent.Type != ArgNumber {\n\t\treturn percent\n\t}\n\tif percent.Number < 0 || percent.Number >= 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)\n\t}\n\tvar arr []float64\n\tarrArg := argsList.Front().Value.(formulaArg).ToList()\n\tfor _, cell := range arrArg {\n\t\tif cell.Type != ArgNumber {\n\t\t\tcontinue\n\t\t}\n\t\tarr = append(arr, cell.Number)\n\t}\n\tdiscard := math.Floor(float64(len(arr)) * percent.Number / 2)\n\tsort.Float64s(arr)\n\tfor i := 0; i < int(discard); i++ {\n\t\tif len(arr) > 0 {\n\t\t\tarr = arr[1:]\n\t\t}\n\t\tif len(arr) > 0 {\n\t\t\tarr = arr[:len(arr)-1]\n\t\t}\n\t}\n\n\targs := list.New().Init()\n\tfor _, ele := range arr {\n\t\targs.PushBack(newNumberFormulaArg(ele))\n\t}\n\treturn fn.AVERAGE(args)\n}", "func parseFloats(in []string) ([]float64, error) {\n\tout := make([]float64, len(in))\n\tfor i := range in {\n\t\tval, err := strconv.ParseFloat(in[i], 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout[i] = val\n\t}\n\treturn out, nil\n}", "func (s *TrialComponentMetricSummary) SetAvg(v float64) *TrialComponentMetricSummary {\n\ts.Avg = &v\n\treturn s\n}", "func (a AverageAggregator) Aggregate(values []float64) float64 {\n\tif len(values) == 0 {\n\t\treturn 0.0\n\t}\n\n\tresult := 0.0\n\tfor _, v := range values {\n\t\tresult += v\n\t}\n\treturn result / float64(len(values))\n}", "func AVG(hist []float64) float64 {\n\tif len(hist) == 0 {\n\t\treturn 0\n\t}\n\n\tvar sum float64\n\tfor _, v := range hist {\n\t\tsum += v\n\t}\n\n\tsum /= float64(len(hist))\n\treturn sum\n}" ]
[ "0.5841493", "0.5782948", "0.5645542", "0.5613625", "0.5547251", "0.5530482", "0.55288845", "0.5513027", "0.54758036", "0.54725236", "0.5438258", "0.5416996", "0.53414214", "0.5296177", "0.52899706", "0.5284825", "0.52583843", "0.5235746", "0.5230519", "0.5230519", "0.51285166", "0.51248413", "0.50923216", "0.50715744", "0.5024638", "0.5017763", "0.49581426", "0.49456114", "0.4940268", "0.48872998", "0.48346516", "0.48340273", "0.480639", "0.48020163", "0.4798499", "0.4768459", "0.47621337", "0.474502", "0.47359174", "0.47203282", "0.47029042", "0.4689375", "0.46867448", "0.46865937", "0.4640283", "0.46235192", "0.4619761", "0.46166223", "0.46138588", "0.46092033", "0.46039665", "0.45813936", "0.4562581", "0.45619527", "0.45520335", "0.45482436", "0.45424047", "0.45289865", "0.4511515", "0.44858345", "0.44836402", "0.4481896", "0.4479737", "0.4469264", "0.44689792", "0.44521612", "0.44483426", "0.4435321", "0.44248018", "0.44111723", "0.44086638", "0.44023123", "0.4398588", "0.43826932", "0.4367372", "0.43407735", "0.4338802", "0.43374622", "0.43371683", "0.43369034", "0.43089744", "0.43025553", "0.42998916", "0.42991957", "0.42972884", "0.42902893", "0.42901793", "0.4278755", "0.42729253", "0.42632568", "0.4252989", "0.42507237", "0.4248427", "0.4237165", "0.42335722", "0.42273265", "0.42001146", "0.41955012", "0.4194131", "0.41938016" ]
0.7826473
0
valueAt returns the stringToFloat() of the value in the row at the given index position. If row is nil, returns nil.
func valueAt(row []string, position int) *float64 { if row == nil { return nil } return stringToFloat(row[position]) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getValueAt(index int, colName string, header *[]string, content *[][]string) (string, error) {\n\n\tif index == -1 {\n\t\treturn \"0.0\", nil\n\t}\n\tindexCol := findIndex(colName, header)\n\tif indexCol < 0 {\n\t\treturn \"\", fmt.Errorf(\"column %s not found\", colName)\n\t}\n\tval := (*content)[index][indexCol]\n\tvalF, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%.2f\", valF), nil\n}", "func valueRightOf(row []string, position int) *float64 {\n\tif position >= len(row)-1 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position+1])\n}", "func valueLeftOf(row []string, position int) *float64 {\n\tif position <= 0 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position-1])\n}", "func (access FloatAccess) Get(row int) float64 {\n return access.rawData[access.indices[row]]\n}", "func (obj VECTOR_TYPE) ValueAt(i int) float64 {\n if i < 0 || i >= obj.Dim() {\n panic(\"index out of bounds\")\n }\n if v, ok := obj.values[i]; ok {\n return v.GetValue()\n } else {\n return 0.0\n }\n}", "func GetRowValue(row Row, index int, columnName string) interface{} {\n\tif row.Values[index] == nil {\n\t\treturn 0\n\t}\n\n\tcolIndex, err := getIndexByColumnName(row, columnName)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif row.Values[index][colIndex] != nil {\n\t\tres := row.Values[index][colIndex]\n\t\treturn res\n\t}\n\treturn json.Number(0)\n}", "func (card *Card) ValueAt(cellName string) (int, error) {\n\tcell, err := card.cellAt(cellName)\n\tif err != nil {\n\t\treturn nan, err\n\t}\n\treturn cell.value, nil\n}", "func (obj *SparseRealVector) ValueAt(i int) float64 {\n if i < 0 || i >= obj.Dim() {\n panic(\"index out of bounds\")\n }\n if v, ok := obj.values[i]; ok {\n return v.GetValue()\n } else {\n return 0.0\n }\n}", "func (items Float64Slice) Value(index int) interface{} { return items[index] }", "func (ns *numbers) GetFloat(tblname string, rowname interface{}, fieldname string) float64 {\n\tval := ns.get(tblname, fmt.Sprint(rowname), fieldname)\n\tif val == \"\" {\n\t\treturn 0.0\n\t}\n\n\tf, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"cannot parse float from gamedata %v %v %v %v\\n\", tblname, rowname, fieldname, err))\n\t}\n\n\treturn f\n}", "func (r *Resultset) GetFloat(row, column int) (float64, error) {\n\td, err := r.GetValue(row, column)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tswitch v := d.(type) {\n\tcase float64:\n\t\treturn v, nil\n\tcase uint64:\n\t\treturn float64(v), nil\n\tcase int64:\n\t\treturn float64(v), nil\n\tcase string:\n\t\treturn strconv.ParseFloat(v, 64)\n\tcase []byte:\n\t\treturn strconv.ParseFloat(string(v), 64)\n\tcase nil:\n\t\treturn 0, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"data type is %T\", v)\n\t}\n}", "func (seq Sequence) ValueAt(period int, e expr.Expr) (val float64, found bool) {\n\tif e.IsConstant() {\n\t\tval, found, _ = e.Get(nil)\n\t\treturn\n\t}\n\tif len(seq) == 0 {\n\t\treturn 0, false\n\t}\n\tif period < 0 {\n\t\treturn 0, false\n\t}\n\treturn seq.ValueAtOffset(period*e.EncodedWidth(), e)\n}", "func valueForColumn(columns []string, idx int) (string, fields) {\n\tif idx >= len(columns) || columns[idx] == \"_\" {\n\t\treturn \"\", 0\n\t}\n\n\treturn columns[idx], fields(1) << fields(idx-1)\n}", "func (r *sparseRow) Value(feature int) float64 {\n\ti := search(r.ind, feature)\n\tif i >= 0 {\n\t\treturn r.val[i]\n\t}\n\treturn 0\n}", "func (tr Row) Float(nn int) (val float64) {\n\tval, err := tr.FloatErr(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (v valuer) Value(i int) float64 {\n\treturn v.data[i]\n}", "func (vm *VirtualMachine) getValueForElement(e quads.Element) interface{} {\n\tif strings.Contains(e.ID(), \"ptr_\") {\n\t\tmemblock := vm.getMemBlockForAddr(e.GetAddr())\n\t\tptrAddr, ok := memblock.Get(e.GetAddr()).(float64)\n\t\tif !ok {\n\t\t\tlog.Fatalf(\"Error: (getValueForElement) couldn't cast index to float64\")\n\t\t}\n\n\t\tauxElement := quads.NewElement(int(ptrAddr), e.ID(), e.Type(), \"\")\n\t\tmemblock = vm.getMemBlockForElement(auxElement)\n\t\trealValue := memblock.Get(int(ptrAddr))\n\t\treturn realValue\n\t}\n\tmemblock := vm.getMemBlockForElement(e)\n\treturn memblock.Get(e.GetAddr())\n}", "func (d Datapoints) ValueAt(n int) float64 { return d[n].Value }", "func (row Row) GetValue(column Column) interface{} {\n\tindex, ok := row.columnOrder[column]\n\tif !ok {\n\t\tlog.Printf(\"WARNING: %v is not found in %v\", column, row.columnOrder)\n\t}\n\treturn row.values[index]\n}", "func (seq Sequence) ValueAtOffset(offset int, e expr.Expr) (val float64, found bool) {\n\tif e.IsConstant() {\n\t\tval, found, _ = e.Get(nil)\n\t\treturn\n\t}\n\tif len(seq) == 0 {\n\t\treturn 0, false\n\t}\n\toffset = offset + Width64bits\n\tif offset >= len(seq) {\n\t\treturn 0, false\n\t}\n\tval, wasSet, _ := e.Get(seq[offset:])\n\treturn val, wasSet\n}", "func (m *Mat) Value(index int) (val float32) {\n\tcursor := 0\n\tfor i := 0; i < len(m.W); i++ {\n\t\tfor f := 0; f < 4; f++ {\n\t\t\tif cursor >= index {\n\t\t\t\tval = m.W[i][f]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcursor++\n\t\t}\n\t}\n\treturn val\n}", "func (a Float32Array) Value() (driver.Value, error) {\n\tif a == nil {\n\t\treturn nil, nil\n\t}\n\n\tif n := len(a); n > 0 {\n\t\t// There will be at least two curly brackets, N bytes of values,\n\t\t// and N-1 bytes of delimiters.\n\t\tb := make([]byte, 1, 1+2*n)\n\t\tb[0] = '{'\n\n\t\tb = strconv.AppendFloat(b, float64(a[0]), 'f', -1, 32)\n\t\tfor i := 1; i < n; i++ {\n\t\t\tb = append(b, ',')\n\t\t\tb = strconv.AppendFloat(b, float64(a[i]), 'f', -1, 32)\n\t\t}\n\n\t\treturn string(append(b, '}')), nil\n\t}\n\n\treturn \"{}\", nil\n}", "func (tr Row) FloatErr(nn int) (val float64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase float64, float32:\n\t\tval = reflect.ValueOf(data).Float()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i >= 2<<53 || i <= -(2<<53) {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(i)\n\t\t}\n\tcase uint64, uint32, uint16, uint8:\n\t\tu := reflect.ValueOf(data).Uint()\n\t\tif u >= 2<<53 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(u)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseFloat(string(data), 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}", "func (r *Resultset) GetValue(row, column int) (interface{}, error) {\n\tif row >= len(r.Values) || row < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid row index %d\", row)\n\t}\n\n\tif column >= len(r.Fields) || column < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid column index %d\", column)\n\t}\n\n\treturn r.Values[row][column], nil\n}", "func (t *Table) Getf(row, col int) float64 {\n\tif row >= len(t.Row) || col >= len(t.ColDefs) {\n\t\treturn float64(0)\n\t}\n\treturn t.Row[row].Col[col].Fval\n}", "func (jz *Jzon) ValueAt(i int) (v *Jzon, err error) {\n\tif jz.Type != JzTypeArr {\n\t\treturn v, expectTypeOf(JzTypeArr, jz.Type)\n\t}\n\n\tif i < 0 || i >= len(jz.data.([]*Jzon)) {\n\t\terr = errors.New(\"index is out of bound\")\n\t\treturn\n\t}\n\n\treturn jz.data.([]*Jzon)[i], nil\n}", "func (m *matrix) GetValue(i, j int) (f float64, err error) {\n\tif ok, err := m.checkBounds(i, j); !ok {\n\t\treturn f, err\n\t}\n\treturn m.matrix[i][j], err\n}", "func (seq Sequence) ValueAtTime(t time.Time, e expr.Expr, resolution time.Duration) (val float64, found bool) {\n\tif e.IsConstant() {\n\t\tval, found, _ = e.Get(nil)\n\t\treturn\n\t}\n\tif len(seq) == 0 {\n\t\treturn 0, false\n\t}\n\tuntil := seq.Until()\n\tt = RoundTimeUntilUp(t, resolution, until)\n\tif t.After(until) {\n\t\treturn 0, false\n\t}\n\tperiod := int(until.Sub(t) / resolution)\n\treturn seq.ValueAt(period, e)\n}", "func (n NullFloat64) Value() (driver.Value, error) {\n\tif n == 0 {\n\t\treturn nil, nil\n\t}\n\treturn float64(n), nil\n}", "func (db *calcDatabase) value() formulaArg {\n\tif db.col == -1 {\n\t\treturn db.database[db.row][len(db.database[db.row])-1]\n\t}\n\treturn db.database[db.row][db.col]\n}", "func (a Float64Array) Value() (driver.Value, error) {\n\tif a == nil {\n\t\treturn nil, nil\n\t}\n\n\tif n := len(a); n > 0 {\n\t\t// There will be at least two curly brackets, N bytes of values,\n\t\t// and N-1 bytes of delimiters.\n\t\tb := make([]byte, 1, 1+2*n)\n\t\tb[0] = '{'\n\n\t\tb = strconv.AppendFloat(b, a[0], 'f', -1, 64)\n\t\tfor i := 1; i < n; i++ {\n\t\t\tb = append(b, ',')\n\t\t\tb = strconv.AppendFloat(b, a[i], 'f', -1, 64)\n\t\t}\n\n\t\treturn string(append(b, '}')), nil\n\t}\n\n\treturn \"{}\", nil\n}", "func (self *T) Get(col, row int) float64 {\n\treturn self[row]\n}", "func (p MapStringToFloat64Ptrs) Value(key string) *float64 {\n\tptr, ok := p[key]\n\tswitch ok {\n\tcase false:\n\t\treturn nil\n\tdefault:\n\t\treturn ptr\n\t}\n}", "func (n NullFloat32) Value() (driver.Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn float64(n.Float32), nil\n}", "func (args *SPH_UDF_ARGS) stringval(idx int) string {\n\treturn GoStringN((*C.char)(args.valueptr(idx)), args.lenval(idx))\n}", "func (a ASTNode) Float() float64 {\n\tif a.t != tval {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Not a basic value\")})\n\t}\n\tv, err := strconv.ParseFloat(a.val.(string), 64)\n\tif err != nil {\n\t\tpanic(ConfErr{a.pos, err})\n\t}\n\treturn v\n}", "func (ns Float32) Value() (driver.Value, error) {\n\tif !ns.Valid {\n\t\treturn nil, nil\n\t}\n\treturn float64(ns.Float32), nil\n}", "func (value *Value) FloatValue() float64 {\n\tswitch value.valueType {\n\tcase Int:\n\t\treturn float64(value.value.(int64))\n\tcase Float:\n\t\treturn value.value.(float64)\n\t}\n\n\tpanic(fmt.Sprintf(\"requested float value but found %T type\", value.value))\n}", "func (t Tuple) At(idx int) float64 {\n\treturn t[idx]\n}", "func (c Cube) Value() (driver.Value, error) {\n\tif c == nil {\n\t\treturn nil, nil\n\t}\n\n\tif n := len(c); n > 0 {\n\t\t// There will be at least two parenthesis, N bytes of values,\n\t\t// and N-1 bytes of delimiters.\n\t\tb := make([]byte, 0, 2*n)\n\n\t\tb = strconv.AppendFloat(b, c[0], 'f', -1, 64)\n\t\tfor i := 1; i < n; i++ {\n\t\t\tb = append(b, ',')\n\t\t\tb = strconv.AppendFloat(b, c[i], 'f', -1, 64)\n\t\t}\n\n\t\treturn fmt.Sprintf(\"(%s)\", string(b)), nil\n\t}\n\n\treturn \"()\", nil\n}", "func (v *Value) Float() float64 {\n return Util.ToFloat(v.data)\n}", "func (c *cell) Value() int {\n\treturn c.value\n}", "func (c *Cell) Float() (float64, error) {\n\tf, err := strconv.ParseFloat(c.Value, 64)\n\tif err != nil {\n\t\treturn math.NaN(), err\n\t}\n\treturn f, nil\n}", "func (l List) ValueAt(index int) (value uint16, err error) {\n\n\tif l.Root == nil {\n\t\treturn value, fmt.Errorf(\"Oops! Looks like the list is empty\")\n\t}\n\n\tcurrent := l.Root\n\tcurrentIndex := 0\n\n\tfor current != nil {\n\t\tif currentIndex == index {\n\t\t\treturn current.Value, err\n\t\t} else if current.Next == nil && index > currentIndex {\n\t\t\treturn value, fmt.Errorf(\"Provided index %v is out of bounds\", index)\n\t\t}\n\t\tcurrentIndex++\n\t\tcurrent = current.Next\n\t}\n\treturn value, err\n}", "func (n Int64String) Value() (driver.Value, error) {\n\tif n == 0 {\n\t\treturn nil, nil\n\t}\n\treturn float64(n), nil\n}", "func (l LinkedList) ValueAt(index int) (interface{}, error) {\n\tif index >= l.Size {\n\t\treturn \"\", fmt.Errorf(\"Index %d out of range\", index)\n\t}\n\n\tvar val interface{}\n\tnode := l.Head\n\n\tfor i := 0; i < l.Size; i++ {\n\t\tif i == index {\n\t\t\tval = node.Data\n\t\t\tbreak\n\t\t}\n\n\t\tnode = node.Next\n\t}\n\n\treturn val, nil\n}", "func (p Point) Value() (driver.Value, error) {\n\treturn fmt.Sprintf(\"(%f,%f)\", p[0], p[1]), nil\n}", "func (uni *Uniform1fv) Get(pos int, v float32) float32 {\n\n\treturn uni.v[pos]\n}", "func (e *TabletVExec) ColumnStringVal(columns ValColumns, colName string) (string, error) {\n\tval, ok := columns[colName]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"Could not find value for column %s\", colName)\n\t}\n\treturn string(val.Val), nil\n}", "func (col *Column) GetValue(values []driver.Value) (driver.Value, error) {\n\tif col.Value != nil {\n\t\treturn *col.Value, nil\n\t}\n\tif col.Ordinal < 0 || col.Ordinal >= len(values) {\n\t\treturn nil, fmt.Errorf(\"internal error: ordinal=%d, value len=%d\", col.Ordinal, len(values))\n\t}\n\treturn values[col.Ordinal], nil\n}", "func (r *Result) Getx(index int) interface{} {\n\tif index < 0 || index >= len(r.val.columns) {\n\t\tpanic(ErrorColumnNotFound{At: \"Getx\", Index: index})\n\t}\n\tbv := r.val.buffer[index]\n\treturn bv.Value\n}", "func (v Value) Float() float64 {\n\tswitch v.Typ {\n\tdefault:\n\t\tf, _ := strconv.ParseFloat(v.String(), 64)\n\t\treturn f\n\tcase ':':\n\t\treturn float64(v.IntegerV)\n\t}\n}", "func (n NullFloat64) Value() (driver.Value, error) {\n\tif n.V == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn *n.V, nil\n}", "func (c *Cell) Float() (float64, error) {\n\tif !c.Is(Numeric) {\n\t\treturn 0, fmt.Errorf(\"cell data is not numeric\")\n\t}\n\n\tf, err := strconv.ParseFloat(c.data, 64)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to convert cell data to number\")\n\t}\n\treturn f, nil\n}", "func (m *Model) Value() float32 {\n\treturn m.value[0][0]\n}", "func (g Grid) GetValueAt(p *Point) float32 {\n\n\tif(p.X<g.Header.Lo1 || p.X>g.Header.Lo2){\n\t\treturn float32(-9999);\n\t}\n\n\tif(p.Y>g.Header.La1 || p.Y<g.Header.La2){\n\t\treturn float32(-9999);\n\t}\n\n\tidxX := int(((p.X - g.Header.Lo1) / g.Width()) * float64(g.Header.Nx-1))\n\tidxY := int(((g.Header.La1 - p.Y) / g.Height()) * float64(g.Header.Ny-1))\n\n\tul := g.GetValueAtIdx(idxX, idxY)\n\tur := g.GetValueAtIdx(idxX+1, idxY)\n\tll := g.GetValueAtIdx(idxX, idxY+1)\n\tlr := g.GetValueAtIdx(idxX+1, idxY+1)\n\n\tv:=BilinearInterpolation(&ll,&ul,&lr,&ur,p)\n\n\treturn float32(v)\n}", "func (r *Row) AppendFloatValue(val float64) {\n\tif len(r.fieldValues) < len(r.fields) {\n\t\tstr := strconv.FormatFloat(val, 'f', 14, 64)\n\t\tencodedVal := StringToLenencStr([]byte(str))\n\t\tr.fieldValues = append(r.fieldValues, str)\n\t\tr.fieldValuesCache = append(r.fieldValuesCache, encodedVal)\n\t}\n}", "func (m *productModel) Value(row, col int) interface{} {\n\n\tGoRec(row+1, \"product\")\n\n\tzname := Lower(Field(col, \"product\").Name)\n\tzv := FieldValue(zname, \"product\")\n\n\tswitch zname {\n\tcase \"pid\", \"pname\", \"categid\":\n\t\treturn zv\n\tcase \"price\":\n\t\t//fmt.Println(\"zv:\", zv, Val(zv))\n\t\treturn Val(zv)\n\t}\n\n\tpanic(\"unexpected col\")\n}", "func (v Value) Float() float64 {\n\tpanic(message)\n}", "func (mat *Matrix) GetValue(m, n int) float64 {\n\treturn mat.values[m][n]\n}", "func (r Row) GetFloat64(colIdx int) float64 {\n\treturn r.c.columns[colIdx].GetFloat64(r.idx)\n}", "func (cmd *FloatCommand) ValueAsLit() string {\n\treturn fmt.Sprintf(\"%f\", cmd.Value)\n}", "func (r *Resultset) GetValueByName(row int, name string) (interface{}, error) {\n\tcolumn, err := r.NameIndex(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.GetValue(row, column)\n}", "func (access FloatAccess) Set(row int, val float64) {\n access.rawData[access.indices[row]] = val\n}", "func (col *Column) readTxt(table *Table, icol int, irow int64, ptr interface{}) error {\n\tvar err error\n\n\trv := reflect.Indirect(reflect.ValueOf(ptr))\n\trt := reflect.TypeOf(rv.Interface())\n\n\tbeg := table.rowsz*int(irow) + col.offset\n\tend := beg + col.dtype.dsize\n\tbuf := table.data[beg:end]\n\tstr := strings.TrimSpace(string(buf))\n\n\tswitch rt.Kind() {\n\tcase reflect.Slice:\n\n\t\treturn fmt.Errorf(\"fitsio: ASCII-table can not read/write slices\")\n\n\tcase reflect.Array:\n\n\t\treturn fmt.Errorf(\"fitsio: ASCII-table can not read/write arrays\")\n\n\tcase reflect.Bool:\n\n\t\treturn fmt.Errorf(\"fitsio: ASCII-table can not read/write booleans\")\n\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tv, err := strconv.ParseUint(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fitsio: error parsing %q into a uint: %v\", str, err)\n\t\t}\n\t\trv.SetUint(v)\n\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tv, err := strconv.ParseInt(str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fitsio: error parsing %q into an int: %v\", str, err)\n\t\t}\n\t\trv.SetInt(v)\n\n\tcase reflect.Float32, reflect.Float64:\n\n\t\tv, err := strconv.ParseFloat(str, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fitsio: error parsing %q into a float: %v\", str, err)\n\t\t}\n\t\trv.SetFloat(v)\n\n\tcase reflect.Complex64, reflect.Complex128:\n\n\t\treturn fmt.Errorf(\"fitsio: ASCII-table can not read/write complexes\")\n\n\tcase reflect.String:\n\t\trv.SetString(str)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"fitsio: ASCII-table can not read/write %v\", rt.Kind())\n\t}\n\treturn err\n}", "func (r *Resultset) GetFloatByName(row int, name string) (float64, error) {\n\tcolumn, err := r.NameIndex(name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn r.GetFloat(row, column)\n}", "func (p Prometheus) findValue(body io.Reader) (float64, error) {\n\tscanLines := bufio.NewScanner(body)\n\tfor scanLines.Scan() { // for each line\n\t\t// now we're splitting by spaces\n\t\tscanWords := bufio.NewScanner(strings.NewReader(scanLines.Text()))\n\t\tscanWords.Split(bufio.ScanWords)\n\n\t\tif scanWords.Scan() { // line is not empty\n\t\t\tswitch scanWords.Text() {\n\t\t\tcase p.Key:\n\t\t\t\tif scanWords.Scan() {\n\t\t\t\t\tfvalue, err := strconv.ParseFloat(scanWords.Text(), 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"%s\", err)\n\t\t\t\t\t\treturn -1.0, err\n\t\t\t\t\t}\n\t\t\t\t\treturn fvalue, nil\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// if it doesn't start with the key, discard the line\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"Token %s not found\", p.Key)\n}", "func (v *V) At(i int) float64 {\n\tif i < 0 || i >= v.Dim() {\n\t\tpanic(ErrIndex)\n\t}\n\treturn v.Data[i]\n}", "func (v Value) Float(bitSize int) (float64, error) {\n\tif v.typ != Number {\n\t\treturn 0, v.newError(\"%s is not a number\", v.Raw())\n\t}\n\tf, err := strconv.ParseFloat(v.Raw(), bitSize)\n\tif err != nil {\n\t\treturn 0, v.newError(\"%v\", err)\n\t}\n\treturn f, nil\n}", "func (u *Util) StringToFloat(value interface{}) (number float32, err error) {\n number = -999\n if s,ok := value.(string); ok {\n price, err := strconv.ParseFloat(s, 32)\n if err == nil { number = float32(price) }\n } else {\n err = errors.New(\"variable is not string\")\n }\n return number, err\n}", "func (access StringAccess) Get(row int) string {\n return access.rawData[access.indices[row]].(string)\n}", "func (r Row) GetFloat32(colIdx int) float32 {\n\treturn r.c.columns[colIdx].GetFloat32(r.idx)\n}", "func (tr Row) ForceFloat(nn int) (val float64) {\n\tval, _ = tr.FloatErr(nn)\n\treturn\n}", "func Get_Value(value *vector_tile.Tile_Value) interface{} {\n\tif value.StringValue != nil {\n\t\treturn *value.StringValue\n\t} else if value.FloatValue != nil {\n\t\treturn *value.FloatValue\n\t} else if value.DoubleValue != nil {\n\t\treturn *value.DoubleValue\n\t} else if value.IntValue != nil {\n\t\treturn *value.IntValue\n\t} else if value.UintValue != nil {\n\t\treturn *value.UintValue\n\t} else if value.SintValue != nil {\n\t\treturn *value.SintValue\n\t} else if value.BoolValue != nil {\n\t\treturn *value.BoolValue\n\t} else {\n\t\treturn \"\"\n\t}\n\treturn \"\"\n}", "func (d *DB) readfloat_row(row []byte, pos uint32) float32 {\n\tvar retval float32\n\tdata := row[pos : pos+4]\n\tbits := binary.LittleEndian.Uint32(data)\n\tretval = math.Float32frombits(bits)\n\treturn retval\n}", "func (r *Person) Value(col string) (interface{}, error) {\n\tswitch col {\n\tcase \"id\":\n\t\treturn r.ID, nil\n\tcase \"name\":\n\t\treturn r.Name, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"kallax: invalid column in Person: %s\", col)\n\t}\n}", "func (self *T) Get(col, row int) float32 {\n\treturn self[col][row]\n}", "func (bc *BinaryCell) GetValue() float64 {\n\tif bc.free {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (cell *SpreadsheetCell) Value() int {\n\treturn cell.value\n}", "func (v *Value) StringAt(i int) (string, error) {\n\tif v.kind != kindArray {\n\t\treturn \"\", errors.New(\"JSON value is not an array\")\n\t}\n\tif i >= len(v.arrayContent) {\n\t\treturn \"\", errors.New(\"Index is out of bounds of array\")\n\t}\n\tvalue, err := v.arrayContent[i].String()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn value, nil\n}", "func sensorValueFromRow(rows *sql.Rows) (SensorValue, error) {\n\tvar sensorId,\n\t\tip,\n\t\ttyp string\n\tvar t time.Time\n\tvar value float64\n\n\terr := rows.Scan(\n\t\t&sensorId,\n\t\t&typ,\n\t\t&t,\n\t\t&value,\n\t\t&ip)\n\n\treturn SensorValue{\n\t\tSensorId: sensorId,\n\t\tType: typ,\n\t\tTime: t,\n\t\tValue: value,\n\t\tIp: ip,\n\t}, err\n}", "func (loc *LogOddsCell) GetValue() float64 {\n\treturn loc.logOddsVal\n}", "func (dr DatumRow) GetFloat32(colIdx int) (float32, bool) {\n\tdatum := dr[colIdx]\n\tif datum.IsNull() {\n\t\treturn 0, true\n\t}\n\treturn dr[colIdx].GetFloat32(), false\n}", "func (v Value) Float() float64 {\n\tswitch {\n\tcase v == 0:\n\t\treturn 0\n\tcase v == 64:\n\t\treturn 0.5\n\tcase v == 127:\n\t\treturn 1\n\tcase v < 64:\n\t\treturn float64(v) / 128\n\tdefault:\n\t\treturn float64(v-1) / 126\n\t}\n}", "func (r *Resultset) GetString(row, column int) (string, error) {\n\td, err := r.GetValue(row, column)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch v := d.(type) {\n\tcase string:\n\t\treturn v, nil\n\tcase []byte:\n\t\treturn hack.String(v), nil\n\tcase int64:\n\t\treturn strconv.FormatInt(v, 10), nil\n\tcase uint64:\n\t\treturn strconv.FormatUint(v, 10), nil\n\tcase float64:\n\t\treturn strconv.FormatFloat(v, 'f', -1, 64), nil\n\tcase nil:\n\t\treturn \"\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"data type is %T\", v)\n\t}\n}", "func typeValue(valueType string, value interface{}) interface{} {\n\tswitch valueType {\n\tdefault:\n\t\treturn 0\n\tcase \"int\":\n\t\treturn int(value.(float64))\n\tcase \"float64\":\n\t\treturn value.(float64)\n\t}\n}", "func (column *ColumnString) GetItem(i int) interface{} {\n\treturn interface{}(column.data[i])\n}", "func parseFloatValue(input string) (res float64) {\n\tvar err error\n\n\tres, err = strconv.ParseFloat(input, 64)\n\tif err != nil {\n\t\t// negative values must be dropped here\n\t\treturn\n\t}\n\n\tif res < 0 {\n\t\treturn 0\n\t}\n\treturn\n}", "func reflectValue(fieldType reflect.Type, fieldValue reflect.Value, v string) (reflect.Value, error) {\n\tswitch k := fieldValue.Kind(); k {\n\tcase reflect.Int16:\n\t\ti, err := strconv.ParseInt(v, 10, 16)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int16(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int16(i)), nil\n\tcase reflect.Int32:\n\t\ti, err := strconv.ParseInt(v, 10, 32)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int32(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int32(i)), nil\n\tcase reflect.Int64:\n\t\ti, err := strconv.ParseInt(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int64(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int64(i)), nil\n\tcase reflect.String:\n\t\treturn reflect.ValueOf(v), nil\n\tcase reflect.Bool:\n\t\tb, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(false), err\n\t\t}\n\t\treturn reflect.ValueOf(bool(b)), nil\n\tcase reflect.Float64:\n\t\tf, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(float64(0)), errors.New(\"error float\")\n\t\t}\n\t\treturn reflect.ValueOf(float64(f)), nil\n\tcase reflect.Slice:\n\t\treturn reflectSliceValue(fieldType, fieldValue, v)\n\tdefault:\n\t\treturn reflect.ValueOf(0), errors.New(\"turbo: not supported kind[\" + k.String() + \"]\")\n\t}\n}", "func (t *Table) Putf(row, col int, v float64) bool {\n\tif row >= len(t.Row) || col >= len(t.ColDefs) {\n\t\treturn false\n\t}\n\tif row < 0 {\n\t\trow = len(t.Row) - 1\n\t}\n\tt.Row[row].Col[col].Type = CELLFLOAT\n\tt.Row[row].Col[col].Fval = v\n\treturn true\n}", "func (s *Sensor) Value(n int) (string, error) {\n\treturn stringFrom(attributeOf(s, fmt.Sprint(value, n)))\n}", "func (this *JSONArray) Float64(index int) float64 {\n\treturn this.innerArray[index].(float64)\n}", "func (r Row) GetString(colIdx int) string {\n\treturn r.c.columns[colIdx].GetString(r.idx)\n}", "func (c *StringValueMap) GetAsFloat(key string) float32 {\n\treturn c.GetAsFloatWithDefault(key, 0)\n}", "func (c *StringValueMap) GetAsNullableFloat(key string) *float32 {\n\tif value, ok := c.value[key]; ok {\n\t\treturn convert.FloatConverter.ToNullableFloat(value)\n\t}\n\treturn nil\n}", "func (m *MockValues) ValueAt(arg0 int) float64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ValueAt\", arg0)\n\tret0, _ := ret[0].(float64)\n\treturn ret0\n}", "func (s SimpleCsv) GetCellByField(columnName string, row int) (string, bool) {\n\tcolumn := s.GetHeaderPosition(columnName)\n\tif column >= 0 && row < len(s) {\n\t\treturn s[row][column], true\n\t}\n\treturn \"\", false\n}", "func (cf *ColumnField) checkValue() error {\n\tswitch cf.Type {\n\tcase \"\":\n\t\ttyp := cf.Field.Type\n\t\tfor typ.Kind() == reflect.Ptr {\n\t\t\ttyp = typ.Elem()\n\t\t}\n\t\tswitch typ.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tcf.Type = \"Bool\"\n\t\tcase reflect.Int8:\n\t\t\tcf.Type = \"Int8\"\n\t\tcase reflect.Int16:\n\t\t\tcf.Type = \"Int16\"\n\t\tcase reflect.Int32:\n\t\t\tcf.Type = \"Int32\"\n\t\tcase reflect.Int64, reflect.Int:\n\t\t\tcf.Type = \"Int64\"\n\t\tcase reflect.Uint8:\n\t\t\tcf.Type = \"UInt8\"\n\t\tcase reflect.Uint16:\n\t\t\tcf.Type = \"UInt16\"\n\t\tcase reflect.Uint32:\n\t\t\tcf.Type = \"UInt32\"\n\t\tcase reflect.Uint64, reflect.Uint:\n\t\t\tcf.Type = \"UInt64\"\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tcf.Type = \"Float\"\n\t\tcase reflect.Struct:\n\t\t\tswitch reflect.Zero(typ).Interface().(type) {\n\t\t\tcase time.Time:\n\t\t\t\tcf.Type = \"Time\"\n\t\t\tcase Geo:\n\t\t\t\tcf.Type = \"WGS84GeoPoint\"\n\t\t\t}\n\t\t}\n\t\tif cf.Type == \"\" {\n\t\t\treturn NewError(TypeError, \"The type is not supported as _value.\", map[string]interface{}{\n\t\t\t\t\"type\": reflect.TypeOf(cf.Field.Type).Name(),\n\t\t\t})\n\t\t}\n\tcase \"Bool\", \"Int8\", \"Int16\", \"Int32\", \"Int64\", \"UInt8\", \"UInt16\", \"UInt32\", \"UInt64\",\n\t\t\"Float\", \"Time\", \"WGS84GeoPoint\", \"TokyoGeoPoint\":\n\tdefault:\n\t\treturn NewError(TypeError, \"The type is not supported as _value.\", map[string]interface{}{\n\t\t\t\"type\": cf.Type,\n\t\t})\n\t}\n\treturn nil\n}", "func FloatValue(f float64) Value { return StringValue(strconv.FormatFloat(f, 'f', -1, 64)) }", "func get(row []string, col int) string {\n\tif col < len(row) {\n\t\treturn row[col]\n\t}\n\treturn \"\"\n}" ]
[ "0.75364584", "0.6123415", "0.6121763", "0.6119237", "0.61098325", "0.6106026", "0.6010408", "0.59776723", "0.59278715", "0.58837295", "0.5854869", "0.58399117", "0.57418776", "0.56525666", "0.5634338", "0.56315815", "0.5627601", "0.56131566", "0.5574433", "0.55499494", "0.5537568", "0.5434669", "0.54277396", "0.54248774", "0.5422882", "0.5380056", "0.5311101", "0.52774495", "0.52479625", "0.52434146", "0.52366686", "0.5236475", "0.5220432", "0.5177873", "0.5140879", "0.51335526", "0.5122014", "0.50899863", "0.50852317", "0.50704783", "0.50310993", "0.5028614", "0.50266236", "0.5017228", "0.5011357", "0.50009406", "0.49996448", "0.496372", "0.49569342", "0.4953449", "0.49522728", "0.4933542", "0.49276787", "0.49202114", "0.49201006", "0.4918413", "0.49070755", "0.49041703", "0.49032664", "0.48986664", "0.48983398", "0.4898198", "0.48878348", "0.48781964", "0.4874587", "0.4859172", "0.4854206", "0.48505646", "0.48503324", "0.48409957", "0.48400787", "0.4837849", "0.48349857", "0.48348796", "0.48160064", "0.48132762", "0.48126402", "0.48003134", "0.47974792", "0.47799104", "0.47749943", "0.4765136", "0.47583076", "0.47536233", "0.47493282", "0.47463655", "0.47453305", "0.4742581", "0.47398168", "0.47325787", "0.4724912", "0.47148603", "0.4713497", "0.47107503", "0.4705648", "0.46875313", "0.4684796", "0.46836317", "0.46801922", "0.4668666" ]
0.8536682
0
stringToFloat converts the given string to a float. If the string is "nan", or otherwise not interpretable as a float, returns nil.
func stringToFloat(num string) *float64 { if num == nan { return nil } f, err := strconv.ParseFloat(num, 64) if err != nil { return nil } return &f }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StringToFloat(str String) Float {\n\tv := &stringToFloat{from: str}\n\tstr.AddListener(v)\n\treturn v\n}", "func StringToFloat(param string) float64 {\n\tval, _ := strconv.ParseFloat(param, 10)\n\treturn val\n}", "func (u *Util) StringToFloat(value interface{}) (number float32, err error) {\n number = -999\n if s,ok := value.(string); ok {\n price, err := strconv.ParseFloat(s, 32)\n if err == nil { number = float32(price) }\n } else {\n err = errors.New(\"variable is not string\")\n }\n return number, err\n}", "func strToFloat(str string, typeAbbreviation string) float64 {\n\t// Remove space\n\tif strings.Contains(str, \" \") {\n\t\tstr = strings.ReplaceAll(str, \" \", \"\")\n\t}\n\tstr = strings.ReplaceAll(str, typeAbbreviation, \"\")\n\tf, err := strconv.ParseFloat(str, 10)\n\tif err != nil {\n\t\tErrorLog(\"cannot parse string to float: %s\", str)\n\t\treturn 0\n\t}\n\tInfoLogV1(\"strToFloat %f\", f)\n\treturn f\n}", "func ConvertStringToFloat(str string) float64 {\n\ts, err := strconv.ParseFloat(str, 64)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}", "func StrToFloat(s string) float64 {\n\tif n, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn n\n\t}\n\treturn float64(0.0)\n}", "func convertStringToFloat(str string) float64 {\n\tconst float64Bitsize = 64\n\tconvertedString, err := strconv.ParseFloat(str, float64Bitsize)\n\t// Store error in string array which will be checked in main function later to see if there is a need to exit\n\tif err != nil {\n\t\tlog.Error(\"String to float error: %v\", err)\n\t\terrorsConversion = append(errorsConversion, err)\n\t}\n\treturn convertedString\n}", "func strToFloat(str string) (float64, error) {\n\tnumber, err := strconv.ParseFloat(str, 64)\n\tif err == nil {\n\t\treturn number, nil\n\t}\n\treturn -1, fmt.Errorf(`invalid parameter '%v' was found in the provided csv. \n\t\tMake sure the csv contain only valid float numbers`, str)\n}", "func (s String) Float() float64 {\n\tf, err := cast.ToFloat64E(string(s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func ParseToFloat(data string) (float64, error) {\n\treturn strconv.ParseFloat(data, 0)\n}", "func StringToFloatWithFormat(str String, format string) Float {\n\tif format == \"%f\" { // Same as not using custom format.\n\t\treturn StringToFloat(str)\n\t}\n\n\tv := &stringToFloat{from: str, format: format}\n\tstr.AddListener(v)\n\treturn v\n}", "func toFloat(str string) (float64, error) {\n\tres, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tres = 0.0\n\t}\n\treturn res, err\n}", "func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64 {\n\tif s == \"\" {\n\t\treturn 0.0\n\t}\n\n\tconst maxLength = 20\n\n\tif len([]rune(s)) > maxLength {\n\t\ts = s[0:maxLength]\n\t}\n\n\ts = strings.Replace(s, string(thousandsSeparator), \"\", -1)\n\n\ts = strings.Replace(s, string(decimalSeparator), \".\", -1)\n\n\tif f, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn f\n\t}\n\n\treturn 0.0\n}", "func TestStrToFloat(t *testing.T) {\n\tstrList := []StrToFloatTest{\n\t\t{\"1\", 1.0},\n\t\t{\"2,234.5 \", 2234.5},\n\t\t{\" 3,345,456.123\", 3345456.123},\n\t\t{\"-9234.43\", -9234.43},\n\t\t{\"asd\", 0},\n\t}\n\n\tfor i, str := range strList {\n\t\tnumFloat := StrToFloat(str.NumStr)\n\t\tif !reflect.DeepEqual(str.NumFloat, numFloat) {\n\t\t\tt.Errorf(\"StrToFloat(%v) failed: expected %v got %v\", i, str.NumFloat, numFloat)\n\t\t}\n\t}\n}", "func TestFloat(tst *testing.T) {\n\n\t// Test bool\n\tf, err := StringToFloat(\"1.256898\")\n\tbrtesting.AssertEqual(tst, err, nil, \"StringToFloat failed\")\n\tbrtesting.AssertEqual(tst, f, 1.256898, \"StringToFloat failed\")\n\tf, err = StringToFloat(\"go-bedrock\")\n\tbrtesting.AssertNotEqual(tst, err, nil, \"StringToFloat failed\")\n}", "func IsFloat(str string) bool {\n\treturn str != \"\" && rxFloat.MatchString(str)\n}", "func (app *AppCtx) ConvertPercentageStringToFloat(value string) (float64, error) {\n\tvar f float64\n\tvar err error\n\n\tif value[len(value)-1:] != \"%\" {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s that did not end with '%%' character\", value)\n\t}\n\tif f, err = strconv.ParseFloat(value[0:len(value)-1], 64); err != nil {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s with a non-numerical value before the %%\", value)\n\t}\n\tif f < 0 {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s with a negative percentage\", value)\n\t}\n\tif f > 100 {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s which is over 100%%\", value)\n\t}\n\treturn f, err\n}", "func ToFloat(str string) (float64, error) {\n\tres, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tres = 0.0\n\t}\n\treturn res, err\n}", "func ToFloat(str string) (float64, error) {\n\tres, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tres = 0.0\n\t}\n\treturn res, err\n}", "func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {}", "func LooksLikeAFloat(inputStr string) (matched bool, value float64) {\n\tmatched = floatRe.MatchString(inputStr)\n\tif matched {\n\t\tvalue, _ = strconv.ParseFloat(inputStr, 64)\n\t\treturn true, value\n\t}\n\treturn\n}", "func StringFloat(from string, defaultValue ...float64) FloatAccessor {\n\tnv := &NullFloat{}\n\tpv, err := strconv.ParseFloat(from, 64)\n\tnv.Error = err\n\tif defaultFloat(nv, defaultValue...) {\n\t\treturn nv\n\t}\n\tv := pv\n\tnv.P = &v\n\treturn nv\n}", "func StringToFloat64(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\treturn f\n\n}", "func FloatOrPanic(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func GetFloatFromText(s string) float64 {\n\ti := regexp.\n\t\tMustCompile(\"[^0-9|.]\").\n\t\tReplaceAllString(s, \"\")\n\n\tf, err := strconv.ParseFloat(i, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn f\n}", "func ParseFloat(s string) TermT {\n\tcs := C.CString(s)\n\tdefer C.free(unsafe.Pointer(cs))\n\treturn TermT(C.yices_parse_float(cs))\n}", "func FloatSetString(z *big.Float, s string) (*big.Float, bool)", "func parseFloat(s string) (float64, error) {\n\n\tnegative := s[0] == '-'\n\tif negative {\n\t\ts = s[1:]\n\t}\n\n\ttotal := float64(0)\n\n\tdecimalFound := false\n\tj := 0\n\n\tfor i := len(s) - 1; i >= 0; i-- {\n\n\t\tif !decimalFound && s[i] == '.' {\n\t\t\tdecimalFound = true\n\t\t\ttotal *= math.Pow(10, -float64(j))\n\t\t\tj = 0\n\t\t\tcontinue\n\t\t}\n\n\t\tdigit := float64(s[i] - '0')\n\n\t\tif digit > 9 {\n\t\t\treturn 0, StringNotValid\n\t\t}\n\n\t\ttotal += digit * math.Pow(10, float64(j))\n\t\tj++\n\t}\n\n\tif negative {\n\t\ttotal = -total\n\t}\n\n\treturn total, nil\n}", "func ToF(str string) float64 {\n\tval, err := strconv.ParseFloat(str, 64)\n\tL.IsError(err, str)\n\treturn val\n}", "func Float(str string) bool {\n\t_, err := strconv.ParseFloat(str, 0)\n\treturn err == nil\n}", "func ConvFloat(string string) float64 {\n\tfloat, err := strconv.ParseFloat(string, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn float\n}", "func atof(s string) float64 {\n\tif s == \"*\" {\n\t\treturn math.NaN()\n\t}\n\n\tf, err := strconv.ParseFloat(strings.TrimSpace(s), 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func AsF(str string) (float64, bool) {\n\tres, err := strconv.ParseFloat(str, 64)\n\treturn res, err == nil\n}", "func StringToFloat64(s string, def float64) float64 {\n\tv, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tlog.Warnf(\"failed to parse float64 value: %s\", s)\n\t\treturn def\n\t}\n\treturn v\n}", "func ParseFloat(operand string) (f float64, err error) { return strconv.ParseFloat(operand, 64) }", "func (s String) FloatE() (float64, error) {\n\tf, err := cast.ToFloat64E(string(s))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn f, nil\n}", "func (s *ss) convertFloat(str string, n int) float64 {\n\tif p := indexRune(str, 'p'); p >= 0 {\n\t\t// Atof doesn't handle power-of-2 exponents,\n\t\t// but they're easy to evaluate.\n\t\tf, err := strconv.ParseFloat(str[:p], n)\n\t\tif err != nil {\n\t\t\t// Put full string into error.\n\t\t\tif e, ok := err.(*strconv.NumError); ok {\n\t\t\t\te.Num = str\n\t\t\t}\n\t\t\ts.error(err)\n\t\t}\n\t\tm, err := strconv.Atoi(str[p+1:])\n\t\tif err != nil {\n\t\t\t// Put full string into error.\n\t\t\tif e, ok := err.(*strconv.NumError); ok {\n\t\t\t\te.Num = str\n\t\t\t}\n\t\t\ts.error(err)\n\t\t}\n\t\treturn math.Ldexp(f, m)\n\t}\n\tf, err := strconv.ParseFloat(str, n)\n\tif err != nil {\n\t\ts.error(err)\n\t}\n\treturn f\n}", "func Float(val string) (out *big.Float, err error) {\n\tvalue, ret := new(big.Float).SetString(val)\n\tif !ret {\n\t\terr = fmt.Errorf(\"invalid va\")\n\t\treturn\n\t}\n\treturn value, err\n}", "func Str2float(x string) float64 {\n\tk, _ := strconv.ParseFloat(x, 64)\n\treturn k\n}", "func typeToFloat(args ...DataType) (DataType, error) {\n\tif len(args) != 1 {\n\t\treturn nil, fmt.Errorf(\"Type.toFloat expects exactly 1 argument\")\n\t}\n\n\tswitch object := args[0].(type) {\n\tcase *StringType:\n\t\ti, err := strconv.ParseFloat(object.Value, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Type.toFloat can't convert '%s' to Integer\", object.Value)\n\t\t}\n\t\treturn &FloatType{Value: i}, nil\n\tcase *IntegerType:\n\t\treturn &FloatType{Value: float64(object.Value)}, nil\n\tcase *BooleanType:\n\t\tresult := 0\n\t\tif object.Value {\n\t\t\tresult = 1\n\t\t}\n\t\treturn &FloatType{Value: float64(result)}, nil\n\tcase *FloatType:\n\t\treturn &FloatType{Value: object.Value}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Type.toFloat can't convert '%s' to Integer\", object.Type())\n\t}\n}", "func String2Float64(v string) float64 {\n\tf, err := strconv.ParseFloat(v, 64)\n\tif err != nil {\n\t\t// Log conversion error\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"string\": v,\n\t\t\t\"error\": err.Error(),\n\t\t}).Warn(\"Error converting string to float64\")\n\n\t\treturn 0.0\n\t}\n\n\treturn f\n}", "func parseFloatValue(input string) (res float64) {\n\tvar err error\n\n\tres, err = strconv.ParseFloat(input, 64)\n\tif err != nil {\n\t\t// negative values must be dropped here\n\t\treturn\n\t}\n\n\tif res < 0 {\n\t\treturn 0\n\t}\n\treturn\n}", "func FloatIntStr(valInt string) (out *big.Float, err error) {\n\ti, err := DecodeBigInt(valInt)\n\tif err != nil {\n\t\treturn\n\t}\n\tout, err = FloatInt(i)\n\treturn\n}", "func TestNilToFloat(t *testing.T) {\n\n\tresult, natural := FloatOk(nil, float64(-1))\n\tassert.Equal(t, result, float64(-1))\n\tassert.False(t, natural)\n}", "func toFloat(rawFloat string) float64 {\n\tparsed, _ := strconv.ParseFloat(strings.Replace(strings.Replace(strings.Replace(rawFloat, \"$\", \"\", -1), \",\", \"\", -1), \"%\", \"\", -1), 64)\n\treturn parsed\n}", "func FloatConverter(str string, target reflect.Value) (ok bool) {\n\tf, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttarget.SetFloat(f)\n\treturn true\n}", "func ParseFloat(s string, base int, prec uint, mode big.RoundingMode,) (*big.Float, int, error)", "func FloatParse(z *big.Float, s string, base int) (*big.Float, int, error)", "func ParseFloat(s string, bitSize int) (float64, error) {\n\treturn strconv.ParseFloat(s, bitSize)\n}", "func FloatString(x *big.Float,) string", "func (v Value) Float() float64 {\n\tswitch v.Typ {\n\tdefault:\n\t\tf, _ := strconv.ParseFloat(v.String(), 64)\n\t\treturn f\n\tcase ':':\n\t\treturn float64(v.IntegerV)\n\t}\n}", "func (p *parser) parseFloat(annotations []Symbol) Float {\n\treturn Float{annotations: annotations, isSet: true, text: p.next().Val}\n}", "func ValidFloatStr(val string) bool {\n\tvar validFloat = regexp.MustCompile(`^[-+]?([0-9]+(\\.[0-9]+)?)$`)\n\treturn validFloat.MatchString(val)\n}", "func IsFloat(val any) bool {\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tswitch rv := val.(type) {\n\tcase float32, float64:\n\t\treturn true\n\tcase string:\n\t\treturn rv != \"\" && rxFloat.MatchString(rv)\n\t}\n\treturn false\n}", "func (c *Currency) ParseFloat(s string) error {\n\tf, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tif log.IsTrace() {\n\t\t\tlog.Trace(\"money.Currency.ParseFloat\", \"err\", err, \"arg\", s, \"currency\", c)\n\t\t}\n\t\treturn log.Error(\"money.Currency.ParseFloat.ParseFloat\", \"err\", err, \"arg\", s)\n\t}\n\tc.Valid = true\n\t*c = c.Setf(f)\n\treturn nil\n}", "func coerceToFloat(unk interface{}) (float64, error) {\n\tswitch i := unk.(type) {\n\tcase float64:\n\t\tif math.IsNaN(i) {\n\t\t\treturn i, errors.New(\"value was NaN\")\n\t\t}\n\t\treturn i, nil\n\tcase float32:\n\t\treturn float64(i), nil\n\tcase int:\n\t\treturn float64(i), nil\n\tcase int32:\n\t\treturn float64(i), nil\n\tcase int64:\n\t\treturn float64(i), nil\n\tcase uint:\n\t\treturn float64(i), nil\n\tcase uint32:\n\t\treturn float64(i), nil\n\tcase uint64:\n\t\treturn float64(i), nil\n\tdefault:\n\t\treturn math.NaN(), fmt.Errorf(\"value %q could not be coerced to float64\", i)\n\t}\n}", "func ParseFloatDef(s string, def float64) float64 {\n\tif f, err := strconv.ParseFloat(s, 32); err == nil {\n\t\treturn f\n\t}\n\treturn def\n}", "func StringToFloat32(i []string) ([]float32, error) {\n\to := make([]float32, len(i))\n\tfor k, v := range i {\n\t\tc, err := strconv.ParseFloat(v, 32)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"slicex: unable to convert string '%s' to float32\", v)\n\t\t}\n\n\t\to[k] = float32(c)\n\t}\n\n\treturn o, nil\n}", "func ParseFloat32(str string) float32 {\n\tf, err := strconv.ParseFloat(str, 32)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn float32(f)\n}", "func toFloat(str string) float64 {\n\t// possible numbers\n\tnumbers := map[string]float64{\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9}\n\tlenStr := len(str) - 1\n\t// this would change to true if the number is decimal\n\tdecimal := false\n\t// this would change to true if the number is negative\n\tnagative := false\n\t// where indicate where the dot is\n\tdotPos := 0\n\t// the finall result\n\tvar result float64 = 0\n\t// check if the string is empty\n\tif lenStr == -1 {\n\t\tpanic(\"string is empty\")\n\t}\n\t// check if the string contains any digit\n\tfor i := range numbers {\n\t\tif strings.Contains(str, i) {\n\t\t\tbreak\n\t\t}\n\t\tif i == \"9\" {\n\t\t\tpanic(\"string does not have any digit\")\n\t\t}\n\t}\n\t// check if the string contains a decimal number\n\tif strings.Contains(str, \".\") {\n\t\tpointsCount := strings.Count(str, \".\")\n\t\tif pointsCount != 1 {\n\t\t\tpanic(\"string is not valid\")\n\t\t}\n\t\tlenStr -= 1 // lenStr minus 1, because one of chars in str is a dot\n\t\tdecimal = true\n\t}\n\tfor i, chr := range str {\n\t\tvalue, exist := numbers[string(chr)]\n\t\tif !exist {\n\t\t\tswitch {\n\t\t\tcase string(chr) == \".\":\n\t\t\t\tdotPos = len(str) - i - 1\n\t\t\t\tcontinue\n\t\t\tcase i == 0 && string(chr) == \"-\":\n\t\t\t\tnagative = true\n\t\t\tdefault:\n\t\t\t\tpanic(\"string is not valid\")\n\t\t\t}\n\t\t}\n\t\tresult += value * (math.Pow(10, float64(lenStr)))\n\t\tlenStr -= 1\n\t}\n\tif nagative {\n\t\tresult *= -1\n\t}\n\tif decimal {\n\t\tresult /= math.Pow(10, float64(dotPos))\n\t}\n\treturn result\n}", "func parseFloats(str string) ([]float64, error) {\n\tvar (\n\t\tfields = strings.Fields(str)\n\t\tfloat_parameters = make([]float64, len(fields))\n\t\terr error\n\t)\n\tfor i, v := range fields {\n\t\tfloat_parameters[i], err = strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn float_parameters, nil\n}", "func (data *Data) Float(s ...string) float64 {\n\treturn data.Interface(s...).(float64)\n}", "func ToFloat(value interface{}) interface{} {\n\tswitch value := value.(type) {\n\tcase bool:\n\t\tif value {\n\t\t\treturn 1.0\n\t\t}\n\t\treturn 0.0\n\tcase *bool:\n\t\treturn ToFloat(*value)\n\tcase int:\n\t\treturn float64(value)\n\tcase *int32:\n\t\treturn ToFloat(*value)\n\tcase float32:\n\t\treturn value\n\tcase *float32:\n\t\treturn ToFloat(*value)\n\tcase float64:\n\t\treturn value\n\tcase *float64:\n\t\treturn ToFloat(*value)\n\tcase string:\n\t\tval, err := strconv.ParseFloat(value, 64)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn val\n\tcase *string:\n\t\treturn ToFloat(*value)\n\t}\n\treturn 0.0\n}", "func StrToFloat64(val string) (float64, error) {\n\tFloat64, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn Float64, nil\n}", "func Parse(s string) (float64, error) {\n\treturn strconv.ParseFloat(s, 64)\n}", "func (c *Cell) Float() (float64, error) {\n\tf, err := strconv.ParseFloat(c.Value, 64)\n\tif err != nil {\n\t\treturn math.NaN(), err\n\t}\n\treturn f, nil\n}", "func StringsToFloats(stringValues [][]string) ([][]float64, error) {\n\tvalues := array.Zero2D(len(stringValues), len(stringValues[0]))\n\n\tfor rowIndex := range values {\n\t\tfor colIndex := range values[rowIndex] {\n\t\t\tvar err error = nil\n\n\t\t\ttrimString :=\n\t\t\t\tstrings.TrimSpace(stringValues[rowIndex][colIndex])\n\n\t\t\tvalues[rowIndex][colIndex], err =\n\t\t\t\tstrconv.ParseFloat(trimString, 64)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn values, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn values, nil\n}", "func BytesToFloat(s []byte) (float64, error) {\n // Find the decimal point\n n := bytes.IndexByte(s, '.')\n // ...or just process as an int if there isn't one\n if n == -1 {\n i, err := BytesToInt(s)\n return float64(i), err\n }\n // ...and count decimal places\n dp := (len(s) - n) - 1\n\n // Read the integer section\n i, err := BytesToInt(s[:n])\n if err != nil {\n return 0, err\n }\n f := float64(i)\n // ...and the decimals\n i, err = BytesToInt(s[n+1:])\n if err != nil {\n return 0, err\n }\n f += float64(i) / math.Pow10(dp)\n\n return f, nil\n}", "func (p *Parser) parseFloatLiteral() asti.ExpressionI {\n\tflo := &ast.FloatLiteral{Token: p.curToken}\n\tvalue, err := strconv.ParseFloat(p.curToken.Literal, 64)\n\tif err != nil {\n\t\tp.AddError(\"could not parse %q as float\", p.curToken.Literal)\n\t\treturn nil\n\t}\n\tflo.Value = value\n\treturn flo\n}", "func GetFloat(json []byte, path ...string) (float64, error) {\n\tval, err := GetString(json, path...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tfloatVal, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn -1, ErrFloatParse(val)\n\t}\n\treturn floatVal, nil\n}", "func (t *Type) toFloat(typeTo reflect.Kind) FloatAccessor {\n\tnv := &NullFloat{}\n\tif !t.rv.IsValid() || !isFloat(typeTo) {\n\t\tnv.Error = ErrConvert\n\t\treturn nv\n\t}\n\tswitch {\n\tcase t.IsString(true):\n\t\tvalue, err := strconv.ParseFloat(t.rv.String(), bitSizeMap[typeTo])\n\t\tnv.P = &value\n\t\tnv.Error = err\n\t\treturn nv\n\tcase t.IsFloat(true):\n\t\tfloatValue := t.rv.Float()\n\t\tnv.P = &floatValue\n\t\tif !isSafeFloat(floatValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsInt(true):\n\t\tintValue := t.rv.Int()\n\t\tv := float64(intValue)\n\t\tnv.P = &v\n\t\tif !isSafeIntToFloat(intValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsUint(true):\n\t\tuintValue := t.rv.Uint()\n\t\tv := float64(uintValue)\n\t\tnv.P = &v\n\t\tif !isSafeUintToFloat(uintValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsComplex(true):\n\t\tcomplexValue := t.rv.Complex()\n\t\tv := float64(real(complexValue))\n\t\tnv.P = &v\n\t\tif !isSafeComplexToFloat(complexValue, bitSizeMap[typeTo]) {\n\t\t\tnv.Error = ErrConvert\n\t\t}\n\t\treturn nv\n\tcase t.IsBool(true):\n\t\tvar v float64\n\t\tif t.rv.Bool() {\n\t\t\tv = 1\n\t\t\tnv.P = &v\n\t\t} else {\n\t\t\tnv.P = &v\n\t\t}\n\t\treturn nv\n\t}\n\tnv.Error = ErrConvert\n\treturn nv\n}", "func (m MetricType) resolveFloat(val interface{}) interface{} {\n\t_, isFloat64 := val.(float64)\n\tif isFloat64 && m == FloatType {\n\t\treturn float32(val.(float64))\n\t}\n\n\treturn val\n}", "func ToFloat(value interface{}) (v float64, e error) {\n\tswitch value.(type) {\n\tcase string:\n\t\tv, e = strconv.ParseFloat((value).(string), 64)\n\tcase int, int8, int16, int32, int64:\n\t\tval := reflect.ValueOf(value).Int()\n\t\tv = float64(val)\n\tcase float32:\n\t\tval, _ := ToString(value) // convert float32 into string, to maintain precision\n\t\tv, e = ToFloat(val)\n\tcase float64:\n\t\tv = reflect.ValueOf(value).Float()\n\tdefault:\n\t\te = fmt.Errorf(\"Value %T is type %s\", value, reflect.TypeOf(value).Kind())\n\t}\n\n\treturn\n}", "func (c *StringValueMap) GetAsNullableFloat(key string) *float32 {\n\tif value, ok := c.value[key]; ok {\n\t\treturn convert.FloatConverter.ToNullableFloat(value)\n\t}\n\treturn nil\n}", "func (t *Typed) FloatIf(key string) (float64, bool) {\n\tvalue, exists := t.GetIf(key)\n\tif exists == false {\n\t\treturn 0, false\n\t}\n\tswitch t := value.(type) {\n\tcase float32:\n\t\treturn float64(t), true\n\tcase float64:\n\t\treturn float64(t), true\n\tcase string:\n\t\tf, err := strconv.ParseFloat(t, 10)\n\t\treturn f, err == nil\n\t}\n\treturn 0, false\n}", "func FloatUnmarshalText(z *big.Float, text []byte) error", "func (f FormField) Float() float64 {\n\tif result, err := strconv.ParseFloat(f.Value, 64); err == nil {\n\t\treturn result\n\t}\n\treturn 0.0\n}", "func (a ASTNode) Float() float64 {\n\tif a.t != tval {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Not a basic value\")})\n\t}\n\tv, err := strconv.ParseFloat(a.val.(string), 64)\n\tif err != nil {\n\t\tpanic(ConfErr{a.pos, err})\n\t}\n\treturn v\n}", "func (v Value) Float(bitSize int) (float64, error) {\n\tif v.typ != Number {\n\t\treturn 0, v.newError(\"%s is not a number\", v.Raw())\n\t}\n\tf, err := strconv.ParseFloat(v.Raw(), bitSize)\n\tif err != nil {\n\t\treturn 0, v.newError(\"%v\", err)\n\t}\n\treturn f, nil\n}", "func getPositiveFloatFromString(n string, defaultValue float64, fieldName string) float64 {\n\t// empty value? return default\n\tif n == \"\" {\n\t\treturn defaultValue\n\t}\n\n\ti, err := strconv.ParseFloat(n, 64)\n\tif err != nil || i <= 0 {\n\t\tlog.Printf(\"can't convert field %s (value %s) - not a positive float (falling back to default value)\", fieldName, n)\n\t\treturn defaultValue\n\t}\n\n\treturn i\n}", "func StringFloat32(from string, defaultValue ...float32) Float32Accessor {\n\tnv := &NullFloat32{}\n\tpv, err := strconv.ParseFloat(from, 32)\n\tnv.Error = err\n\tif defaultFloat32(nv, defaultValue...) {\n\t\treturn nv\n\t}\n\tv := float32(pv)\n\tnv.P = &v\n\treturn nv\n}", "func (f FloatField) Clean(value string) (interface{}, ValidationError) {\n\tcleaned_value, err := strconv.ParseFloat(strings.TrimSpace(value), 64)\n\tif err != nil {\n\t\treturn nil, errors.New(\"The value must be a valid float.\")\n\t}\n\treturn cleaned_value, nil\n}", "func parseFloat64(str string, dest *float64) error {\n\tstr = strings.TrimSpace(str)\n\tif len(str) == 0 {\n\t\t*dest = 0\n\t\treturn nil\n\t}\n\n\tstr = strings.Replace(str, \",\", \"\", -1) // Remove commas\n\tval, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*dest = val\n\treturn nil\n}", "func GetFloat(in *google_protobuf.FloatValue) *float32 {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\treturn &in.Value\n}", "func parseNullableFloat64FromString(content string, aggErr *AggregateError) *float64 {\n if len(content) == 0 {\n return nil\n }\n result := parseFloat64FromString(content, aggErr)\n return &result\n}", "func parseFloat64(s string) (float64, bool) {\n\tf, err := strconv.ParseFloat(strings.TrimSpace(s), 64)\n\tif err != nil {\n\t\treturn 0, false\n\t}\n\treturn f, true\n}", "func floatStringToNullInt(s string, fieldName string) sql.NullInt64 {\n\tif s == \"\" {\n\t\treturn sql.NullInt64{}\n\t}\n\n\tvar res int64\n\n\ts = strings.Replace(s, \",\", \".\", -1)\n\tval, err := strconv.ParseFloat(s, 32)\n\tif err != nil {\n\t\tlog.Fatal(\"Erro ao parsear valor em \", fieldName, \" \", err)\n\t}\n\tres = int64(math.Round(val))\n\n\treturn sql.NullInt64{\n\t\tInt64: res,\n\t\tValid: true,\n\t}\n}", "func PercentFromString(percentStr string) (percent float64, err error) {\n\tarray := strings.Fields(percentStr)\n\tif len(array) < 1 {\n\t\treturn percent, fmt.Errorf(\"Failed to parse %s\", percentStr)\n\t}\n\n\tpercent, err = strconv.ParseFloat(array[0], 64)\n\n\treturn\n}", "func (n null) Float() float64 {\n\tpanic(ErrInvalidConvNilToFloat)\n}", "func voltToFloat32(s string) float32 {\n\tf, _ := strconv.ParseFloat(strings.TrimSuffix(s, \"V\"), 32)\n\treturn float32(f)\n}", "func (f *Float) SetString(s string, base int) error {\n\tf.doinit()\n\tif base < 2 || base > 36 {\n\t\treturn os.ErrInvalid\n\t}\n\tp := C.CString(s)\n\tdefer C.free(unsafe.Pointer(p))\n\tif C.mpf_set_str(&f.i[0], p, C.int(base)) < 0 {\n\t\treturn os.ErrInvalid\n\t}\n\treturn nil\n}", "func (imf *ImprFloat) FromString(valStr string) *ImprFloat {\n\timf.resetFlag()\n\tif !ValidPositiveFloatStr(valStr) {\n\t\terr := fmt.Errorf(\"ImprFloat warning: Bad float string %v, use default value\", valStr)\n\t\tlog.Println(err)\n\t\timf.err = err\n\t\tvalStr = \"0\"\n\t}\n\tvalStr = strings.TrimSpace(valStr)\n\timf.data = []byte(valStr)\n\t//fill '.'\n\tsize := len(imf.data)\n\tpos := bytes.Index(imf.data, []byte(\".\"))\n\tif pos == -1 { // no '.' so assume '.' in the end\n\t\timf.data = append(imf.data, '.')\n\t\tpos = size\n\t}\n\timf.pos = pos\n\treturn imf\n}", "func fpToFloat32(t string, x gosmc.SMCBytes, size uint32) (float32, error) {\n\tif v, ok := AppleFPConv[t]; ok {\n\t\tres := binary.BigEndian.Uint16(x[:size])\n\t\tif v.Signed {\n\t\t\treturn float32(int16(res)) / v.Div, nil\n\t\t} else {\n\t\t\treturn float32(res) / v.Div, nil\n\t\t}\n\t}\n\n\treturn 0.0, fmt.Errorf(\"unable to convert to float32 type %q, bytes %v to float32\", t, x)\n}", "func (s VerbatimString) ToFloat64() (float64, error) { return _verbatimString(s).ToFloat64() }", "func NewFromStringErr(s string) (Fixed, error) {\n\tif strings.HasPrefix(s, \"-\") {\n\t\treturn NaN, errNegativeNum\n\t}\n\tif strings.ContainsAny(s, \"eE\") {\n\t\tf, err := strconv.ParseFloat(s, 64)\n\t\tif err != nil {\n\t\t\treturn NaN, err\n\t\t}\n\t\treturn NewFromFloat(f), nil\n\t}\n\tif \"NaN\" == s {\n\t\treturn NaN, nil\n\t}\n\tperiod := strings.Index(s, \".\")\n\tvar i uint64\n\tvar f uint64\n\tvar err error\n\tif period == -1 {\n\t\ti, err = strconv.ParseUint(s, 10, 64)\n\t} else {\n\t\ti, err = strconv.ParseUint(s[:period], 10, 64)\n\t\tfs := s[period+1:]\n\t\tfs = fs + zeros[:maxInt(0, nPlaces-len(fs))]\n\t\tf, err = strconv.ParseUint(fs[0:nPlaces], 10, 64)\n\t}\n\tif err != nil {\n\t\treturn NaN, err\n\t}\n\tif float64(i) > max {\n\t\treturn NaN, errTooLarge\n\t}\n\treturn Fixed{fp: i*scale + f}, nil\n}", "func ToFloat(v Value) (float64, bool) {\n\tswitch v.iface.(type) {\n\tcase int64:\n\t\treturn float64(v.AsInt()), true\n\tcase float64:\n\t\treturn v.AsFloat(), true\n\tcase string:\n\t\tn, f, tp := StringToNumber(v.AsString())\n\t\tswitch tp {\n\t\tcase IsInt:\n\t\t\treturn float64(n), true\n\t\tcase IsFloat:\n\t\t\treturn f, true\n\t\t}\n\t}\n\treturn 0, false\n}", "func (c *Cell) Float() (float64, error) {\n\tif !c.Is(Numeric) {\n\t\treturn 0, fmt.Errorf(\"cell data is not numeric\")\n\t}\n\n\tf, err := strconv.ParseFloat(c.data, 64)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to convert cell data to number\")\n\t}\n\treturn f, nil\n}", "func BytesToFloat(b []byte) float32 {\n\tif b == nil {\n\t\treturn 0.0\n\t} else {\n\t\treturn *(*float32)(unsafe.Pointer(&b[0]))\n\t}\n}", "func (tr Row) FloatErr(nn int) (val float64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase float64, float32:\n\t\tval = reflect.ValueOf(data).Float()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i >= 2<<53 || i <= -(2<<53) {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(i)\n\t\t}\n\tcase uint64, uint32, uint16, uint8:\n\t\tu := reflect.ValueOf(data).Uint()\n\t\tif u >= 2<<53 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(u)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseFloat(string(data), 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}", "func ParseFloat64(str string) float64 {\n\tf, _ := strconv.ParseFloat(str, 32)\n\treturn f\n}" ]
[ "0.8082372", "0.7937381", "0.7389342", "0.7340307", "0.73294926", "0.73089814", "0.7286272", "0.7238494", "0.7159106", "0.7103468", "0.70908254", "0.69628805", "0.6879595", "0.6753214", "0.6728125", "0.65932554", "0.6590158", "0.65481657", "0.65481657", "0.65408546", "0.6523945", "0.65147793", "0.64897084", "0.6468941", "0.64184374", "0.6385817", "0.632022", "0.6282946", "0.6251961", "0.6236332", "0.62268203", "0.6223915", "0.61927265", "0.6188992", "0.61734337", "0.6173388", "0.61470145", "0.6122877", "0.6081949", "0.60567415", "0.60400665", "0.60271275", "0.60012287", "0.5987612", "0.596267", "0.59622765", "0.5953243", "0.5948147", "0.5914897", "0.59056634", "0.5902569", "0.59012365", "0.58748776", "0.58323896", "0.5778863", "0.5772328", "0.5688848", "0.56715477", "0.56645995", "0.5655493", "0.5650361", "0.56275636", "0.56269306", "0.56113863", "0.55938303", "0.5577414", "0.55590856", "0.5548129", "0.55390286", "0.5528052", "0.55225515", "0.5512806", "0.55011326", "0.54926354", "0.5482938", "0.5481511", "0.54799485", "0.546701", "0.54490674", "0.5447779", "0.5446511", "0.5433666", "0.543125", "0.5420627", "0.54194957", "0.54094684", "0.54058576", "0.5401263", "0.53948486", "0.53759855", "0.5371473", "0.535345", "0.5347845", "0.53475815", "0.5324244", "0.5303132", "0.5295869", "0.5290785", "0.5289281", "0.52891564" ]
0.83623695
0
valueLeftOf returns the stringToFloat() of the value to the left of the given index in the row. If i is 0, returns nil.
func valueLeftOf(row []string, position int) *float64 { if position <= 0 { return nil } return stringToFloat(row[position-1]) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func valueRightOf(row []string, position int) *float64 {\n\tif position >= len(row)-1 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position+1])\n}", "func (o *WorkbookChart) GetLeft() AnyOfnumberstringstring {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (b *Bound) Left() float64 {\n\treturn b.sw[0]\n}", "func (f fieldElement) leftShift(i uint) (result fieldElement) {\n\t// 0 <= i < 128\n\tif i < 64 {\n\t\tcopy(result[:], f[:])\n\t} else if i < 128 {\n\t\tresult[1] = f[0]\n\t\tresult[2] = f[1]\n\t\tresult[3] = f[2]\n\t\ti -= 64\n\t} else {\n\t\tpanic(\"leftShift argument out of range\")\n\t}\n\n\tresult[3] = result[3]<<i | result[2]>>(64-i)\n\tresult[2] = result[2]<<i | result[1]>>(64-i)\n\tresult[1] = result[1]<<i | result[0]>>(64-i)\n\tresult[0] = result[0] << i\n\n\treturn result\n}", "func valueAt(row []string, position int) *float64 {\n\tif row == nil {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position])\n}", "func (self SimpleInterval) Left() float64 {\n\treturn self.LR[0]\n}", "func Left(i int) int {\n\treturn 2 * i\n}", "func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}", "func (l Left) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {\n\tstr, err := l.str.Eval(ctx, row)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar text []rune\n\tswitch str := str.(type) {\n\tcase string:\n\t\ttext = []rune(str)\n\tcase []byte:\n\t\ttext = []rune(string(str))\n\tcase nil:\n\t\treturn nil, nil\n\tdefault:\n\t\treturn nil, sql.ErrInvalidType.New(reflect.TypeOf(str).String())\n\t}\n\n\tvar length int64\n\truneCount := int64(len(text))\n\tlen, err := l.len.Eval(ctx, row)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len == nil {\n\t\treturn nil, nil\n\t}\n\n\tlen, err = sql.Int64.Convert(len)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlength = len.(int64)\n\n\tif length > runeCount {\n\t\tlength = runeCount\n\t}\n\tif length <= 0 {\n\t\treturn \"\", nil\n\t}\n\n\treturn string(text[:length]), nil\n}", "func (o *WorkbookChart) GetLeftOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Left, true\n}", "func left(i int) int {\n\treturn i*2 + 1\n}", "func left(index int) int {\n\treturn 2*index + 1\n}", "func left(i int) int {\r\n\treturn (i * 2) + 1\r\n}", "func ColumnLeft(name string) {\n\tidx := colIndex(name)\n\tif idx > 0 {\n\t\tswapCols(idx, idx-1)\n\t}\n}", "func (unpacker *BitUnpacker) Left() uint32 {\n\treturn unpacker.size - (unpacker.pbyte*8 + unpacker.pbit)\n}", "func (o DashboardSpacingPtrOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Left\n\t}).(pulumi.StringPtrOutput)\n}", "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func (o DashboardSpacingOutput) Left() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Left }).(pulumi.StringPtrOutput)\n}", "func (fn *formulaFuncs) LEFT(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"LEFT\", argsList)\n}", "func GetLeftIndex(n int) int {\n\treturn 2*n + 1\n}", "func (b *TestDriver) Left(val int) error {\n\tlog.Printf(\"Left: %d\", val)\n\treturn nil\n}", "func (me *BitStream) Left() int {\n\treturn me.Bits - me.Index\n}", "func FloatValLT(v float64) predicate.Property {\n\treturn predicate.Property(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldFloatVal), v))\n\t})\n}", "func (s *SubsetFontObj) KernValueByLeft(left uint) (bool, *core.KernValue) {\n\n\tif !s.ttfFontOption.UseKerning {\n\t\treturn false, nil\n\t}\n\n\tk := s.ttfp.Kern()\n\tif k == nil {\n\t\treturn false, nil\n\t}\n\n\tif kval, ok := k.Kerning[left]; ok {\n\t\treturn true, &kval\n\t}\n\n\treturn false, nil\n}", "func (o *TileBounds) GetLeftOk() (*int32, bool) {\n\tif o == nil || o.Left == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Left, true\n}", "func (o *WorkbookChart) SetLeft(v AnyOfnumberstringstring) {\n\to.Left = &v\n}", "func (l *Label) left(g *Graph) (*Label, *DataError) {\n Assert(nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n \n return g.labelStore.findAllowZero(l.l)\n}", "func leftAngleCode(data []byte) int {\n\ti := 1\n\tfor i < len(data) {\n\t\tif data[i] == '>' {\n\t\t\tbreak\n\t\t}\n\t\tif !isnum(data[i]) {\n\t\t\treturn 0\n\t\t}\n\t\ti++\n\t}\n\treturn i\n}", "func (tm *Term) FixLeft() error {\n\ttm.FixCols = ints.MaxInt(tm.FixCols-1, 0)\n\treturn tm.Draw()\n}", "func LeftChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No left child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, Offset(index, depth)*2), nil\n}", "func left(x uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\treturn x ^ (0x01 << (level(x) - 1))\n}", "func LeftRight(val string) (string, string, bool) {\n\tif len(val) < 2 {\n\t\treturn \"\", val, false\n\t}\n\tswitch by := val[0]; by {\n\tcase '`':\n\t\tvals := strings.Split(val, \"`.`\")\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", IdentityTrim(val), false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t\t// wat, no idea what this is\n\t\treturn \"\", val, false\n\tcase '[':\n\t\tvals := strings.Split(val, \"].[\")\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", IdentityTrim(val), false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t\t// wat, no idea what this is\n\t\treturn \"\", val, false\n\tdefault:\n\t\tvals := strings.SplitN(val, \".\", 2)\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", val, false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t}\n\n\treturn \"\", val, false\n}", "func (e Equation) Left() Type {\n\treturn e.left\n}", "func (sopsTxtJustify TextJustify) Left() TextJustify {\n\n\tlockStrOpsTextJustify.Lock()\n\n\tdefer lockStrOpsTextJustify.Unlock()\n\n\treturn TextJustify(1)\n}", "func ValueLT(v []byte) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.LT(s.C(FieldValue), v))\n\t\t},\n\t)\n}", "func (m *Model) wordLeft() bool {\n\tif m.pos == 0 || len(m.value) == 0 {\n\t\treturn false\n\t}\n\n\tif m.EchoMode != EchoNormal {\n\t\treturn m.cursorStart()\n\t}\n\n\tblink := false\n\ti := m.pos - 1\n\tfor i >= 0 {\n\t\tif unicode.IsSpace(m.value[i]) {\n\t\t\tblink = m.setCursor(m.pos - 1)\n\t\t\ti--\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i >= 0 {\n\t\tif !unicode.IsSpace(m.value[i]) {\n\t\t\tblink = m.setCursor(m.pos - 1)\n\t\t\ti--\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn blink\n}", "func searchLeft(a []uint, x uint) int {\n\tlo := 0\n\thi := len(a)\n\tfor lo < hi {\n\t\tmid := (lo + hi) / 2\n\t\tif a[mid] < x {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\n\treturn lo\n}", "func LeftSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Offset(index, depth) * twoPow(depth+1)\n}", "func (ns *numbers) GetFloat(tblname string, rowname interface{}, fieldname string) float64 {\n\tval := ns.get(tblname, fmt.Sprint(rowname), fieldname)\n\tif val == \"\" {\n\t\treturn 0.0\n\t}\n\n\tf, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"cannot parse float from gamedata %v %v %v %v\\n\", tblname, rowname, fieldname, err))\n\t}\n\n\treturn f\n}", "func Left(s string, n int) string {\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\trunes := []rune(s)\n\tif n >= len(runes) {\n\t\treturn s\n\t}\n\n\treturn string(runes[:n])\n\n}", "func (board *Board) Left() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif blankPosition%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = LEFT\n\ttile := clone.GetTileAt(blankPosition - 1)\n\tclone.SetTileAt(blankPosition-1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (v *TypePair) GetLeft() (o *Type) {\n\tif v != nil {\n\t\to = v.Left\n\t}\n\treturn\n}", "func LeftOf(x ...interface{}) Either {\n\treturn newEither(false, x...)\n}", "func (tr Row) FloatErr(nn int) (val float64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase float64, float32:\n\t\tval = reflect.ValueOf(data).Float()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i >= 2<<53 || i <= -(2<<53) {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(i)\n\t\t}\n\tcase uint64, uint32, uint16, uint8:\n\t\tu := reflect.ValueOf(data).Uint()\n\t\tif u >= 2<<53 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(u)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseFloat(string(data), 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}", "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func (ll *LinkedList) PopLeft() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.start.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.start = ll.start.next\n\t\tll.start.previous = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}", "func (d *dbBasePostgres) GenerateOperatorLeftCol(fi *fieldInfo, operator string, leftCol *string) {\n\tswitch operator {\n\tcase \"contains\", \"startswith\", \"endswith\":\n\t\t*leftCol = fmt.Sprintf(\"%s::text\", *leftCol)\n\tcase \"iexact\", \"icontains\", \"istartswith\", \"iendswith\":\n\t\t*leftCol = fmt.Sprintf(\"UPPER(%s::text)\", *leftCol)\n\t}\n}", "func Left(text string, size int) string {\n\tspaces := size - Length(text)\n\tif spaces <= 0 {\n\t\treturn text\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(text)\n\n\tfor i := 0; i < spaces; i++ {\n\t\tbuffer.WriteString(space)\n\t}\n\treturn buffer.String()\n}", "func (b *BHeap) left(i int) int {\n\treturn i<<1 + 1\n}", "func (r *RedirectNode) LeftFD() int { return r.rmap.lfd }", "func (s Series) Min() (float64, error) {\n\tif s.elements.Len() == 0 || s.Type() == String {\n\t\treturn math.NaN(), nil\n\t}\n\n\tmin := s.elements.Elem(0)\n\tfor i := 1; i < s.elements.Len(); i++ {\n\t\telem := s.elements.Elem(i)\n\t\tif elem.Less(min) {\n\t\t\tmin = elem\n\t\t}\n\t}\n\treturn min.Float()\n}", "func (m *Machine) Left() {\n\tfmt.Printf(\">> LEFT\\n\")\n\t// If we're at the 0th position, then we need to expand our tape array:\n\tif m.position == 0 {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(make([]Cell, size), m.Tape...)\n\t\tm.position += size\n\t}\n\n\tm.position -= 1\n}", "func (p Permutator) left() int {\n\treturn (p.amount - p.index) + 1\n}", "func ValueLT(column string, arg any, opts ...Option) *sql.Predicate {\n\treturn sql.P(func(b *sql.Builder) {\n\t\topts = normalizePG(b, arg, opts)\n\t\tvaluePath(b, column, opts...)\n\t\tb.WriteOp(sql.OpLT).Arg(arg)\n\t})\n}", "func StringValLT(v string) predicate.Property {\n\treturn predicate.Property(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldStringVal), v))\n\t})\n}", "func getPositiveFloatFromString(n string, defaultValue float64, fieldName string) float64 {\n\t// empty value? return default\n\tif n == \"\" {\n\t\treturn defaultValue\n\t}\n\n\ti, err := strconv.ParseFloat(n, 64)\n\tif err != nil || i <= 0 {\n\t\tlog.Printf(\"can't convert field %s (value %s) - not a positive float (falling back to default value)\", fieldName, n)\n\t\treturn defaultValue\n\t}\n\n\treturn i\n}", "func Left(str string, size int) string {\n\tif str == \"\" || size < 0 {\n\t\treturn \"\"\n\t}\n\tif len(str) <= size {\n\t\treturn str\n\t}\n\treturn str[0:size]\n}", "func InsertLeft(data []int64, counter []int64, x int64) {\n\ti := sort.Search(len(data),\n\t\tfunc(i int) bool {\n\t\t\treturn x <= data[i]\n\t\t})\n\tif i < len(data) {\n\t\tcounter[i]++\n\t} else {\n\t\tcounter[len(data)-1]++\n\t}\n}", "func (tr Row) ForceFloat(nn int) (val float64) {\n\tval, _ = tr.FloatErr(nn)\n\treturn\n}", "func (s SGTree) leftChild(treeIndex int) int {\n\treturn 2*treeIndex + 1\n}", "func leftMost(node *Node) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tcurrent := node\n\n\tfor {\n\t\tif current.left == nil {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.left\n\t}\n}", "func (bst BinaryTree) InsertLeft(n, at *BSTreeNode) *BSTreeNode {\n\tif at.Left == nil {\n\t\tat.Left = n\n\t\treturn at.Left\n\t}\n\tif at.Left.Value >= n.Value {\n\t\treturn bst.InsertLeft(n, at.Left)\n\t}\n\treturn bst.InsertRight(n, at.Left)\n}", "func NewLeft(str, len sql.Expression) sql.Expression {\n\treturn Left{str, len}\n}", "func moveCursorLeft(positionCursor *int, numberDigits int,listOfNumbers [6]int) {\n\n\tif *positionCursor == 0 { \t\t\t\t\t\t // Scenario 1: position of cursor at the beginning of list\n\n\t\t*positionCursor=numberDigits-1\t\t\t\t // set it to the end\n\n\t\tpositionCursor = &listOfNumbers[numberDigits-1] // sets address of position to be that of the correct element\n\n\t} else {\t\t\t\t\t\t\t\t\t\t // Scenario 2: position of cursor is not at the beginning of list\n\n\t\t*positionCursor--\t\t\t\t\t\t\t // decrease the value of position of the cursor\n\n\t\tvar temp = *positionCursor\t\t\t\t\t // temp variable for position of cursor\n\n\t\tpositionCursor = &listOfNumbers[temp] \t // sets address of position to be that of the correct element\n\t}\n}", "func (d *Deque) Left() interface{} {\n\treturn d.left[d.leftOff]\n}", "func (this *BigInteger) ShiftLeft(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.RShiftTo(-n, r)\n\t} else {\n\t\tthis.LShiftTo(n, r)\n\t}\n\treturn r\n}", "func MaskLeft(s string) string {\n\trs := []rune(s)\n\tfor i := 0; i < len(rs)-4; i++ {\n\t\trs[i] = 'X'\n\t}\n\treturn string(rs)\n}", "func ValueLT(v float64) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldValue), v))\n\t})\n}", "func (tr Row) Float(nn int) (val float64) {\n\tval, err := tr.FloatErr(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (tree *Tree) Left() *Node {\n\tvar parent *Node\n\tcurrent := tree.Root\n\tfor current != nil {\n\t\tparent = current\n\t\tcurrent = current.Left\n\t}\n\treturn parent\n}", "func (tm *Term) ScrollLeft() error {\n\ttm.ColSt = ints.MaxInt(tm.ColSt-1, 0)\n\treturn tm.Draw()\n}", "func (e *Tree) PushLeft(value interface{}) *Tree {\n\treturn e.pushTree(\"left\", value)\n}", "func leftChild(i int) int {\n\treturn (i * 2) + 1\n}", "func (f *FilterBetween) WithLeftValue(val interface{}) *FilterBetween {\n\tf.ValueLeft = val\n\treturn f\n}", "func (rbst *RBSTAbelGroup) RotateLeft(root *Node, start, stop, k int) *Node {\r\n\tstart++\r\n\tk %= (stop - start + 1)\r\n\r\n\tx, y := rbst.SplitByRank(root, start-1)\r\n\ty, z := rbst.SplitByRank(y, k)\r\n\tz, p := rbst.SplitByRank(z, stop-start+1-k)\r\n\treturn rbst.Merge(rbst.Merge(rbst.Merge(x, z), y), p)\r\n}", "func MiddleRow(rows [][]string, decimalPlaces int) []string {\n\tmiddleRow := rows[1]\n\tresult := make([]string, len(middleRow))\n\n\tfor i, val := range middleRow {\n\t\tif isNaN(val) {\n\t\t\tresult[i] = averageOf(\n\t\t\t\tdecimalPlaces,\n\t\t\t\tvalueAt(rows[0], i),\n\t\t\t\tvalueAt(rows[2], i),\n\t\t\t\tvalueLeftOf(middleRow, i),\n\t\t\t\tvalueRightOf(middleRow, i),\n\t\t\t)\n\t\t} else {\n\t\t\tresult[i] = val\n\t\t}\n\t}\n\n\treturn result\n}", "func (tree *UTree) Left() *Node {\r\n\tvar parent *Node\r\n\tcurrent := tree.root\r\n\tfor current != nil {\r\n\t\tparent = current\r\n\t\tcurrent = current.left\r\n\t}\r\n\treturn parent\r\n}", "func (pd *philosopherData) LeftChopstick() int {\n\treturn pd.leftChopstick\n}", "func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int {\n\tdims := binaryMatrix.Dimensions()\n\tn, m := dims[0], dims[1]\n\ti, j := 0, m-1\n\tans := -1\n\n\tfor i < n && j >= 0 {\n\t\tif binaryMatrix.Get(i, j) == 1 {\n\t\t\tans = j\n\t\t\tj--\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn ans\n}", "func (n *Node) MoveLeft(p []int, i int) {\n\tif i%NumberColumns > 0 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i-1]\n\t\tc[i-1] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i-1]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (d *dbBase) GenerateOperatorLeftCol(*fieldInfo, string, *string) {\n\t// default not use\n}", "func LeftRotate(x *Node) *Node {\n\tif x.IsNil {\n\t\treturn x\n\t}\n\n\txRight := x.RightChild\n\t// Get right Child\n\t//\n\tif xRight.IsNil {\n\t\treturn xRight\n\t}\n\n\t// Assign parent of x as parent of right child\n\t//\n\txParent := x.Parent\n\txRight.Parent = xParent\n\tif !xParent.IsNil {\n\t\tif xParent.LeftChild == x {\n\t\t\txParent.LeftChild = xRight\n\t\t} else if xParent.RightChild == x {\n\t\t\txParent.RightChild = xRight\n\t\t}\n\t}\n\n\txRightLeft := xRight.LeftChild\n\n\t// Set xright as the parent of x\n\t//\n\tx.Parent = xRight\n\txRight.LeftChild = x\n\n\t// Set right child of x to the left child of xright\n\t//\n\tx.RightChild = xRightLeft\n\tif !xRightLeft.IsNil {\n\t\txRightLeft.Parent = x\n\t}\n\n\treturn xRight\n}", "func EmtellLT(v string) predicate.Repairinvoice {\n\treturn predicate.Repairinvoice(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldEmtell), v))\n\t})\n}", "func (v Vect) TurnLeft() Vect {\n\tif v.X == 0 {\n\t\tif v.Y == 1 {\n\t\t\treturn Vect{-1, 0}\n\t\t}\n\t\tif v.Y == -1 {\n\t\t\treturn Vect{1, 0}\n\t\t}\n\t}\n\tif v.X == -1 {\n\t\treturn Vect{0, -1}\n\t}\n\treturn Vect{0, 1}\n}", "func ShiftLeft(input []byte, shiftNum int) (result []byte, leftMostCarryFlag bool) {\n\tif shiftNum >= 1 {\n\t\tresult = make([]byte, len(input))\n\t\tcopy(result, input)\n\n\t\tfor i := 0; i < len(result); i++ {\n\t\t\tcarryFlag := ((result[i] & 0x80) == 0x80)\n\n\t\t\tif i > 0 && carryFlag {\n\t\t\t\tresult[i-1] |= 0x01\n\t\t\t} else if i == 0 {\n\t\t\t\tleftMostCarryFlag = carryFlag\n\t\t\t}\n\n\t\t\tresult[i] <<= 1\n\t\t}\n\n\t\tif shiftNum == 1 {\n\t\t\treturn result, leftMostCarryFlag\n\t\t}\n\t\treturn ShiftLeft(result, shiftNum-1)\n\t}\n\n\treturn input, false\n}", "func left(s []*big.Int) []*big.Int {\n\tvar r []*big.Int\n\tfor i := range s {\n\t\tif i&1 == 0 { // even\n\t\t\tr = append(r, s[i])\n\t\t}\n\t}\n\treturn r\n}", "func leftRecursive(expr ast.Node) ast.Node {\n\tswitch node := expr.(type) {\n\tcase *ast.Apply:\n\t\treturn node.Target\n\tcase *ast.ApplyBrace:\n\t\treturn node.Left\n\tcase *ast.Binary:\n\t\treturn node.Left\n\tcase *ast.Index:\n\t\treturn node.Target\n\tcase *ast.InSuper:\n\t\treturn node.Index\n\tcase *ast.Slice:\n\t\treturn node.Target\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (fn *formulaFuncs) leftRight(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires at least 1 argument\", name))\n\t}\n\tif argsList.Len() > 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s allows at most 2 arguments\", name))\n\t}\n\ttext, numChars := argsList.Front().Value.(formulaArg).Value(), 1\n\tif argsList.Len() == 2 {\n\t\tnumArg := argsList.Back().Value.(formulaArg).ToNumber()\n\t\tif numArg.Type != ArgNumber {\n\t\t\treturn numArg\n\t\t}\n\t\tif numArg.Number < 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t\t}\n\t\tnumChars = int(numArg.Number)\n\t}\n\tif name == \"LEFTB\" || name == \"RIGHTB\" {\n\t\tif len(text) > numChars {\n\t\t\tif name == \"LEFTB\" {\n\t\t\t\treturn newStringFormulaArg(text[:numChars])\n\t\t\t}\n\t\t\t// RIGHTB\n\t\t\treturn newStringFormulaArg(text[len(text)-numChars:])\n\t\t}\n\t\treturn newStringFormulaArg(text)\n\t}\n\t// LEFT/RIGHT\n\tif utf8.RuneCountInString(text) > numChars {\n\t\tif name == \"LEFT\" {\n\t\t\treturn newStringFormulaArg(string([]rune(text)[:numChars]))\n\t\t}\n\t\t// RIGHT\n\t\treturn newStringFormulaArg(string([]rune(text)[utf8.RuneCountInString(text)-numChars:]))\n\t}\n\treturn newStringFormulaArg(text)\n}", "func (t *Table) Getf(row, col int) float64 {\n\tif row >= len(t.Row) || col >= len(t.ColDefs) {\n\t\treturn float64(0)\n\t}\n\treturn t.Row[row].Col[col].Fval\n}", "func LeftRotate(n *Node) *Node {\n\tr := n.Right\n\tif r == nil {\n\t\treturn n\n\t}\n\n\tn.Right = r.Left\n\tr.Left = n\n\n\treturn r\n}", "func (fn *formulaFuncs) LEFTB(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"LEFTB\", argsList)\n}", "func (dr DatumRow) GetFloat32(colIdx int) (float32, bool) {\n\tdatum := dr[colIdx]\n\tif datum.IsNull() {\n\t\treturn 0, true\n\t}\n\treturn dr[colIdx].GetFloat32(), false\n}", "func getValueAt(index int, colName string, header *[]string, content *[][]string) (string, error) {\n\n\tif index == -1 {\n\t\treturn \"0.0\", nil\n\t}\n\tindexCol := findIndex(colName, header)\n\tif indexCol < 0 {\n\t\treturn \"\", fmt.Errorf(\"column %s not found\", colName)\n\t}\n\tval := (*content)[index][indexCol]\n\tvalF, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%.2f\", valF), nil\n}", "func (i *Input) CursorLeft() {\n\tif i.Pos > 0 {\n\t\ti.Pos--\n\t}\n}", "func (ival *InputValue) Start() Pos {\n\tswitch {\n\tcase ival == nil:\n\t\treturn -1\n\tcase ival.Null != nil:\n\t\treturn ival.Null.Start\n\tcase ival.Scalar != nil:\n\t\treturn ival.Scalar.Start\n\tcase ival.VariableRef != nil:\n\t\treturn ival.VariableRef.Dollar\n\tcase ival.List != nil:\n\t\treturn ival.List.LBracket\n\tcase ival.InputObject != nil:\n\t\treturn ival.InputObject.LBrace\n\tdefault:\n\t\tpanic(\"unknown input value\")\n\t}\n}", "func getCharsLeftCount(limit int, position Point, dir Point) int {\n\tleft := 0\n\t// increase counter while position is not out of boundaries of grid\n\tfor !outOfBound(position, limit) {\n\t\tposition.x += dir.x\n\t\tposition.y += dir.y\n\t\tleft++\n\t}\n\n\treturn left\n}", "func RotateLeft(x uint, k int) uint {\n\tif UintSize == 32 {\n\t\treturn uint(RotateLeft32(uint32(x), k))\n\t}\n\treturn uint(RotateLeft64(uint64(x), k))\n}", "func (h *heap) leftChildIndex(i int64) int64 {\n\treturn i*2 + 1\n}", "func (t *binarySearchST) Floor(key interface{}) interface{} {\n\tutils.AssertF(key != nil, \"Key is nil\")\n\n\ti := t.Rank(key)\n\tif i < t.n && t.keys[i] == key { // key in table\n\t\treturn t.keys[i]\n\t}\n\tif i == 0 { // any key in table greater than key\n\t\treturn nil\n\t}\n\treturn t.keys[i-1]\n}", "func (ns *numbers) GetInt(tblname string, rowname interface{}, fieldname string) int32 {\n\tval := ns.get(tblname, fmt.Sprint(rowname), fieldname)\n\tif val == \"\" {\n\t\treturn 0\n\t}\n\n\tv, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"cannot parse integer from gamedata %v %v %v %v\\n\", tblname, rowname, fieldname, err))\n\t}\n\n\t// round to the integer\n\t// 1.00000001 -> 1\n\t// 0.99999999 -> 1\n\t// -0.9999990 -> -1\n\t// -1.0000001 -> -1\n\treturn int32(v)\n}" ]
[ "0.63793755", "0.60753334", "0.5925222", "0.5773447", "0.57536495", "0.57357925", "0.56298304", "0.5471403", "0.5449241", "0.5393281", "0.5390063", "0.5386777", "0.5379932", "0.53666055", "0.53522307", "0.5348878", "0.53427994", "0.5301268", "0.5254871", "0.5244777", "0.5207459", "0.5187869", "0.5122483", "0.50836307", "0.5081425", "0.50779915", "0.506345", "0.5034121", "0.5026697", "0.50192297", "0.49741992", "0.49734864", "0.49424744", "0.49189582", "0.4914646", "0.4895405", "0.48777628", "0.4845342", "0.47998342", "0.47965688", "0.47923803", "0.4788341", "0.47743607", "0.47419643", "0.4741436", "0.4740517", "0.47283506", "0.4715876", "0.47151685", "0.471304", "0.47024682", "0.46883595", "0.46798527", "0.46661246", "0.46391457", "0.46381867", "0.46304494", "0.46269175", "0.46268034", "0.46188733", "0.46109", "0.4596231", "0.45938903", "0.45916584", "0.45896232", "0.45894438", "0.4555777", "0.45529962", "0.45457786", "0.45407557", "0.45383063", "0.4526801", "0.45230576", "0.4521994", "0.45172146", "0.45108402", "0.45053205", "0.4496761", "0.4488521", "0.44843948", "0.44749337", "0.44722062", "0.4457669", "0.44291157", "0.44284678", "0.44125098", "0.44071206", "0.44062203", "0.43952364", "0.43917075", "0.43900552", "0.43620864", "0.43614057", "0.43578517", "0.43521377", "0.43515787", "0.43508756", "0.43503314", "0.4339831", "0.4331637" ]
0.8459729
0
valueRightOf returns the stringToFloat() of the value to the right of the given index in the row. If i is the last element, returns nil.
func valueRightOf(row []string, position int) *float64 { if position >= len(row)-1 { return nil } return stringToFloat(row[position+1]) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func valueLeftOf(row []string, position int) *float64 {\n\tif position <= 0 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position-1])\n}", "func (b *Bound) Right() float64 {\n\treturn b.ne[0]\n}", "func Right(i int) int {\n\treturn 2*i + 1\n}", "func (self SimpleInterval) Right() float64 {\n\treturn self.LR[1]\n}", "func right(i int) int {\r\n\treturn (i * 2 ) + 2\r\n}", "func right(index int) int {\n\treturn 2*index + 2\n}", "func right(i int) int {\n\treturn i*2 + 2\n}", "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func (matrix Matrix4) Right() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[0][0],\n\t\tmatrix[0][1],\n\t\tmatrix[0][2],\n\t}.Unit()\n}", "func (o DashboardSpacingPtrOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DashboardSpacing) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Right\n\t}).(pulumi.StringPtrOutput)\n}", "func (o DashboardSpacingOutput) Right() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DashboardSpacing) *string { return v.Right }).(pulumi.StringPtrOutput)\n}", "func (q Quat) Right() Vec3f {\n\treturn q.RotateVec(Vec3f{1, 0, 0})\n}", "func ColumnRight(name string) {\n\tidx := colIndex(name)\n\tif idx < len(GlobalColumns)-1 {\n\t\tswapCols(idx, idx+1)\n\t}\n}", "func valueAt(row []string, position int) *float64 {\n\tif row == nil {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position])\n}", "func (s Square) Right() int {\n\treturn s.left + s.width\n}", "func (v *TypePair) GetRight() (o *Type) {\n\tif v != nil {\n\t\to = v.Right\n\t}\n\treturn\n}", "func (fn *formulaFuncs) RIGHT(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"RIGHT\", argsList)\n}", "func (d *Deque) Right() interface{} {\n\tif d.rightOff > 0 {\n\t\treturn d.right[d.rightOff-1]\n\t} else {\n\t\treturn d.blocks[(d.rightIdx-1+len(d.blocks))%len(d.blocks)][blockSize-1]\n\t}\n}", "func GetRightIndex(n int) int {\n\treturn 2*n + 2\n}", "func (b *TestDriver) Right(val int) error {\n\tlog.Printf(\"Right: %d\", val)\n\n\treturn nil\n}", "func right(x uint, n uint) uint {\n\tif level(x) == 0 {\n\t\treturn x\n\t}\n\n\tr := x ^ (0x03 << (level(x) - 1))\n\tfor r > 2*(n-1) {\n\t\tr = left(r)\n\t}\n\treturn r\n}", "func (this *Tuple) PopRight() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tidx := this.Offset(-1)\n\tret := this.data[idx]\n\tthis.data = this.data[:idx]\n\treturn ret\n}", "func (e Equation) Right() Type {\n\treturn e.right\n}", "func (s *Scope) GetRight() raytracing.Vector {\n\treturn *s.Right\n}", "func (b *BHeap) right(i int) int {\n\treturn i<<1 + 2\n}", "func rightMost(node *Node) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tcurrent := node\n\n\tfor {\n\t\tif current.right == nil {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.right\n\t}\n}", "func Right(s string, n int) string {\n\trunes := []rune(s)\n\tif n < 1 {\n\t\treturn \"\"\n\t}\n\tif n >= len(runes) {\n\t\treturn s\n\t}\n\n\treturn string(runes[len(runes)-n:])\n}", "func Right(arr []int, n int) {\n\tmisc.Reverse(arr[n:])\n\tmisc.Reverse(arr[:n])\n\tmisc.Reverse(arr[:])\n}", "func RightChild(index, depth uint) (uint, error) {\n\tif index&1 == 0 {\n\t\treturn 0, errors.New(\"No right child\")\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn Index(depth-1, 1+(Offset(index, depth)*2)), nil\n}", "func (r *RedirectNode) RightFD() int { return r.rmap.rfd }", "func (m *CUserMsg_ParticleManager_UpdateParticleOrient) GetRight() *CMsgVector {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func Right(str string, size int) string {\n\tif str == \"\" || size < 0 {\n\t\treturn \"\"\n\t}\n\tif len(str) <= size {\n\t\treturn str\n\t}\n\treturn str[len(str)-size:]\n}", "func (tm *Term) FixRight() error {\n\ttm.FixCols++ // no obvious max\n\treturn tm.Draw()\n}", "func Right(text string, size int) string {\n\tspaces := size - Length(text)\n\tif spaces <= 0 {\n\t\treturn text\n\t}\n\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < spaces; i++ {\n\t\tbuffer.WriteString(space)\n\t}\n\n\tbuffer.WriteString(text)\n\treturn buffer.String()\n}", "func Right(str string, length int, pad string) string {\n\treturn str + times(pad, length-len(str))\n}", "func (m *Machine) Right() {\n\tfmt.Printf(\">> RIGHT\\n\")\n\t// If we're at the last position, then we need to expand our tape array:\n\tif m.position == (len(m.Tape) - 1) {\n\t\tsize := len(m.Tape)\n\t\tm.Tape = append(m.Tape, make([]Cell, size)...)\n\t}\n\n\tm.position += 1\n}", "func LeftRight(val string) (string, string, bool) {\n\tif len(val) < 2 {\n\t\treturn \"\", val, false\n\t}\n\tswitch by := val[0]; by {\n\tcase '`':\n\t\tvals := strings.Split(val, \"`.`\")\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", IdentityTrim(val), false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t\t// wat, no idea what this is\n\t\treturn \"\", val, false\n\tcase '[':\n\t\tvals := strings.Split(val, \"].[\")\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", IdentityTrim(val), false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t\t// wat, no idea what this is\n\t\treturn \"\", val, false\n\tdefault:\n\t\tvals := strings.SplitN(val, \".\", 2)\n\t\tif len(vals) == 1 {\n\t\t\treturn \"\", val, false\n\t\t} else if len(vals) == 2 {\n\t\t\treturn IdentityTrim(vals[0]), IdentityTrim(vals[1]), true\n\t\t}\n\t}\n\n\treturn \"\", val, false\n}", "func (m *Model) wordRight() bool {\n\tif m.pos >= len(m.value) || len(m.value) == 0 {\n\t\treturn false\n\t}\n\n\tif m.EchoMode != EchoNormal {\n\t\treturn m.cursorEnd()\n\t}\n\n\tblink := false\n\ti := m.pos\n\tfor i < len(m.value) {\n\t\tif unicode.IsSpace(m.value[i]) {\n\t\t\tblink = m.setCursor(m.pos + 1)\n\t\t\ti++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i < len(m.value) {\n\t\tif !unicode.IsSpace(m.value[i]) {\n\t\t\tblink = m.setCursor(m.pos + 1)\n\t\t\ti++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn blink\n}", "func RightSpan(index, depth uint) uint {\n\tif index&1 == 0 {\n\t\treturn index\n\t}\n\tif depth == 0 {\n\t\tdepth = Depth(index)\n\t}\n\n\treturn (Offset(index, depth)+1)*twoPow(depth+1) - 2\n}", "func (d *Deque) PopRight() (res interface{}) {\n\td.rightOff--\n\tif d.rightOff < 0 {\n\t\td.rightOff = blockSize - 1\n\t\td.rightIdx = (d.rightIdx - 1 + len(d.blocks)) % len(d.blocks)\n\t\td.right = d.blocks[d.rightIdx]\n\t}\n\tres, d.right[d.rightOff] = d.right[d.rightOff], nil\n\treturn\n}", "func (fn *formulaFuncs) RIGHTB(argsList *list.List) formulaArg {\n\treturn fn.leftRight(\"RIGHTB\", argsList)\n}", "func ShiftRight(input []byte, shiftNum int) (result []byte, rightMostCarryFlag bool) {\n\tif shiftNum >= 1 {\n\t\tresult = make([]byte, len(input))\n\t\tcopy(result, input)\n\t\tfor i := len(result) - 1; i >= 0; i-- {\n\t\t\tcarryFlag := ((result[i] & 0x01) == 0x01)\n\n\t\t\tif i < len(result)-1 && carryFlag {\n\t\t\t\tresult[i+1] |= 0x80\n\t\t\t} else if i == len(result)-1 {\n\t\t\t\trightMostCarryFlag = carryFlag\n\t\t\t}\n\n\t\t\tresult[i] >>= 1\n\t\t}\n\n\t\tif shiftNum == 1 {\n\t\t\treturn result, rightMostCarryFlag\n\t\t}\n\t\treturn ShiftRight(result, shiftNum-1)\n\t}\n\n\treturn input, false\n}", "func TakeRight(data interface{}, size int) (interface{}, error) {\n\tvar err error\n\n\tresult := func(err *error) interface{} {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdataValue, dataType, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !isZeroOrPositiveNumber(err, \"size\", size) {\n\t\t\treturn data\n\t\t}\n\n\t\tresult := makeSlice(dataType)\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn result.Interface()\n\t\t}\n\n\t\tforEachSlice(dataValue, dataValueLen, func(each reflect.Value, i int) {\n\t\t\tif i >= (dataValueLen - size) {\n\t\t\t\tresult = reflect.Append(result, each)\n\t\t\t}\n\t\t})\n\n\t\treturn result.Interface()\n\t}(&err)\n\n\treturn result, err\n}", "func getValueAt(index int, colName string, header *[]string, content *[][]string) (string, error) {\n\n\tif index == -1 {\n\t\treturn \"0.0\", nil\n\t}\n\tindexCol := findIndex(colName, header)\n\tif indexCol < 0 {\n\t\treturn \"\", fmt.Errorf(\"column %s not found\", colName)\n\t}\n\tval := (*content)[index][indexCol]\n\tvalF, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%.2f\", valF), nil\n}", "func (ll *LinkedList) PopRight() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.end.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.end = ll.end.previous\n\t\tll.end.next = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}", "func (m *SplitRegionResponse) GetRight() *metapb.Region {\n\tif m != nil {\n\t\treturn m.Right\n\t}\n\treturn nil\n}", "func (tr Row) Uint64Err(nn int) (val uint64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase uint64, uint32, uint16, uint8:\n\t\tval = reflect.ValueOf(data).Uint()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i < 0 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = uint64(i)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseUint(string(data), 10, 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}", "func (sopsTxtJustify TextJustify) Right() TextJustify {\n\n\tlockStrOpsTextJustify.Lock()\n\n\tdefer lockStrOpsTextJustify.Unlock()\n\n\treturn TextJustify(2)\n}", "func (v Vect) TurnRight() Vect {\n\tif v.X == 0 {\n\t\tif v.Y == 1 {\n\t\t\treturn Vect{1, 0}\n\t\t}\n\t\tif v.Y == -1 {\n\t\t\treturn Vect{-1, 0}\n\t\t}\n\t}\n\tif v.X == -1 {\n\t\treturn Vect{0, 1}\n\t}\n\treturn Vect{0, -1}\n}", "func (f *FilterBetween) WithRightValue(val interface{}) *FilterBetween {\n\tf.ValueRight = val\n\treturn f\n}", "func chopRight(expr string) (left string, tok rune, right string) {\n\t// XXX implementation redacted for CHALLENGE1.\n\t// TODO restore implementation and replace '~'\n\tparts := strings.Split(expr, \"~\")\n\tif len(parts) != 4 {\n\t\treturn\n\t}\n\tleft = parts[0]\n\ttok = rune(parts[1][0])\n\tright = parts[2]\n\t// close = parts[3]\n\treturn\n}", "func (tree *Tree) sumRight(node *TreeNode) int {\n\tif node == nil {\n\t\treturn 0\n\t}\n\n\tleftSum, rightSum := 0, 0\n\tfor node != nil {\n\t\tif node.left != nil {\n\t\t\tleftSum = max(leftSum, tree.sumLeft(node.left) + node.data)\n\t\t}\n\t\trightSum += node.data\n\t\tnode = node.right\n\t}\n\n\treturn max(rightSum, leftSum)\n}", "func (ubt *ubtTree) Right() UnboundBinaryTree {\n\tif ubt.right == nil {\n\t\tubt.right = &ubtTree{}\n\t}\n\treturn ubt.right\n}", "func lexRightDelim(l *lexer) stateFn {\n\tl.pos += Pos(len(l.rightDelim))\n\tl.emit(itemRightDelim)\n\tif l.peek() == '\\\\' {\n\t\tl.pos++\n\t\tl.emit(itemElideNewline)\n\t}\n\treturn lexText\n}", "func (dr DatumRow) GetFloat64(colIdx int) (float64, bool) {\n\tdatum := dr[colIdx]\n\tif datum.IsNull() {\n\t\treturn 0, true\n\t}\n\treturn dr[colIdx].GetFloat64(), false\n}", "func (e *Tree) Right() *Tree { return e.right }", "func RotateRight(t TermT, n uint32) TermT {\n\treturn TermT(C.yices_rotate_right(C.term_t(t), C.uint32_t(n)))\n}", "func (s SGTree) rightChild(treeIndex int) int {\n\treturn 2*treeIndex + 2\n}", "func (tr Row) Uint64(nn int) (val uint64) {\n\tval, err := tr.Uint64Err(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (h *heap) rightChildIndex(i int64) int64 {\n\treturn i*2 + 2\n}", "func (fn *formulaFuncs) leftRight(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires at least 1 argument\", name))\n\t}\n\tif argsList.Len() > 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s allows at most 2 arguments\", name))\n\t}\n\ttext, numChars := argsList.Front().Value.(formulaArg).Value(), 1\n\tif argsList.Len() == 2 {\n\t\tnumArg := argsList.Back().Value.(formulaArg).ToNumber()\n\t\tif numArg.Type != ArgNumber {\n\t\t\treturn numArg\n\t\t}\n\t\tif numArg.Number < 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t\t}\n\t\tnumChars = int(numArg.Number)\n\t}\n\tif name == \"LEFTB\" || name == \"RIGHTB\" {\n\t\tif len(text) > numChars {\n\t\t\tif name == \"LEFTB\" {\n\t\t\t\treturn newStringFormulaArg(text[:numChars])\n\t\t\t}\n\t\t\t// RIGHTB\n\t\t\treturn newStringFormulaArg(text[len(text)-numChars:])\n\t\t}\n\t\treturn newStringFormulaArg(text)\n\t}\n\t// LEFT/RIGHT\n\tif utf8.RuneCountInString(text) > numChars {\n\t\tif name == \"LEFT\" {\n\t\t\treturn newStringFormulaArg(string([]rune(text)[:numChars]))\n\t\t}\n\t\t// RIGHT\n\t\treturn newStringFormulaArg(string([]rune(text)[utf8.RuneCountInString(text)-numChars:]))\n\t}\n\treturn newStringFormulaArg(text)\n}", "func (board *Board) Right() *Board {\n\tblankPosition := board.PositionOfBlank()\n\tif (blankPosition+1)%board.Dimension == 0 {\n\t\treturn nil\n\t}\n\n\tclone := board.Clone()\n\tclone.move = RIGHT\n\ttile := clone.GetTileAt(blankPosition + 1)\n\tclone.SetTileAt(blankPosition+1, BLANK)\n\tclone.SetTileAt(blankPosition, tile)\n\tclone.cost = clone.g + clone.Cost()\n\treturn clone\n}", "func (e *LineEditor) CursorRight() {\n\t// right moves only if we're within a valid line.\n\t// for past EOF, there's no movement\n\tif e.Cx < len(e.Row) {\n\t\te.Cx++\n\t}\n}", "func mostRightChild(root *treeNode) *treeNode {\n\tif root == nil {\n\t\treturn root\n\t}\n\tp := root\n\tfor p.right != nil {\n\t\tp = p.right\n\t}\n\treturn p\n}", "func DropRight(data interface{}, size int) (interface{}, error) {\n\tvar err error\n\n\tresult := func(err *error) interface{} {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdataValue, dataType, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !isZeroOrPositiveNumber(err, \"size\", size) {\n\t\t\treturn data\n\t\t}\n\n\t\tif size == 0 {\n\t\t\treturn data\n\t\t}\n\n\t\tresult := makeSlice(dataType)\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn result.Interface()\n\t\t}\n\n\t\tforEachSlice(dataValue, dataValueLen, func(each reflect.Value, i int) {\n\t\t\tif i < (dataValueLen - size) {\n\t\t\t\tresult = reflect.Append(result, each)\n\t\t\t}\n\t\t})\n\n\t\treturn result.Interface()\n\t}(&err)\n\n\treturn result, err\n}", "func (l *Label) right(g *Graph) (*Label, *DataError) {\n Assert (nilLabel, l != nil)\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n \n return g.labelStore.findAllowZero(l.r)\n}", "func rotWordRight(input uint32, n uint) uint32 {\n\treturn input<<(32-8*n) | input>>(8*n)\n}", "func (td TupleDesc) GetFloat64(i int, tup Tuple) (v float64, ok bool) {\n\ttd.expectEncoding(i, Float64Enc)\n\tb := td.GetField(i, tup)\n\tif b != nil {\n\t\tv, ok = readFloat64(b), true\n\t}\n\treturn\n}", "func (n *Node) MoveRight(p []int, i int) {\n\tif i%NumberColumns != 3 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+1]\n\t\tc[i+1] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+1]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (r Row) GetFloat64(colIdx int) float64 {\n\treturn r.c.columns[colIdx].GetFloat64(r.idx)\n}", "func decendRight(root *SnailfishNumber) *SnailfishNumber {\n\tfor root.rhs != nil {\n\t\troot = root.rhs\n\t}\n\treturn root\n}", "func (result ContractFunctionResult) GetUint64(index uint64) uint64 {\n\treturn binary.BigEndian.Uint64(result.ContractCallResult[index*32+24 : (index+1)*32])\n}", "func right(s []*big.Int) []*big.Int {\n\tvar r []*big.Int\n\tfor i := range s {\n\t\tif i&1 == 1 { // odd\n\t\t\tr = append(r, s[i])\n\t\t}\n\t}\n\treturn r\n}", "func moveCursorRight( positionCursor *int, numberDigits int, listOfNumbers [6]int) {\n\n\tif *positionCursor == numberDigits-1 { \t\t// Scenario 1: position of cursor at the end of list\n\n\t\t*positionCursor = 0\t\t\t\t\t\t// set it to the beginning\n\n\t\tpositionCursor = &listOfNumbers[0]\t // sets address of position to be that of the correct element\n\n\t} else {\t\t\t\t\t\t\t\t\t// Scenario 2: position of cursor is not at the end of list\n\n\t\t*positionCursor++\t\t\t\t\t\t// increase the value of position of the cursor\n\n\t\tvar temp = *positionCursor\t\t\t\t// temp variable for position of cursor\n\n\t\tpositionCursor = &listOfNumbers[temp]\t// sets address of position to be that of the correct element\n\t}\n }", "func (i *Input) CursorRight() {\n\tif i.Pos < i.Buffer.Len() {\n\t\ti.Pos++\n\t}\n}", "func rightChild(i int) int {\n\treturn (i * 2) + 2\n}", "func (h *heap) rightSiblingIndex(i int64) int64 {\n\treturn i + 1\n}", "func (this *BigInteger) ShiftRight(n int64) *BigInteger {\n\tvar r *BigInteger = NewBigInteger()\n\tif n < 0 {\n\t\tthis.LShiftTo(-n, r)\n\t} else {\n\t\tthis.RShiftTo(n, r)\n\t}\n\treturn r\n}", "func (tree *UTree) Right() *Node {\r\n\tvar parent *Node\r\n\tcurrent := tree.root\r\n\tfor current != nil {\r\n\t\tparent = current\r\n\t\tcurrent = current.right\r\n\t}\r\n\treturn parent\r\n}", "func RightRotate(n *Node) *Node {\n\tl := n.Left\n\tif l == nil {\n\t\treturn n\n\t}\n\n\tn.Left = l.Right\n\tl.Right = n\n\n\treturn l\n}", "func ProcessRotateRight(data []byte, amount int) []byte {\n\treturn ProcessRotateLeft(data, -amount)\n}", "func (tr Row) ForceUint64(nn int) (val uint64) {\n\tval, _ = tr.Uint64Err(nn)\n\treturn\n}", "func (r Rectangle) BottomRight() Point {\n\treturn r.Max\n}", "func (tm *Term) ScrollRight() error {\n\ttm.ColSt++ // no obvious max\n\treturn tm.Draw()\n}", "func (s Stream) DropRight(input interface{}) Stream {\n\ts.operations = append(s.operations, &streamDropRight{\n\t\tItemsValue: s.itemsValue,\n\t\tItemsType: s.itemsType,\n\t\tItem: input,\n\t\tOption: drop.Right,\n\t})\n\treturn s\n}", "func IToFloat64(i interface{}) (res float64, err error) {\n\tswitch v := i.(type) {\n\tcase float64:\n\t\treturn v, nil\n\tcase string:\n\t\treturn strconv.ParseFloat(v, 64)\n\tcase bool:\n\t\tif v {\n\t\t\treturn 1, nil\n\t\t}\n\t\treturn 0, nil\n\tdefault:\n\t\treturn strconv.ParseFloat(fmt.Sprint(i), 64)\n\t}\n}", "func lexRightBracket(t *Tokeniser) stateFunc {\n\tr, w := t.currentRune()\n\tif t.bracketStack.empty() {\n\t\tt.emitErrorf(\"unexpected right bracket %#U\", r)\n\t\treturn nil\n\t} else if toCheck := t.bracketStack.pop(); toCheck != rightBracketToLeftMap[r] {\n\t\tt.emitErrorf(\"unexpected right bracket %#U, expected %#U\", r, rightBracketToLeftMap[r])\n\t\treturn nil\n\t}\n\tt.advance(w)\n\tswitch r {\n\tcase ')':\n\t\tt.emit(RROUND)\n\tcase '}':\n\t\tt.emit(RCURLY)\n\tcase ']':\n\t\tt.emit(RSQUARE)\n\t}\n\treturn lexCode\n}", "func (r Row) GetUint64(colIdx int) uint64 {\n\treturn r.c.columns[colIdx].GetUint64(r.idx)\n}", "func (dr DatumRow) GetUint64(colIdx int) (uint64, bool) {\n\tdatum := dr[colIdx]\n\tif datum.IsNull() {\n\t\treturn 0, true\n\t}\n\treturn dr[colIdx].GetUint64(), false\n}", "func valueForColumn(columns []string, idx int) (string, fields) {\n\tif idx >= len(columns) || columns[idx] == \"_\" {\n\t\treturn \"\", 0\n\t}\n\n\treturn columns[idx], fields(1) << fields(idx-1)\n}", "func (g *Grid) PartialRight() []Partial {\n\tvar r []Partial\n\n\tfor j := 0; j < g.Size; j++ {\n\t\tpartial := \"\"\n\t\tfor i := 0; i < g.Size; i++ {\n\t\t\tt, ok := g.grid[i][j].(charCell)\n\t\t\tif ok && !t.isRight {\n\t\t\t\tPanicIfFalse(t.isDown, \"either isDown or isRight should be set\")\n\t\t\t\tpartial += fmt.Sprintf(\"%c\", t.char)\n\t\t\t} else {\n\t\t\t\tif len(partial) > 1 {\n\t\t\t\t\tr = append(r, Partial{Partial: partial, X: i - len(partial), Y: j})\n\t\t\t\t}\n\t\t\t\tpartial = \"\"\n\t\t\t}\n\t\t}\n\t\tif len(partial) > 1 {\n\t\t\tr = append(r, Partial{Partial: partial, X: g.Size - len(partial), Y: j})\n\t\t}\n\t}\n\treturn r\n}", "func TrimRightFunc(f func(rune) bool) MapFunc {\n\treturn func(s string) string { return strings.TrimRightFunc(s, f) }\n}", "func (column *ColumnString) GetItem(i int) interface{} {\n\treturn interface{}(column.data[i])\n}", "func (builder *Builder) Right(n uint) *Builder {\n\treturn builder.With(Right(n))\n}", "func (p *Pager) moveRight(delta int) {\n\tif p.ShowLineNumbers && delta > 0 {\n\t\tp.ShowLineNumbers = false\n\t\treturn\n\t}\n\n\tif p.leftColumnZeroBased == 0 && delta < 0 {\n\t\tp.ShowLineNumbers = true\n\t\treturn\n\t}\n\n\tresult := p.leftColumnZeroBased + delta\n\tif result < 0 {\n\t\tp.leftColumnZeroBased = 0\n\t} else {\n\t\tp.leftColumnZeroBased = result\n\t}\n}", "func bitFillRight(i *big.Int) {\n\tif s := i.Sign(); s < 0 {\n\t\tpanic(\"pre-condition failure\")\n\t} else if s == 0 {\n\t\treturn\n\t}\n\tn := i.BitLen()\n\tif n > 0xFFFF {\n\t\tpanic(\"interval: input is too large\")\n\t}\n\ti.SetInt64(1)\n\ti.Lsh(i, uint(n))\n\ti.Sub(i, one)\n}", "func (n *Node) MoveDownRight(p []int, i int) {\n\tif i%NumberColumns != 3 && i < 8 {\n\t\tc := n.ClonePuzzle()\n\t\ttemp := c[i+5]\n\t\tc[i+5] = c[i]\n\t\tc[i] = temp\n\n\t\tchild := NewPuzzle(c)\n\t\tchild.Move = boardPositions[i+5]\n\t\tchild.Parent = n\n\t\tchild.G = n.G + 1\n\t\tn.Children = append(n.Children, child)\n\t}\n}", "func (v *Venom) GetFloat64(key string) float64 {\n\tval, ok := v.Find(key)\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tif value, ok := val.(float64); !ok {\n\t\treturn 0\n\t} else {\n\t\treturn value\n\t}\n}", "func (e *Tree) PushRight(value interface{}) *Tree {\n\treturn e.pushTree(\"right\", value)\n}", "func (r *rows) columnInt64(iCol int) (v int64, err error) {\n\tv = bin.Xsqlite3_column_int64(r.tls, r.pstmt, int32(iCol))\n\treturn v, nil\n}" ]
[ "0.6006863", "0.59945416", "0.5970664", "0.5819593", "0.5782678", "0.5774075", "0.5750997", "0.56056243", "0.56044173", "0.5571784", "0.55708253", "0.5532962", "0.5486794", "0.54614246", "0.5410383", "0.53747565", "0.53538173", "0.5330816", "0.53068346", "0.52522296", "0.51821405", "0.51809704", "0.51643634", "0.5122943", "0.5074767", "0.5069671", "0.5052562", "0.50265944", "0.50099677", "0.49809358", "0.49455595", "0.49244228", "0.491431", "0.48969603", "0.48398024", "0.4810419", "0.48098215", "0.48077083", "0.48061496", "0.47594538", "0.47266883", "0.47069117", "0.47037548", "0.46936584", "0.46851978", "0.4672979", "0.46696204", "0.46626213", "0.4645772", "0.46419024", "0.46374154", "0.46299994", "0.46276248", "0.46213204", "0.46107522", "0.4604663", "0.4599639", "0.45994318", "0.45982575", "0.45897576", "0.45675126", "0.45639637", "0.4558226", "0.45575675", "0.4533706", "0.44993448", "0.44985363", "0.4486019", "0.44773698", "0.4472269", "0.44717592", "0.44653016", "0.4459898", "0.44518933", "0.4443246", "0.44381005", "0.44372383", "0.4432156", "0.44262016", "0.44236466", "0.44195077", "0.44192916", "0.4412821", "0.4412177", "0.44047663", "0.43970248", "0.4382568", "0.43667632", "0.43659824", "0.43564403", "0.43518618", "0.43376553", "0.4336736", "0.43344858", "0.4333649", "0.4332069", "0.4329067", "0.4328004", "0.43255913", "0.43176636" ]
0.84193784
0
NextRow returns the next row of CSV data as a slice of strings, with any nan values in the input data replaced with interpreted values.
func (c *CSVInterpolator) NextRow() ([]string, error) { c.row++ rowsToGet := c.numRows() rows, err := c.rp.GetRows(c.rowToStartWith(), rowsToGet) if err != nil { return nil, err } if rowsToGet != rowsNeededToInterpolate { rows = [][]string{nil, rows[0], rows[1]} } if rows[1] == nil { return nil, io.EOF } return MiddleRow(rows, c.decimalPlaces), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (sv *sorterValues) NextRow() sqlbase.EncDatumRow {\n\tif len(sv.rows) == 0 {\n\t\treturn nil\n\t}\n\n\tx := heap.Pop(sv)\n\treturn *x.(*sqlbase.EncDatumRow)\n}", "func (ds *Dataset) Next() ([]float64, error) {\n\tds.lock.Lock()\n\tdefer ds.lock.Unlock()\n\tif ds.Mtx == nil {\n\t\treturn nil, ErrNoData\n\t}\n\tr, _ := ds.Mtx.Dims()\n\tif ds.index >= r {\n\t\tds.index = 0\n\t\treturn nil, io.EOF\n\t}\n\trows := ds.Mtx.RawRowView(ds.index)\n\tds.index++\n\treturn rows, nil\n}", "func TableNextRow() {\n\tTableNextRowV(0, 0.0)\n}", "func (n *noopProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor n.State == execinfra.StateRunning {\n\t\trow, meta := n.input.Next()\n\n\t\tif meta != nil {\n\t\t\tif meta.Err != nil {\n\t\t\t\tn.MoveToDraining(nil /* err */)\n\t\t\t}\n\t\t\treturn nil, meta\n\t\t}\n\t\tif row == nil {\n\t\t\tn.MoveToDraining(nil /* err */)\n\t\t\tbreak\n\t\t}\n\n\t\tif outRow := n.ProcessRowHelper(row); outRow != nil {\n\t\t\treturn outRow, nil\n\t\t}\n\t}\n\treturn nil, n.DrainHelper()\n}", "func (rows *Rows) Next(dest []driver.Value) error {\n\tif rows.current >= len(rows.resultSet.Rows) {\n\t\treturn io.EOF\n\t}\n\n\trow := rows.resultSet.Rows[rows.current]\n\tfor i, d := range row.Data {\n\t\tdest[i] = *d.VarCharValue\n\t}\n\n\trows.current++\n\treturn nil\n}", "func (pr *newPartialResult) Next() (data []types.Datum, err error) {\n\tchunk := pr.getChunk()\n\tif chunk == nil {\n\t\treturn nil, nil\n\t}\n\tdata = make([]types.Datum, pr.rowLen)\n\tfor i := 0; i < pr.rowLen; i++ {\n\t\tvar l []byte\n\t\tl, chunk.RowsData, err = codec.CutOne(chunk.RowsData)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tdata[i].SetRaw(l)\n\t}\n\treturn\n}", "func (e *TableReaderExecutor) Next() (*Row, error) {\n\tfor {\n\t\t// Get partial result.\n\t\tif e.partialResult == nil {\n\t\t\tvar err error\n\t\t\te.partialResult, err = e.result.Next()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif e.partialResult == nil {\n\t\t\t\t// Finished.\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\t// Get a row from partial result.\n\t\th, rowData, err := e.partialResult.Next()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif rowData == nil {\n\t\t\t// Finish the current partial result and get the next one.\n\t\t\te.partialResult.Close()\n\t\t\te.partialResult = nil\n\t\t\tcontinue\n\t\t}\n\t\tvalues := make([]types.Datum, e.schema.Len())\n\t\terr = codec.SetRawValues(rowData, values)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\terr = decodeRawValues(values, e.schema, e.ctx.GetSessionVars().GetTimeZone())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn resultRowToRow(e.table, h, values, e.asName), nil\n\t}\n}", "func (f *commaSeparated) NextRecord() (string, error) {\n\trec, err := f.csvReader.Read()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tw := csv.NewWriter(buf)\n\tif f.FieldDelim != \"\" {\n\t\tw.Comma, _ = utf8.DecodeRune([]byte(f.FieldDelim))\n\t}\n\terr = w.Write(rec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tw.Flush()\n\n\treturn buf.String(), nil\n}", "func (itr *doltTableRowIter) Next() (sql.Row, error) {\n\tkey, val, err := itr.nomsIter.Next(itr.ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif key == nil && val == nil {\n\t\treturn nil, io.EOF\n\t}\n\n\tkeySl, err := key.(types.Tuple).AsSlice()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif itr.end != nil {\n\t\tisLess, err := keySl.Less(itr.nbf, itr.end)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !isLess {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t}\n\n\tvalSl, err := val.(types.Tuple).AsSlice()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sqlRowFromNomsTupleValueSlices(keySl, valSl, itr.table.sch)\n}", "func (d *Decoder) Next() (*Row, error) {\n\trecord, err := d.reader.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.rowNumber++\n\n\treturn &Row{\n\t\td: d,\n\t\trecord: record,\n\t}, nil\n}", "func (r *Rows) Next(dest []driver.Value) error {\n\ttypes, err := r.columnTypes(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range types {\n\t\tswitch types[i] {\n\t\tcase Integer:\n\t\t\tdest[i] = r.message.getInt64()\n\t\tcase Float:\n\t\t\tdest[i] = r.message.getFloat64()\n\t\tcase Blob:\n\t\t\tdest[i] = r.message.getBlob()\n\t\tcase Text:\n\t\t\tdest[i] = r.message.getString()\n\t\tcase Null:\n\t\t\tr.message.getUint64()\n\t\t\tdest[i] = nil\n\t\tcase UnixTime:\n\t\t\ttimestamp := time.Unix(r.message.getInt64(), 0)\n\t\t\tdest[i] = timestamp\n\t\tcase ISO8601:\n\t\t\tvalue := r.message.getString()\n\t\t\tif value == \"\" {\n\t\t\t\tdest[i] = nil\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvar t time.Time\n\t\t\tvar timeVal time.Time\n\t\t\tvar err error\n\t\t\tvalue = strings.TrimSuffix(value, \"Z\")\n\t\t\tfor _, format := range iso8601Formats {\n\t\t\t\tif timeVal, err = time.ParseInLocation(format, value, time.UTC); err == nil {\n\t\t\t\t\tt = timeVal\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdest[i] = t\n\t\tcase Boolean:\n\t\t\tdest[i] = r.message.getInt64() != 0\n\t\tdefault:\n\t\t\tpanic(\"unknown data type\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (cs *CSVReader) Next() bool {\n\n\tif cs.done {\n\t\treturn false\n\t}\n\n\tif cs.limitchunk > 0 && cs.limitchunk <= cs.chunknum {\n\t\tcs.done = true\n\t\treturn false\n\t}\n\n\tcs.chunknum++\n\n\ttruncate(cs.bdata)\n\n\tfor j := 0; j < cs.chunkSize; j++ {\n\n\t\t// Try to read a row, return false if done.\n\t\tvar rec []string\n\t\tvar err error\n\t\tif cs.firstrow != nil {\n\t\t\trec = cs.firstrow\n\t\t\tcs.firstrow = nil\n\t\t} else {\n\t\t\trec, err = cs.csvrdr.Read()\n\t\t\tif err == io.EOF {\n\t\t\t\tcs.done = true\n\t\t\t\treturn ilen(cs.bdata[0]) > 0\n\t\t\t} else if err != nil {\n\t\t\t\tif cs.skipErrors {\n\t\t\t\t\tos.Stderr.WriteString(fmt.Sprintf(\"%v\\n\", err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tcs.nobs++\n\n\t\tfor pos, typ := range cs.types {\n\t\t\tfpos := cs.filepos[pos]\n\t\t\tswitch typ.Type {\n\t\t\tcase String:\n\t\t\t\tx := rec[fpos]\n\t\t\t\tu := cs.bdata[pos].([]string)\n\t\t\t\tcs.bdata[pos] = append(u, string(x))\n\t\t\tcase Time:\n\t\t\t\tx := cs.parseTime(rec[fpos])\n\t\t\t\tu := cs.bdata[pos].([]time.Time)\n\t\t\t\tcs.bdata[pos] = append(u, time.Time(x))\n\t\t\tcase Uint8:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]uint8)\n\t\t\t\tcs.bdata[pos] = append(u, uint8(x))\n\t\t\tcase Uint16:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]uint16)\n\t\t\t\tcs.bdata[pos] = append(u, uint16(x))\n\t\t\tcase Uint32:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]uint32)\n\t\t\t\tcs.bdata[pos] = append(u, uint32(x))\n\t\t\tcase Uint64:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]uint64)\n\t\t\t\tcs.bdata[pos] = append(u, uint64(x))\n\t\t\tcase Int8:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]int8)\n\t\t\t\tcs.bdata[pos] = append(u, int8(x))\n\t\t\tcase Int16:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]int16)\n\t\t\t\tcs.bdata[pos] = append(u, int16(x))\n\t\t\tcase Int32:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]int32)\n\t\t\t\tcs.bdata[pos] = append(u, int32(x))\n\t\t\tcase Int64:\n\t\t\t\tx, err := strconv.Atoi(rec[fpos])\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]int64)\n\t\t\t\tcs.bdata[pos] = append(u, int64(x))\n\t\t\tcase Float32:\n\t\t\t\tx, err := strconv.ParseFloat(rec[fpos], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tx = math.NaN()\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]float32)\n\t\t\t\tcs.bdata[pos] = append(u, float32(x))\n\t\t\tcase Float64:\n\t\t\t\tx, err := strconv.ParseFloat(rec[fpos], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tx = math.NaN()\n\t\t\t\t}\n\t\t\t\tu := cs.bdata[pos].([]float64)\n\t\t\t\tcs.bdata[pos] = append(u, float64(x))\n\t\t\tdefault:\n\t\t\t\tpanic(\"unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (qr *queryResult) Next(dest []driver.Value) error {\n\tif qr.pos >= qr.numRow() {\n\t\tif qr.attributes.LastPacket() {\n\t\t\treturn io.EOF\n\t\t}\n\t\tif err := qr.conn._fetchNext(context.Background(), qr); err != nil {\n\t\t\tqr.lastErr = err //fieldValues and attrs are nil\n\t\t\treturn err\n\t\t}\n\t\tif qr.numRow() == 0 {\n\t\t\treturn io.EOF\n\t\t}\n\t\tqr.pos = 0\n\t}\n\n\tqr.copyRow(qr.pos, dest)\n\terr := qr.decodeErrors.RowError(qr.pos)\n\tqr.pos++\n\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(qr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (e *IndexReaderExecutor) Next() (*Row, error) {\n\tfor {\n\t\t// Get partial result.\n\t\tif e.partialResult == nil {\n\t\t\tvar err error\n\t\t\te.partialResult, err = e.result.Next()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif e.partialResult == nil {\n\t\t\t\t// Finished.\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\t// Get a row from partial result.\n\t\th, rowData, err := e.partialResult.Next()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif rowData == nil {\n\t\t\t// Finish the current partial result and get the next one.\n\t\t\te.partialResult.Close()\n\t\t\te.partialResult = nil\n\t\t\tcontinue\n\t\t}\n\t\tvalues := make([]types.Datum, e.schema.Len())\n\t\terr = codec.SetRawValues(rowData, values)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\terr = decodeRawValues(values, e.schema, e.ctx.GetSessionVars().GetTimeZone())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn resultRowToRow(e.table, h, values, e.asName), nil\n\t}\n}", "func (qr *queryResult) Next(dest []driver.Value) error {\n\tif qr.pos >= qr.numRow() {\n\t\tif qr.attributes.LastPacket() {\n\t\t\treturn io.EOF\n\t\t}\n\t\tif err := qr.conn._fetchNext(qr); err != nil {\n\t\t\tqr.lastErr = err //fieldValues and attrs are nil\n\t\t\treturn err\n\t\t}\n\t\tif qr.numRow() == 0 {\n\t\t\treturn io.EOF\n\t\t}\n\t\tqr.pos = 0\n\t}\n\n\tqr.copyRow(qr.pos, dest)\n\terr := qr.decodeErrors.RowError(qr.pos)\n\tqr.pos++\n\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(qr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (qi *QueryIterator) Next() ([]interface{}, error) {\n\tqi.processedRows++\n\tqi.rowsIndex++\n\tif int(qi.rowsIndex) >= len(qi.Rows) {\n\t\terr := qi.fetchPage()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\trow := qi.Rows[qi.rowsIndex]\n\tfields := qi.schema.Fields\n\tvar values = make([]interface{}, 0)\n\tfor i, cell := range row.F {\n\t\tvalue := toValue(cell.V, fields[i])\n\t\tvalues = append(values, value)\n\t}\n\treturn values, nil\n}", "func (reader *BoltRowReader) Read() (string, error) {\n\tdata, _, err := reader.rows.NextNeo()\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\tif reader.rowsRead == 0 {\n\t\t\t\treturn \"\", observation.ErrNoInstanceFound\n\t\t\t} else if reader.rowsRead == 1 {\n\t\t\t\treturn \"\", observation.ErrNoResultsFound\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tif len(data) < 1 {\n\t\treturn \"\", observation.ErrNoDataReturned\n\t}\n\n\tif csvRow, ok := data[0].(string); ok {\n\t\treader.rowsRead++\n\t\treturn csvRow + \"\\n\", nil\n\t}\n\n\treturn \"\", observation.ErrUnrecognisedType\n}", "func (f *filtererProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor f.State == execinfra.StateRunning {\n\t\trow, meta := f.input.Next()\n\n\t\tif meta != nil {\n\t\t\tif meta.Err != nil {\n\t\t\t\tf.MoveToDraining(nil /* err */)\n\t\t\t}\n\t\t\treturn nil, meta\n\t\t}\n\t\tif row == nil {\n\t\t\tf.MoveToDraining(nil /* err */)\n\t\t\tbreak\n\t\t}\n\n\t\t// Perform the actual filtering.\n\t\tpasses, err := f.filter.EvalFilter(row)\n\t\tif err != nil {\n\t\t\tf.MoveToDraining(err)\n\t\t\tbreak\n\t\t}\n\t\tif passes {\n\t\t\tif outRow := f.ProcessRowHelper(row); outRow != nil {\n\t\t\t\treturn outRow, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, f.DrainHelper()\n}", "func (rows *Rows) Next() ([]string, error) {\r\n\tif rows.status == false {\r\n\t\treturn nil, errors.New(\"Cursor not opened.\")\r\n\t}\r\n\r\n\t// start cursor\r\n\trows.dbi.createOperation(\"DB_FETCH_RECORD\")\r\n\trows.dbi.data.curId = rows.Curid\r\n\t// data\r\n\trows.dbi.data.commPrepare()\r\n\t// communicate\r\n\tif rows.dbi.data.comm() == false {\r\n\t\trows.dbi.Close()\r\n\t\trows.status = false\r\n\t\treturn nil, errors.New(rows.dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\trows.dbi.data.commParse()\r\n\trows.dbi.parseError()\r\n\r\n\tif rows.dbi.Sqlcode < 0 {\r\n\t\treturn nil, errors.New(rows.dbi.Sqlerrm)\r\n\t}\r\n\r\n\treturn rows.dbi.data.outVar, nil\r\n}", "func (r rowsRes) Next(dest []driver.Value) error {\n\terr := r.my.ScanRow(r.row)\n\tif err != nil {\n\t\treturn errFilter(err)\n\t}\n\tfor i, col := range r.row {\n\t\tif col == nil {\n\t\t\tdest[i] = nil\n\t\t\tcontinue\n\t\t}\n\t\tswitch c := col.(type) {\n\t\tcase time.Time:\n\t\t\tdest[i] = c\n\t\t\tcontinue\n\t\tcase mysql.Timestamp:\n\t\t\tdest[i] = c.Time\n\t\t\tcontinue\n\t\tcase mysql.Date:\n\t\t\tdest[i] = c.Localtime()\n\t\t\tcontinue\n\t\t}\n\t\tv := reflect.ValueOf(col)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t// this contains time.Duration to\n\t\t\tdest[i] = v.Int()\n\t\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\tu := v.Uint()\n\t\t\tif u > math.MaxInt64 {\n\t\t\t\tpanic(\"Value to large for int64 type\")\n\t\t\t}\n\t\t\tdest[i] = int64(u)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tdest[i] = v.Float()\n\t\tcase reflect.Slice:\n\t\t\tif v.Type().Elem().Kind() == reflect.Uint8 {\n\t\t\t\tdest[i] = v.Interface().([]byte)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tpanic(fmt.Sprint(\"Unknown type of column: \", v.Type()))\n\t\t}\n\t}\n\treturn nil\n}", "func (itr *doltTableRowIter) Next() (sql.Row, error) {\n\treturn itr.reader.ReadSqlRow(itr.ctx)\n}", "func (tr *tableReader) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor tr.State == execinfra.StateRunning {\n\t\t// Check if it is time to emit a progress update.\n\t\tif tr.rowsRead >= tableReaderProgressFrequency {\n\t\t\tmeta := execinfrapb.GetProducerMeta()\n\t\t\tmeta.Metrics = execinfrapb.GetMetricsMeta()\n\t\t\tmeta.Metrics.RowsRead = tr.rowsRead\n\t\t\ttr.rowsRead = 0\n\t\t\treturn nil, meta\n\t\t}\n\n\t\trow, _, _, err := tr.fetcher.NextRow(tr.Ctx)\n\t\tif row == nil || err != nil {\n\t\t\ttr.MoveToDraining(err)\n\t\t\tbreak\n\t\t}\n\n\t\t// When tracing is enabled, number of rows read is tracked twice (once\n\t\t// here, and once through InputStats). This is done so that non-tracing\n\t\t// case can avoid tracking of the stall time which gives a noticeable\n\t\t// performance hit.\n\t\ttr.rowsRead++\n\t\tif outRow := tr.ProcessRowHelper(row); outRow != nil {\n\t\t\treturn outRow, nil\n\t\t}\n\t}\n\treturn nil, tr.DrainHelper()\n}", "func (s *orderedSynchronizer) NextRow() (sqlbase.EncDatumRow, error) {\n\tif !s.initialized {\n\t\tif err := s.initHeap(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.initialized = true\n\t} else {\n\t\t// Last row returned was from the source at the root of the heap; get\n\t\t// the next row for that source.\n\t\tif err := s.advanceRoot(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(s.heap) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn s.sources[s.heap[0]].row, nil\n}", "func (r *sqlRows) Next(values []driver.Value) error {\n\terr := r.rows.Next(values)\n\tif err == driver.ErrBadConn {\n\t\tr.conn.Close()\n\t}\n\tfor i, v := range values {\n\t\tif b, ok := v.([]byte); ok {\n\t\t\tvalues[i] = append([]byte{}, b...)\n\t\t}\n\t}\n\treturn err\n}", "func (r *result) Next(dest []driver.Value) error {\n\tif r.data == nil {\n\t\tif err := r.readNext(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor i := 0; i < len(r.columns); i++ {\n\t\tkey := r.columns[i]\n\t\tval := r.data[key]\n\t\tdest[i] = val\n\t}\n\tr.data = nil\n\tr.offset++\n\treturn nil\n}", "func (ps *projectSetProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor ps.State == execinfra.StateRunning {\n\t\tif err := ps.cancelChecker.Check(); err != nil {\n\t\t\tps.MoveToDraining(err)\n\t\t\treturn nil, ps.DrainHelper()\n\t\t}\n\n\t\t// Start of a new row of input?\n\t\tif !ps.inputRowReady {\n\t\t\t// Read the row from the source.\n\t\t\trow, meta, err := ps.nextInputRow()\n\t\t\tif meta != nil {\n\t\t\t\tif meta.Err != nil {\n\t\t\t\t\tps.MoveToDraining(nil /* err */)\n\t\t\t\t}\n\t\t\t\treturn nil, meta\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tps.MoveToDraining(err)\n\t\t\t\treturn nil, ps.DrainHelper()\n\t\t\t}\n\t\t\tif row == nil {\n\t\t\t\tps.MoveToDraining(nil /* err */)\n\t\t\t\treturn nil, ps.DrainHelper()\n\t\t\t}\n\n\t\t\t// Keep the values for later.\n\t\t\tcopy(ps.rowBuffer, row)\n\t\t\tps.inputRowReady = true\n\t\t}\n\n\t\t// Try to find some data on the generator side.\n\t\tnewValAvail, err := ps.nextGeneratorValues()\n\t\tif err != nil {\n\t\t\tps.MoveToDraining(err)\n\t\t\treturn nil, ps.DrainHelper()\n\t\t}\n\t\tif newValAvail {\n\t\t\tif outRow := ps.ProcessRowHelper(ps.rowBuffer); outRow != nil {\n\t\t\t\treturn outRow, nil\n\t\t\t}\n\t\t} else {\n\t\t\t// The current batch of SRF values was exhausted. Advance\n\t\t\t// to the next input row.\n\t\t\tps.inputRowReady = false\n\t\t}\n\t}\n\treturn nil, ps.DrainHelper()\n}", "func (r *Recordset) Next() (row *ast.Row, err error) {\n\tif r.cursor == len(r.rows) {\n\t\treturn\n\t}\n\trow = &ast.Row{Data: r.rows[r.cursor]}\n\tr.cursor++\n\treturn\n}", "func (r *Reader) ReadRow() ([]string, error) {\n\tvar result []string\n\tfor {\n\t\tc, b, e := r.parseCell()\n\t\tif e != nil {\n\t\t\tif e == io.EOF && len(result) > 0 {\n\t\t\t\tresult = append(result, c)\n\t\t\t}\n\t\t\treturn result, e\n\t\t}\n\t\tresult = append(result, c)\n\t\tif b == 0 {\n\t\t\tbreak\n\t\t}\n\t\t// Line endings may be '\\r\\n', so eat '\\r'.\n\t\tif b == '\\r' {\n\t\t\tb, e = r.br.ReadByte()\n\t\t\tif e != nil {\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\t\tif b == r.Config.FieldDelim {\n\t\t\tcontinue\n\t\t} else if b == '\\n' {\n\t\t\tbreak\n\t\t} else {\n\t\t\treturn nil, errors.New(\"expected , got \" + string(int(b)))\n\t\t}\n\t}\n\treturn result, nil\n}", "func nextValue(data []byte) (offset int) {\n\tfor true {\n\t\tif len(data) == offset {\n\t\t\treturn -1\n\t\t}\n\n\t\tif data[offset] != ' ' && data[offset] != '\\n' && data[offset] != ',' {\n\t\t\treturn\n\t\t}\n\n\t\toffset++\n\t}\n\n\treturn -1\n}", "func CursorToNextRow() string {\n\tout := \"\"\n\tout += fmt.Sprint(cursorDown(1))\n\tout += fmt.Sprint(cursorLeft(2))\n\n\treturn out\n}", "func (rb *readerBase) nextRow() (sqlbase.EncDatumRow, error) {\n\tfor {\n\t\tfetcherRow, err := rb.fetcher.NextRow()\n\t\tif err != nil || fetcherRow == nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// TODO(radu): we are defeating the purpose of EncDatum here - we\n\t\t// should modify RowFetcher to return EncDatums directly and avoid\n\t\t// the cost of decoding/reencoding.\n\t\tfor i := range fetcherRow {\n\t\t\tif fetcherRow[i] != nil {\n\t\t\t\trb.row[i].SetDatum(rb.desc.Columns[i].Type.Kind, fetcherRow[i])\n\t\t\t}\n\t\t}\n\t\tpassesFilter, err := rb.filter.evalFilter(rb.row)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif passesFilter {\n\t\t\tbreak\n\t\t}\n\t}\n\toutRow := rb.rowAlloc.AllocRow(len(rb.outputCols))\n\tfor i, col := range rb.outputCols {\n\t\toutRow[i] = rb.row[col]\n\t}\n\treturn outRow, nil\n}", "func (tr TxnRow) Next() string {\n\tvar b [12]byte\n\tbinary.LittleEndian.PutUint64(b[:8], tr.Round)\n\tbinary.LittleEndian.PutUint32(b[8:], uint32(tr.Intra))\n\treturn base64.URLEncoding.EncodeToString(b[:])\n}", "func (it *RowIterator) Next() (*channelpb.Row, error) {\n\tvar item *channelpb.Row\n\tif err := it.nextFunc(); err != nil {\n\t\treturn item, err\n\t}\n\titem = it.items[0]\n\tit.items = it.items[1:]\n\treturn item, nil\n}", "func (r *Rows) Next(dest []driver.Value) error {\nagain:\n\trow, err := r.rows.Next(r.ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(row) == 0 {\n\t\treturn nil\n\t}\n\n\tif _, ok := row[0].(types.OkResult); ok {\n\t\t// skip OK results\n\t\tgoto again\n\t}\n\n\tfor i := range row {\n\t\tdest[i] = r.convert(i, row[i])\n\t}\n\treturn nil\n}", "func (itr *RoaringIterator) Next() (rowID, columnID uint64, eof bool) {\n\tv, eof := itr.itr.Next()\n\treturn v / SliceWidth, v % SliceWidth, eof\n}", "func (s *TransactionRows) NextRaw() ([]byte, bool) {\n\tsnap, err := s.iter.Next()\n\tif err != nil {\n\t\ts.lastError = err\n\t\treturn nil, false\n\t}\n\tdata := snap.Data()\n\tb, err := json.Marshal(data)\n\tif err == nil {\n\t\treturn b, true\n\t}\n\treturn nil, false\n}", "func (cr *callResult) Next(dest []driver.Value) error {\n\tif len(cr.fieldValues) == 0 || cr.eof {\n\t\treturn io.EOF\n\t}\n\n\tcopy(dest, cr.fieldValues)\n\terr := cr.decodeErrors.RowError(0)\n\tcr.eof = true\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(cr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (r *Reader) readRow() (err error) {\n r.line++\n\n r.row, err = r.r.ReadString(r.EOL)\n if err != nil && err != io.EOF {\n r.error(err)\n }\n\n return\n}", "func (cr *callResult) Next(dest []driver.Value) error {\n\tif len(cr.fieldValues) == 0 || cr.eof {\n\t\treturn io.EOF\n\t}\n\n\tcopy(dest, cr.fieldValues)\n\terr := cr.decodeErrors.RowError(0)\n\tcr.eof = true\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(cr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (i *FuncIterator) GetNext() (line []byte, input interface{}, err error) {\n\tnextIndex := atomic.AddInt64(&i.currentIndex, 1)\n\tvar nextValue string\n\tif i.endIndex != 0 && nextIndex > i.endIndex {\n\t\terr = io.EOF\n\t} else {\n\t\tnextValue, err = i.next(nextIndex)\n\t\tline = []byte(nextValue)\n\t}\n\treturn line, nextValue, err\n}", "func (e *HashSemiJoinExec) Next() (*Row, error) {\n\tif !e.prepared {\n\t\tif err := e.prepare(); err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tbigRow, match, err := e.fetchBigRow()\n\t\tif bigRow == nil || err != nil {\n\t\t\treturn bigRow, errors.Trace(err)\n\t\t}\n\t\tresultRows, err := e.doJoin(bigRow, match)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif len(resultRows) > 0 {\n\t\t\treturn resultRows[0], nil\n\t\t}\n\t}\n}", "func (e *IndexLookUpExecutor) Next() (*Row, error) {\n\tfor {\n\t\tif e.taskCurr == nil {\n\t\t\ttaskCurr, ok := <-e.taskChan\n\t\t\tif !ok {\n\t\t\t\treturn nil, e.tasksErr\n\t\t\t}\n\t\t\te.taskCurr = taskCurr\n\t\t}\n\t\trow, err := e.taskCurr.getRow()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif row != nil {\n\t\t\treturn row, nil\n\t\t}\n\t\te.taskCurr = nil\n\t}\n}", "func (iter *sliceIterator) next() (string, string, int) {\n\tif iter.position > len(iter.slice)-1 {\n\t\treturn \"\", \"\", -1\n\t}\n\tposition := iter.position\n\titer.position++\n\treturn iter.slice[position], strings.Trim(iter.slice[position], \" \\t\"), position\n}", "func (r *QueryResult) Next(dest []driver.Value) error {\n\tif len(r.page.Columns) == 0 {\n\t\tr.close()\n\t\treturn io.EOF\n\t}\n\trowCount := int32(len(r.page.Columns[0]))\n\tif r.index >= rowCount {\n\t\tif r.page.Last {\n\t\t\tr.close()\n\t\t\treturn io.EOF\n\t\t}\n\t\tctx, cancel := r.contextWithCancel()\n\t\tdefer cancel()\n\t\tif err := r.fetchNextPage(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor i := 0; i < len(r.page.Columns); i++ {\n\t\tcol := r.page.Columns[i]\n\t\t// TODO: find out the reason for requiring the following fix\n\t\tif len(col) <= int(r.index) {\n\t\t\tr.close()\n\t\t\treturn io.EOF\n\t\t}\n\t\tdest[i] = col[r.index]\n\t}\n\tr.index++\n\treturn nil\n}", "func nextDataLine(scanner *bufio.Scanner) string {\n\tfor scanner.Scan() {\n\t\tline := trimComment(scanner.Text())\n\t\tif line != \"\" {\n\t\t\treturn line\n\t\t}\n\t}\n\treturn \"\"\n}", "func (ps *projectSetProcessor) nextInputRow() (\n\trowenc.EncDatumRow,\n\t*execinfrapb.ProducerMetadata,\n\terror,\n) {\n\trow, meta := ps.input.Next()\n\tif row == nil {\n\t\treturn nil, meta, nil\n\t}\n\n\t// Initialize a round of SRF generators or scalar values.\n\tfor i := range ps.exprHelpers {\n\t\tif fn := ps.funcs[i]; fn != nil {\n\t\t\t// A set-generating function. Prepare its ValueGenerator.\n\n\t\t\t// Set ExprHelper.row so that we can use it as an IndexedVarContainer.\n\t\t\tps.exprHelpers[i].Row = row\n\n\t\t\tps.EvalCtx.IVarContainer = ps.exprHelpers[i]\n\t\t\tgen, err := fn.EvalArgsAndGetGenerator(ps.EvalCtx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tif gen == nil {\n\t\t\t\tgen = builtins.EmptyGenerator()\n\t\t\t}\n\t\t\tif err := gen.Start(ps.Ctx, ps.FlowCtx.Txn); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tps.gens[i] = gen\n\t\t}\n\t\tps.done[i] = false\n\t}\n\n\treturn row, nil, nil\n}", "func (dr *SeparatedReaders) Next() (err error) {\n\tdr.Count++\n\tif !dr.delimiterFound {\n\t\t// read and discard remains of section.\n\t\t// TODO could read directly any unused, reducing copying taking place\n\t\tbuf := make([]byte, bytes.MinRead)\n\t\tfor {\n\t\t\t_, err = dr.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tdr.delimiterFound = false\n\treturn\n}", "func getNextRecordSlice(rdr *bufio.Reader) ([]string, int64, string) {\n\tposn := maxPosn\n\tdata := emptyRecord\n\tvarid := \"\"\n\ttext, err := rdr.ReadString('\\n')\n\tif err == nil {\n\t\ttext = strings.TrimRight(text, \"\\n\")\n\t\tdata = strings.Split(text, \"\\t\")\n\t\tposn = int64(variant.GetPosn(data))\n\t\tvarid = variant.GetVarid(data)\n\t}\n\treturn data, posn, varid\n}", "func (s *server) Next() Data {\n\tpage := s.row / s.pageSize\n\tif page != s.currentPage {\n\t\ts.currentPage = page\n\t\ts.getPage(page)\n\t}\n\tif s.row > s.maxRow || s.data == nil {\n\t\treturn nil\n\t}\n\tif len(s.data) == 0 {\n\t\treturn nil\n\t}\n\tretval := s.data[s.row%s.pageSize].(map[string]interface{})\n\ts.row++\n\treturn retval\n}", "func (r sqlCursor) Next() map[string]interface{} {\n\tvar err error\n\n\tif r.rows.Next() {\n\t\tif err = r.rows.Scan(r.columnValueReceivers...); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tvalues := make(map[string]interface{}, len(r.columnReceivers))\n\t\tfor j, vr := range r.columnReceivers {\n\t\t\tvalues[r.columnNames[j]] = vr.Unpack(r.columnTypes[j])\n\t\t}\n\t\tif r.builder != nil {\n\t\t\tv2 := r.builder.unpackResult([]map[string]interface{}{values})\n\t\t\treturn v2[0]\n\t\t} else {\n\t\t\treturn values\n\t\t}\n\t} else {\n\t\tif err = r.rows.Err(); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (r *boltRows) NextNeo() ([]interface{}, map[string]interface{}, error) {\n\tif r.closed {\n\t\treturn nil, nil, errors.New(\"Rows are already closed\")\n\t}\n\n\tif !r.consumed {\n\t\tr.consumed = true\n\t\tif err := r.statement.conn.sendPullAll(); err != nil {\n\t\t\tr.finishedConsume = true\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\trespInt, err := r.statement.conn.consume()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tswitch resp := respInt.(type) {\n\tcase messages.SuccessMessage:\n\t\tlog.Infof(\"Got success message: %#v\", resp)\n\t\tr.finishedConsume = true\n\t\treturn nil, resp.Metadata, io.EOF\n\tcase messages.RecordMessage:\n\t\tlog.Infof(\"Got record message: %#v\", resp)\n\t\treturn resp.Fields, nil, nil\n\tdefault:\n\t\treturn nil, nil, errors.New(\"Unrecognized response type getting next query row: %#v\", resp)\n\t}\n}", "func (r *rows) Next(dest []driver.Value) (err error) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Next(%v): %v\", dest, err)\n\t\t}()\n\t}\n\trc := r.rc0\n\tif r.doStep {\n\t\tif rc, err = r.step(r.pstmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tr.doStep = true\n\n\tswitch rc {\n\tcase bin.XSQLITE_ROW:\n\t\tif g, e := len(dest), len(r.columns); g != e {\n\t\t\treturn fmt.Errorf(\"Next(): have %v destination values, expected %v\", g, e)\n\t\t}\n\n\t\tfor i := range dest {\n\t\t\tct, err := r.columnType(i)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch ct {\n\t\t\tcase bin.XSQLITE_INTEGER:\n\t\t\t\tv, err := r.columnInt64(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_FLOAT:\n\t\t\t\tv, err := r.columnDouble(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_TEXT:\n\t\t\t\tv, err := r.columnText(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_BLOB:\n\t\t\t\tv, err := r.columnBlob(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_NULL:\n\t\t\t\tdest[i] = nil\n\t\t\tdefault:\n\t\t\t\tpanic(\"internal error\")\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase bin.XSQLITE_DONE:\n\t\treturn io.EOF\n\tdefault:\n\t\treturn r.errstr(int32(rc))\n\t}\n}", "func (r *rows) Next(dest []driver.Value) error {\n\tif r.index >= len(r.rows) {\n\t\tif r.parent.offset < r.parent.total {\n\t\t\tif err := fetchNextPage(r.parent.conn, r.parent.jobid, r.parent.offset, r.parent.total, r.parent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tr.index = r.parent.rows.index\n\t\t\tr.rows = r.parent.rows.rows\n\t\t} else {\n\t\t\tr.rows = nil\n\t\t}\n\t}\n\tif len(dest) != len(r.parent.columns) {\n\t\treturn fmt.Errorf(\"invalid scan, expected %d arguments and received %d\", len(r.parent.columns), len(dest))\n\t}\n\tif r.rows == nil || len(r.rows) == 0 {\n\t\treturn sql.ErrNoRows\n\t}\n\ttherow := r.rows[r.index]\n\tfor i := 0; i < len(r.parent.columns); i++ {\n\t\tkey := r.parent.columns[i]\n\t\tval := therow[key]\n\t\tdest[i] = val\n\t}\n\tr.index++\n\treturn nil\n}", "func (r *boltRows) Next(dest []driver.Value) error {\n\tdata, _, err := r.NextNeo()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i, item := range data {\n\t\tswitch item := item.(type) {\n\t\tcase []interface{}, map[string]interface{}, graph.Node, graph.Path, graph.Relationship, graph.UnboundRelationship:\n\t\t\tdest[i], err = encoding.Marshal(item)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tdest[i], err = driver.DefaultParameterConverter.ConvertValue(item)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (e *ApplyJoinExec) Next() (*Row, error) {\n\tfor {\n\t\tif e.cursor < len(e.resultRows) {\n\t\t\trow := e.resultRows[e.cursor]\n\t\t\te.cursor++\n\t\t\treturn row, nil\n\t\t}\n\t\tbigRow, match, err := e.join.fetchBigRow()\n\t\tif bigRow == nil || err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tfor _, col := range e.outerSchema {\n\t\t\t*col.Data = bigRow.Data[col.Index]\n\t\t}\n\t\terr = e.join.prepare()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\te.resultRows, err = e.join.doJoin(bigRow, match)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\te.cursor = 0\n\t}\n}", "func (c *CSVInterpolator) rowToStartWith() int64 {\n\tif c.row == 1 {\n\t\treturn 1\n\t}\n\n\treturn c.row - 1\n}", "func (r *newSelectResult) NextRaw() ([]byte, error) {\n\tre := <-r.results\n\treturn re.result, errors.Trace(re.err)\n}", "func nextValue(data []byte, scan *scanner) (value, rest []byte, err error) {\n\tscan.reset()\n\tfor i, c := range data {\n\t\tv := scan.step(scan, c)\n\t\tif v >= scanEndObject {\n\t\t\tswitch v {\n\t\t\t// probe the scanner with a space to determine whether we will\n\t\t\t// get scanEnd on the next character. Otherwise, if the next character\n\t\t\t// is not a space, scanEndTop allocates a needless error.\n\t\t\tcase scanEndObject, scanEndArray:\n\t\t\t\tif scan.step(scan, ' ') == scanEnd {\n\t\t\t\t\treturn data[:i+1], data[i+1:], nil\n\t\t\t\t}\n\t\t\tcase scanError:\n\t\t\t\treturn nil, nil, scan.err\n\t\t\tcase scanEnd:\n\t\t\t\treturn data[:i], data[i:], nil\n\t\t\t}\n\t\t}\n\t}\n\tif scan.eof() == scanError {\n\t\treturn nil, nil, scan.err\n\t}\n\treturn data, nil, nil\n}", "func (rc *SQLiteRows) Next(dest []driver.Value) error {\n\tif rc.s.closed {\n\t\treturn io.EOF\n\t}\n\trc.s.mu.Lock()\n\tdefer rc.s.mu.Unlock()\n\trv := C.sqlite3_step(rc.s.s)\n\tif rv == C.SQLITE_DONE {\n\t\treturn io.EOF\n\t}\n\tif rv != C.SQLITE_ROW {\n\t\trv = C.sqlite3_reset(rc.s.s)\n\t\tif rv != C.SQLITE_OK {\n\t\t\treturn rc.s.c.lastError()\n\t\t}\n\t\treturn nil\n\t}\n\n\trc.declTypes()\n\n\tfor i := range dest {\n\t\tswitch C.sqlite3_column_type(rc.s.s, C.int(i)) {\n\t\tcase C.SQLITE_INTEGER:\n\t\t\tval := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))\n\t\t\tswitch rc.decltype[i] {\n\t\t\tcase columnTimestamp, columnDatetime, columnDate:\n\t\t\t\tvar t time.Time\n\t\t\t\t// Assume a millisecond unix timestamp if it's 13 digits -- too\n\t\t\t\t// large to be a reasonable timestamp in seconds.\n\t\t\t\tif val > 1e12 || val < -1e12 {\n\t\t\t\t\tval *= int64(time.Millisecond) // convert ms to nsec\n\t\t\t\t\tt = time.Unix(0, val)\n\t\t\t\t} else {\n\t\t\t\t\tt = time.Unix(val, 0)\n\t\t\t\t}\n\t\t\t\tt = t.UTC()\n\t\t\t\tif rc.s.c.tz != nil {\n\t\t\t\t\tt = t.In(rc.s.c.tz)\n\t\t\t\t}\n\t\t\t\tdest[i] = t\n\t\t\tcase \"boolean\":\n\t\t\t\tdest[i] = val > 0\n\t\t\tdefault:\n\t\t\t\tdest[i] = val\n\t\t\t}\n\t\tcase C.SQLITE_FLOAT:\n\t\t\tdest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))\n\t\tcase C.SQLITE_BLOB:\n\t\t\tp := C.sqlite3_column_blob(rc.s.s, C.int(i))\n\t\t\tif p == nil {\n\t\t\t\tdest[i] = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))\n\t\t\tswitch dest[i].(type) {\n\t\t\tdefault:\n\t\t\t\tslice := make([]byte, n)\n\t\t\t\tcopy(slice[:], (*[1 << 30]byte)(p)[0:n])\n\t\t\t\tdest[i] = slice\n\t\t\t}\n\t\tcase C.SQLITE_NULL:\n\t\t\tdest[i] = nil\n\t\tcase C.SQLITE_TEXT:\n\t\t\tvar err error\n\t\t\tvar timeVal time.Time\n\n\t\t\tn := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))\n\t\t\ts := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))\n\n\t\t\tswitch rc.decltype[i] {\n\t\t\tcase columnTimestamp, columnDatetime, columnDate:\n\t\t\t\tvar t time.Time\n\t\t\t\ts = strings.TrimSuffix(s, \"Z\")\n\t\t\t\tfor _, format := range SQLiteTimestampFormats {\n\t\t\t\t\tif timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {\n\t\t\t\t\t\tt = timeVal\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\t// The column is a time value, so return the zero time on parse failure.\n\t\t\t\t\tt = time.Time{}\n\t\t\t\t}\n\t\t\t\tif rc.s.c.tz != nil {\n\t\t\t\t\tt = t.In(rc.s.c.tz)\n\t\t\t\t}\n\t\t\t\tdest[i] = t\n\t\t\tdefault:\n\t\t\t\tdest[i] = []byte(s)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}", "func (io *Io) Next() string {\n\tif io.nextToken >= len(io.tokens) {\n\t\tline := io.NextLine()\n\t\tio.tokens = strings.Fields(line)\n\t\tio.nextToken = 0\n\t}\n\n\tres := io.tokens[io.nextToken]\n\tio.nextToken++\n\treturn res\n}", "func (c *FunctionSchema) NextRow() bool {\n\tif c.rowNum >= len(c.rows)-1 {\n\t\tc.done = true\n\t}\n\tc.rowNum = c.rowNum + 1\n\treturn !c.done\n}", "func (mts *metadataTestSender) Next() (sqlbase.EncDatumRow, *ProducerMetadata) {\n\tmts.maybeStart(\"metadataTestSender\", \"\" /* logTag */)\n\n\tif mts.sendRowNumMeta {\n\t\tmts.sendRowNumMeta = false\n\t\tmts.rowNumCnt++\n\t\treturn nil, &ProducerMetadata{\n\t\t\tRowNum: &RemoteProducerMetadata_RowNum{\n\t\t\t\tRowNum: mts.rowNumCnt,\n\t\t\t\tSenderID: mts.id,\n\t\t\t\tLastMsg: false,\n\t\t\t},\n\t\t}\n\t}\n\n\tfor {\n\t\trow, meta := mts.input.Next()\n\t\tif meta != nil {\n\t\t\treturn nil, meta\n\t\t}\n\t\tif mts.closed || row == nil {\n\t\t\treturn nil, mts.producerMeta(nil /* err */)\n\t\t}\n\n\t\toutRow, status, err := mts.out.ProcessRow(mts.ctx, row)\n\t\tif err != nil {\n\t\t\treturn nil, mts.producerMeta(err)\n\t\t}\n\t\tswitch status {\n\t\tcase NeedMoreRows:\n\t\t\tif outRow == nil && err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase DrainRequested:\n\t\t\tmts.input.ConsumerDone()\n\t\t\tcontinue\n\t\t}\n\t\tmts.sendRowNumMeta = true\n\t\treturn outRow, nil\n\t}\n}", "func (e *HashJoinExec) Next() (*Row, error) {\n\tif !e.prepared {\n\t\tif err := e.prepare(); err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t}\n\ttxnCtx := e.ctx.GoCtx()\n\tif e.cursor >= len(e.rows) {\n\t\tvar result *execResult\n\t\tselect {\n\t\tcase tmp, ok := <-e.resultCh:\n\t\t\tif !ok {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\tresult = tmp\n\t\t\tif result.err != nil {\n\t\t\t\te.finished.Store(true)\n\t\t\t\treturn nil, errors.Trace(result.err)\n\t\t\t}\n\t\tcase <-txnCtx.Done():\n\t\t\treturn nil, nil\n\t\t}\n\t\tif len(result.rows) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\te.rows = result.rows\n\t\te.cursor = 0\n\t}\n\trow := e.rows[e.cursor]\n\te.cursor++\n\treturn row, nil\n}", "func readRow(scanner *bufio.Scanner, k int) row {\n\tif !scanner.Scan() { panic(\"missing imput\") }\n\tvar result row = make([]string, k)\n\ti := 0\n\tbuilder := &strings.Builder{}\n\tfor _, c := range scanner.Text() {\n\t\tif c == '\\t' {\n\t\t\tresult[i] = builder.String()\n\t\t\tbuilder.Reset() \n\t\t\ti++ \n\t\t\tif i >= k { panic(\"too much columns in input\") }\n\t\t} else {\n\t\t\tbuilder.WriteRune(c)\n\t\t}\n\t}\n\treturn result\n}", "func (r *Row) Next() bool {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif r.s == nil {\n\t\treturn false\n\t}\n\tr.raw, r.err = r.s.DecodeBytes()\n\tr.s = nil\n\n\treturn r.err == nil && r.raw != nil\n}", "func (m *MssqlRowReader) Next() bool {\n\tif m.NextFunc != nil {\n\t\treturn m.NextFunc()\n\t}\n\tnext := m.Cursor.Next()\n\tif next {\n\t\tcolumnNames, err := m.Cursor.Columns()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tm.columns = make([]interface{}, len(columnNames))\n\t\tcolumnPointers := make([]interface{}, len(columnNames))\n\t\tfor i := 0; i < len(columnNames); i++ {\n\t\t\tcolumnPointers[i] = &m.columns[i]\n\t\t}\n\t\tif err := m.Cursor.Scan(columnPointers...); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn next\n}", "func (r *filter) Next(dest []driver.Value) error {\n\trow := make([]driver.Value, len(dest))\n\tfor {\n\t\terr := r.input.Next(row)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif r.apply(row) {\n\t\t\tfor i, v := range row {\n\t\t\t\tdest[i] = v\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (result *Result) Next(txn Transaction) ([]byte, error) {\n\tif !result.HasNext() {\n\t\treturn nil, errors.New(\"no more values\")\n\t}\n\tif result.index == len(result.pageValues) {\n\t\terr := result.getNextPage()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result.Next(txn)\n\t}\n\tionBinary := result.pageValues[result.index].IonBinary\n\tresult.index++\n\treturn ionBinary, nil\n}", "func (h *HandlersApp01sqVendor) RowNext(w http.ResponseWriter, r *http.Request) {\n\tvar rcd App01sqVendor.App01sqVendor\n\tvar err error\n\tvar i int\n\tvar key string\n\n\tlog.Printf(\"hndlrVendor.RowNext(%s)\\n\", r.Method)\n\tlog.Printf(\"\\tURL: %q\\n\", r.URL)\n\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Get the prior key(s).\n\ti = 0\n\tkey = r.FormValue(fmt.Sprintf(\"key%d\", i))\n\trcd.Id, _ = strconv.ParseInt(key, 0, 64)\n\n\ti++\n\n\t// Get the next row and display it.\n\terr = h.db.RowNext(&rcd)\n\tif err != nil {\n\n\t\tlog.Printf(\"...end hndlrVendor.RowNext(Error:400) - No Key\\n\")\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\th.RowDisplay(w, &rcd, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.RowNext()\\n\")\n\n}", "func (o TableExternalDataConfigurationCsvOptionsPtrOutput) SkipLeadingRows() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TableExternalDataConfigurationCsvOptions) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SkipLeadingRows\n\t}).(pulumi.IntPtrOutput)\n}", "func (r *Result) GetRowN() []Nullable {\n\trowBuf := r.val.buffer\n\tret := make([]Nullable, len(rowBuf))\n\tfor i := range rowBuf {\n\t\tret[i] = rowBuf[i]\n\t}\n\treturn ret\n}", "func (itr *SliceIterator) Next() (rowID, columnID uint64, eof bool) {\n\tif itr.i >= itr.n {\n\t\treturn 0, 0, true\n\t}\n\n\trowID = itr.rowIDs[itr.i]\n\tcolumnID = itr.columnIDs[itr.i]\n\n\titr.i++\n\treturn rowID, columnID, false\n}", "func (io *Io) Next() string {\n\tfor io.nextToken >= len(io.tokens) {\n\t\tline := io.NextLine()\n\t\tio.tokens = strings.Fields(line)\n\t\tio.nextToken = 0\n\t}\n\tr := io.tokens[io.nextToken]\n\tio.nextToken++\n\treturn r\n}", "func (s *QualReader) Next() (int, QualSeq) {\n defer func(){s.index+=1}()\n\n return s.index, QualSeq{string(s.next[0][1:]), string(s.next[1])}\n}", "func parseRows(z *html.Tokenizer) string {\n\tfor {\n\t\ttt := z.Next()\n\t\tswitch tt {\n\t\tcase html.ErrorToken:\n\t\t\t// End of the document, we're done\n\t\t\treturn \"\"\n\t\tcase html.StartTagToken:\n\t\t\tt := z.Token()\n\t\t\tif t.Data == \"td\" {\n\t\t\t\tfor _, a := range t.Attr {\n\t\t\t\t\tif a.Val == \"rich-table-cell rich-table-cell-last\" {\n\t\t\t\t\t\tz.Next()\n\t\t\t\t\t\tt = z.Token()\n\t\t\t\t\t\treturn t.Data\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (o TableExternalDataConfigurationCsvOptionsOutput) SkipLeadingRows() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v TableExternalDataConfigurationCsvOptions) *int { return v.SkipLeadingRows }).(pulumi.IntPtrOutput)\n}", "func (r *Reader) NextRow() bool {\n\tif r.cols == nil || r.err != nil {\n\t\treturn false\n\t}\n\trow, err := r.readRow()\n\tr.row = row\n\tif row == nil {\n\t\tr.err = err\n\t\tr.cols = nil\n\t\treturn false\n\t}\n\treturn true\n}", "func (c *ViewSchema) NextRow() bool {\n\tif c.rowNum >= len(c.rows)-1 {\n\t\tc.done = true\n\t}\n\tc.rowNum = c.rowNum + 1\n\treturn !c.done\n}", "func (it *NZIter) Next() (uint32, uint32, bool) {\n\tif it.Done() {\n\t\treturn 0, 0, true\n\t}\n\trowLen := uint32(it.rowEnd - it.rowStart)\n\tfor rowLen == 0 {\n\t\tif it.advance() { // we've hit the end.\n\t\t\treturn 0, 0, true\n\t\t}\n\t\trowLen = uint32(it.rowEnd - it.rowStart)\n\t}\n\n\tr := it.rowIndex\n\tindex := it.rowStart + uint64(it.colIndex)\n\tc := it.g.Indices[index]\n\n\tit.n++\n\treturn r, c, it.advance()\n}", "func (result *BufferedResult) Next() ([]byte, error) {\n\tif !result.HasNext() {\n\t\treturn nil, errors.New(\"no more values\")\n\t}\n\tionBinary := result.values[result.index]\n\tresult.index++\n\treturn ionBinary, nil\n}", "func MiddleRow(rows [][]string, decimalPlaces int) []string {\n\tmiddleRow := rows[1]\n\tresult := make([]string, len(middleRow))\n\n\tfor i, val := range middleRow {\n\t\tif isNaN(val) {\n\t\t\tresult[i] = averageOf(\n\t\t\t\tdecimalPlaces,\n\t\t\t\tvalueAt(rows[0], i),\n\t\t\t\tvalueAt(rows[2], i),\n\t\t\t\tvalueLeftOf(middleRow, i),\n\t\t\t\tvalueRightOf(middleRow, i),\n\t\t\t)\n\t\t} else {\n\t\t\tresult[i] = val\n\t\t}\n\t}\n\n\treturn result\n}", "func NextLine() string {\n\tsc.Scan()\n\treturn sc.Text()\n}", "func loadOneSiteCSVRow(csvHeadersIndex map[string]int, data []string) (bool, CSVRow) {\n\tcsvRow := reflect.New(reflect.TypeOf(CSVRow{}))\n\trowLoaded := false\n\n\tfor header, index := range csvHeadersIndex {\n\t\tvalue := strings.TrimSpace(data[index])\n\t\tcsvRow.Elem().FieldByName(header).Set(reflect.ValueOf(value))\n\t}\n\n\t// if blank data has not been passed then only need to return true\n\tif (CSVRow{}) != csvRow.Elem().Interface().(CSVRow) {\n\t\trowLoaded = true\n\t}\n\n\treturn rowLoaded, csvRow.Elem().Interface().(CSVRow)\n}", "func (j *jsonTableRowIter) NextSibling() bool {\n\tfor i := j.currSib; i < len(j.cols); i++ {\n\t\tif !j.cols[i].finished && len(j.cols[i].cols) != 0 {\n\t\t\tj.currSib = i\n\t\t\treturn false\n\t\t}\n\t}\n\tj.currSib = 0\n\tfor i := 0; i < len(j.cols); i++ {\n\t\tif len(j.cols[i].cols) != 0 {\n\t\t\tj.currSib = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn true\n}", "func nextValue(slice []string) (v string, newSlice []string) {\n\n\tif len(slice) == 0 {\n\t\tv, newSlice = \"\", make([]string, 0)\n\t\treturn\n\t}\n\n\tv = slice[0]\n\n\tif len(slice) > 1 {\n\t\tnewSlice = slice[1:]\n\t} else {\n\t\tnewSlice = make([]string, 0)\n\t}\n\n\treturn\n}", "func (plr *PredictionLogReader) Next() error {\n\treturn plr.tfRecordReader.Next()\n}", "func (r *boltRows) NextPipeline() ([]interface{}, map[string]interface{}, PipelineRows, error) {\n\tif r.closed {\n\t\treturn nil, nil, nil, errors.New(\"Rows are already closed\")\n\t}\n\n\trespInt, err := r.statement.conn.consume()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tswitch resp := respInt.(type) {\n\tcase messages.SuccessMessage:\n\t\tlog.Infof(\"Got success message: %#v\", resp)\n\n\t\tif r.pipelineIndex == len(r.statement.queries)-1 {\n\t\t\tr.finishedConsume = true\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\tsuccessResp, err := r.statement.conn.consume()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, nil, nil, errors.Wrap(err, \"An error occurred getting next set of rows from pipeline command: %#v\", successResp)\n\t\t}\n\n\t\tsuccess, ok := successResp.(messages.SuccessMessage)\n\t\tif !ok {\n\t\t\treturn nil, nil, nil, errors.New(\"Unexpected response getting next set of rows from pipeline command: %#v\", successResp)\n\t\t}\n\n\t\tr.statement.rows = newPipelineRows(r.statement, success.Metadata, r.pipelineIndex+1)\n\t\tr.statement.rows.closeStatement = r.closeStatement\n\t\treturn nil, success.Metadata, r.statement.rows, nil\n\n\tcase messages.RecordMessage:\n\t\tlog.Infof(\"Got record message: %#v\", resp)\n\t\treturn resp.Fields, nil, nil, nil\n\tdefault:\n\t\treturn nil, nil, nil, errors.New(\"Unrecognized response type getting next pipeline row: %#v\", resp)\n\t}\n}", "func (da *DataFrame) Next() bool {\n\n\tda.chunk++\n\tif da.chunk <= len(da.data[0]) {\n\t\treturn true\n\t}\n\tda.done = true\n\treturn false\n}", "func (s *TransactionRows) Next(dst interface{}) (bool, error) {\n\tsnap, err := s.iter.Next()\n\tif err != nil {\n\t\ts.lastError = err\n\t\treturn false, err\n\t}\n\terr = snap.DataTo(&dst)\n\treturn true, err\n}", "func (it *BytesScanner) Next() (result []byte) {\n\tif it.emitEmptySlice {\n\t\tit.emitEmptySlice = false\n\t\tresult = make([]byte, 0)\n\t\treturn result\n\t}\n\n\tscannerIndex := it.index\n\tseparatorIndex := bytes.IndexByte(it.source[scannerIndex:], it.separator)\n\tif separatorIndex < 0 {\n\t\tresult = it.source[scannerIndex:]\n\t\tit.index = len(it.source)\n\t} else {\n\t\tseparatorIndex += scannerIndex\n\t\tresult = it.source[scannerIndex:separatorIndex]\n\t\tif separatorIndex == len(it.source)-1 {\n\t\t\tit.emitEmptySlice = true\n\t\t}\n\t\tit.index = separatorIndex + 1\n\t}\n\treturn result\n}", "func (oq *outputQueue) getEmptyRow() ([]interface{}, error) {\n\tif oq.rowIdx >= oq.length {\n\t\tif err := oq.flush(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trow := oq.mrs.Data[oq.rowIdx]\n\toq.rowIdx++\n\treturn row, nil\n}", "func (i *blockIter) Next() (sql.Row, error) {\n\treturn i.internalIter.Next()\n}", "func (l *LocalMapper) Next() (seriesKey string, timestamp int64, value interface{}) {\n\tfor {\n\t\t// if it's a raw query and we've hit the limit of the number of points to read in\n\t\t// for either this chunk or for the absolute query, bail\n\t\tif l.isRaw && (l.limit == 0 || l.perIntervalLimit == 0) {\n\t\t\treturn \"\", int64(0), nil\n\t\t}\n\n\t\t// find the minimum timestamp\n\t\tmin := -1\n\t\tminKey := int64(math.MaxInt64)\n\t\tfor i, k := range l.keyBuffer {\n\t\t\tif k != 0 && k <= l.tmax && k < minKey && k >= l.tmin {\n\t\t\t\tmin = i\n\t\t\t\tminKey = k\n\t\t\t}\n\t\t}\n\n\t\t// return if there is no more data in this group by interval\n\t\tif min == -1 {\n\t\t\treturn \"\", 0, nil\n\t\t}\n\n\t\t// set the current timestamp and seriesID\n\t\ttimestamp = l.keyBuffer[min]\n\t\tseriesKey = l.seriesKeys[min]\n\n\t\t// decode either the value, or values we need. Also filter if necessary\n\t\tvar value interface{}\n\t\tvar err error\n\t\tif l.isRaw && len(l.selectFields) > 1 {\n\t\t\tif fieldsWithNames, err := l.decoder.DecodeFieldsWithNames(l.valueBuffer[min]); err == nil {\n\t\t\t\tvalue = fieldsWithNames\n\n\t\t\t\t// if there's a where clause, make sure we don't need to filter this value\n\t\t\t\tif l.filters[min] != nil {\n\t\t\t\t\tif !matchesWhere(l.filters[min], fieldsWithNames) {\n\t\t\t\t\t\tvalue = nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tvalue, err = l.decoder.DecodeByID(l.fieldID, l.valueBuffer[min])\n\n\t\t\t// if there's a where clase, see if we need to filter\n\t\t\tif l.filters[min] != nil {\n\t\t\t\t// see if the where is only on this field or on one or more other fields. if the latter, we'll have to decode everything\n\t\t\t\tif len(l.whereFields) == 1 && l.whereFields[0] == l.fieldName {\n\t\t\t\t\tif !matchesWhere(l.filters[min], map[string]interface{}{l.fieldName: value}) {\n\t\t\t\t\t\tvalue = nil\n\t\t\t\t\t}\n\t\t\t\t} else { // decode everything\n\t\t\t\t\tfieldsWithNames, err := l.decoder.DecodeFieldsWithNames(l.valueBuffer[min])\n\t\t\t\t\tif err != nil || !matchesWhere(l.filters[min], fieldsWithNames) {\n\t\t\t\t\t\tvalue = nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// advance the cursor\n\t\tnextKey, nextVal := l.cursors[min].Next()\n\t\tif nextKey == nil {\n\t\t\tl.keyBuffer[min] = 0\n\t\t} else {\n\t\t\tl.keyBuffer[min] = int64(btou64(nextKey))\n\t\t}\n\t\tl.valueBuffer[min] = nextVal\n\n\t\t// if the value didn't match our filter or if we didn't find the field keep iterating\n\t\tif err != nil || value == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// if it's a raw query, we always limit the amount we read in\n\t\tif l.isRaw {\n\t\t\tl.limit--\n\t\t\tl.perIntervalLimit--\n\t\t}\n\n\t\treturn seriesKey, timestamp, value\n\t}\n}", "func (it *TimeSeriesDataPointIterator) Next() (*aiplatformpb.TimeSeriesDataPoint, error) {\n\tvar item *aiplatformpb.TimeSeriesDataPoint\n\tif err := it.nextFunc(); err != nil {\n\t\treturn item, err\n\t}\n\titem = it.items[0]\n\tit.items = it.items[1:]\n\treturn item, nil\n}", "func (rows *Rows) Next() bool {\n\tif rows.closed {\n\t\treturn false\n\t}\n\n\trows.rowCount++\n\trows.columnIdx = 0\n\trows.vr = ValueReader{}\n\n\tfor {\n\t\tt, r, err := rows.conn.rxMsg()\n\t\tif err != nil {\n\t\t\trows.Fatal(err)\n\t\t\treturn false\n\t\t}\n\n\t\tswitch t {\n\t\tcase readyForQuery:\n\t\t\trows.conn.rxReadyForQuery(r)\n\t\t\trows.close()\n\t\t\treturn false\n\t\tcase dataRow:\n\t\t\tfieldCount := r.readInt16()\n\t\t\tif int(fieldCount) != len(rows.fields) {\n\t\t\t\trows.Fatal(ProtocolError(fmt.Sprintf(\"Row description field count (%v) and data row field count (%v) do not match\", len(rows.fields), fieldCount)))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\trows.mr = r\n\t\t\treturn true\n\t\tcase commandComplete:\n\t\tcase bindComplete:\n\t\tdefault:\n\t\t\terr = rows.conn.processContextFreeMsg(t, r)\n\t\t\tif err != nil {\n\t\t\t\trows.Fatal(err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}", "func (rd *RowDecoder) CurrentRowWithDefaultVal() chunk.Row {\n\treturn rd.mutRow.ToRow()\n}", "func (r *Rows) Next() bool {\n\treturn r.c.Next(context.TODO())\n}", "func DecodeTxnRowNext(s string) (round uint64, intra uint32, err error) {\n\tvar b []byte\n\tb, err = base64.URLEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn\n\t}\n\tround = binary.LittleEndian.Uint64(b[:8])\n\tintra = binary.LittleEndian.Uint32(b[8:])\n\treturn\n}", "func (itr *doltColDiffCommitHistoryRowItr) Next(ctx *sql.Context) (sql.Row, error) {\n\tfor itr.tableChanges == nil {\n\t\tif itr.commits != nil {\n\t\t\tfor _, commit := range itr.commits {\n\t\t\t\terr := itr.loadTableChanges(ctx, commit)\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\t\t\titr.commits = nil\n\t\t} else if itr.child != nil {\n\t\t\t_, commit, err := itr.child.Next(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = itr.loadTableChanges(ctx, commit)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t}\n\n\ttableChange := itr.tableChanges[itr.tableChangesIdx]\n\tdefer itr.incrementIndexes(tableChange)\n\n\tmeta := itr.meta\n\th := itr.hash\n\tcol := tableChange.colNames[itr.colIdx]\n\tdiffType := tableChange.diffTypes[itr.colIdx]\n\n\treturn sql.NewRow(\n\t\th.String(),\n\t\ttableChange.tableName,\n\t\tcol,\n\t\tmeta.Name,\n\t\tmeta.Email,\n\t\tmeta.Time(),\n\t\tmeta.Description,\n\t\tdiffType,\n\t), nil\n}", "func (c *jsonTableCol) Next(obj interface{}, pass bool, ord int) (sql.Row, error) {\n\t// nested column should recurse\n\tif len(c.cols) != 0 {\n\t\tif c.data == nil {\n\t\t\tc.LoadData(obj)\n\t\t}\n\n\t\tvar innerObj interface{}\n\t\tif !c.finished {\n\t\t\tinnerObj = c.data[c.pos]\n\t\t}\n\n\t\tvar row sql.Row\n\t\tfor i, col := range c.cols {\n\t\t\tinnerPass := len(col.cols) != 0 && i != c.currSib\n\t\t\trowPart, err := col.Next(innerObj, pass || innerPass, c.pos+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trow = append(row, rowPart...)\n\t\t}\n\n\t\tif pass {\n\t\t\treturn row, nil\n\t\t}\n\n\t\tif c.NextSibling() {\n\t\t\tfor _, col := range c.cols {\n\t\t\t\tcol.Reset()\n\t\t\t}\n\t\t\tc.pos++\n\t\t}\n\n\t\tif c.pos >= len(c.data) {\n\t\t\tc.finished = true\n\t\t}\n\n\t\treturn row, nil\n\t}\n\n\t// this should only apply to nested columns, maybe...\n\tif pass {\n\t\treturn sql.Row{nil}, nil\n\t}\n\n\t// FOR ORDINAL is a special case\n\tif c.opts != nil && c.opts.forOrd {\n\t\treturn sql.Row{ord}, nil\n\t}\n\n\t// TODO: cache this?\n\tval, err := jsonpath.JsonPathLookup(obj, c.path)\n\tif c.opts.exists {\n\t\tif err != nil {\n\t\t\treturn sql.Row{0}, nil\n\t\t} else {\n\t\t\treturn sql.Row{1}, nil\n\t\t}\n\t}\n\n\t// key error means empty\n\tif err != nil {\n\t\tif c.opts.errOnEmp {\n\t\t\treturn nil, fmt.Errorf(\"missing value for JSON_TABLE column '%s'\", c.opts.name)\n\t\t}\n\t\tval = c.opts.defEmpVal\n\t}\n\n\tval, _, err = c.opts.typ.Convert(val)\n\tif err != nil {\n\t\tif c.opts.errOnErr {\n\t\t\treturn nil, err\n\t\t}\n\t\tval, _, err = c.opts.typ.Convert(c.opts.defErrVal)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Base columns are always finished\n\tc.finished = true\n\treturn sql.Row{val}, nil\n}" ]
[ "0.5889878", "0.57259405", "0.57251215", "0.56501406", "0.56458294", "0.56086314", "0.5569356", "0.5569176", "0.54771554", "0.54464453", "0.542114", "0.5378522", "0.5372761", "0.53529674", "0.53516585", "0.53472406", "0.5343415", "0.5331963", "0.53126574", "0.52973896", "0.52861017", "0.5272457", "0.525892", "0.5248517", "0.52250916", "0.51749337", "0.51747566", "0.5172372", "0.5163942", "0.51625675", "0.51424813", "0.51386565", "0.51384056", "0.50908744", "0.50282675", "0.5024956", "0.5020564", "0.5019847", "0.50191516", "0.5002512", "0.4993386", "0.49852064", "0.49679136", "0.4959291", "0.49327108", "0.49325663", "0.4928379", "0.49208957", "0.49134752", "0.48860323", "0.48753518", "0.48723033", "0.48626745", "0.48353174", "0.48202342", "0.4802606", "0.47957075", "0.47953427", "0.4795194", "0.47734103", "0.47683036", "0.47682118", "0.47680745", "0.47668505", "0.47572577", "0.4743586", "0.47137547", "0.46923628", "0.46900076", "0.46820936", "0.46810588", "0.4658101", "0.4654514", "0.46169162", "0.45916194", "0.45891932", "0.45849684", "0.45405087", "0.4538043", "0.45369563", "0.45133823", "0.45093912", "0.4504737", "0.45021397", "0.44974828", "0.4496725", "0.44862062", "0.44845885", "0.44816026", "0.44514558", "0.44416094", "0.44197556", "0.44164735", "0.4416274", "0.44093153", "0.44082916", "0.44012073", "0.43952683", "0.43926138", "0.43821788" ]
0.73612094
0
numRows returns 3, except at start.
func (c *CSVInterpolator) numRows() int64 { if c.row == 1 { return rowsNeededToInterpolate - 1 } return rowsNeededToInterpolate }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (self *T) Rows() int {\n\treturn 2\n}", "func (self *T) Rows() int {\n\treturn 2\n}", "func (c ColDecimal32) Rows() int {\n\treturn len(c)\n}", "func (c ColDecimal256) Rows() int {\n\treturn len(c)\n}", "func (c ColBool) Rows() int {\n\treturn len(c)\n}", "func row(k int) int { return k % 4 }", "func (m M) Rows() int {\n\treturn m.r\n}", "func (c ColDecimal64) Rows() int {\n\treturn len(c)\n}", "func SQLRowCount(rows *sql.Rows) int {\n\tcount := 0\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\tfmt.Println(strconv.Itoa(count))\n\treturn count\n\n}", "func (b *Buffer) getNumOfVisibleRows () int {\n visibleRows := b.rowsOffset + (b.maxVisibleRows - b.reservedRows)\n\n if visibleRows > len(b.rows) {\n visibleRows = len(b.rows)\n }\n\n return visibleRows\n}", "func (matrix *Matrix) getNumRows() int {\n\treturn matrix.NumRows\n}", "func (c ColDate) Rows() int {\n\treturn len(c)\n}", "func (g *Game) Rows() int {\n\treturn int(g.rows)\n}", "func (b Board) NumRows() int {\n\treturn b.nrows\n}", "func (m *matrixComplex) GetNumRows() int { return m.numRows }", "func (fw *Writer) NumRows() int { return fw.nrows }", "func (d *Dense) Rows() int {\n\treturn d.rows\n}", "func iterateRows(count uint, start uint) []uint {\n\tvar i uint\n\tvar items []uint\n\tfor i = start; i < count+1; i++ {\n\t\titems = append(items, i)\n\t}\n\treturn items\n}", "func (d *AddressCacheItem) NumRows() (int, *BlockID) {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\tif d.rows == nil {\n\t\treturn -1, nil\n\t}\n\treturn len(d.rows), d.blockID()\n}", "func (b *Bitmap) Rows() int {\n\treturn int(b.handle.rows)\n}", "func (n *partitionSorter) Len() int { return len(n.rows) }", "func (A *Matrix) Rows() int {\n\treturn A.height\n}", "func (*mySQL) GetRowCount(r RequestAgGrid, rows int) int64 {\n\tif rows == 0 {\n\t\treturn 0\n\t}\n\n\tcurrentLastRow := r.StartRow + int64(rows)\n\n\tif currentLastRow <= r.EndRow {\n\t\treturn currentLastRow\n\t}\n\treturn -1\n}", "func (g *NormalGrid) Rows() int {\n\treturn g.rows\n}", "func (A *Matrix64) Nrows() int {\n\treturn A.nrows\n}", "func getNumberOfRecords(c *bolt.Cursor) (i int) {\n\tfor k, _ := c.First(); k != nil; k, _ = c.Next() {\n\t\ti++\n\t}\n\treturn i\n}", "func (t *Table) Rows() int {\n\treturn len(t.Row)\n}", "func (ac *AddressCache) NumRows(addr string) (int, *BlockID) {\n\taci := ac.addressCacheItem(addr)\n\tif aci == nil {\n\t\treturn -1, nil\n\t}\n\treturn aci.NumRows()\n}", "func checkRows(game Game) []int {\n\tvar out []int\n\n\tfor i, card := range game.Cards {\n\t\tfor _, row := range card.Rows {\n\t\t\tif row.Squares[0].Called && row.Squares[1].Called && row.Squares[2].Called && row.Squares[3].Called && row.Squares[4].Called {\n\t\t\t\tout = append(out, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func (t *Slice) Size() int32 { return 4 }", "func (m *Multi) Len() int {\n\treturn len(m.Rows)\n}", "func (fw *Writer) NumRowGroups() int { return fw.rowGroups }", "func TestGetBoardRowSlice(t *testing.T) {\n\tgameBoard := CreateGameBoard(5)\n\texpectedRowSlice := []string{\"20\", \"21\", \"22\", \"23\", \"24\"}\n\n\trowSlice := GetBoardRowSlice(4, gameBoard)\n\n\tfor i, val := range rowSlice {\n\t\tif val != expectedRowSlice[i] {\n\t\t\tt.Errorf(\"Unexpected element at row slice. actual: %s, expected: %s, index: %d\", val, expectedRowSlice[i], i)\n\t\t}\n\t}\n}", "func (b *Board) CheckRows() []int {\n\tfullRows := []int{}\n\n\tfor i, row := range b.Blocks {\n\t\tfor j, cell := range row {\n\t\t\tif cell == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif j == len(row)-1 {\n\t\t\t\tfullRows = append(fullRows, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fullRows\n}", "func (x IntSlice) Len() int {return len(x)}", "func (rr rowRangeSlice) Len() int {\n\treturn len(rr)\n}", "func (f *fragment) rows(start uint64, filters ...rowFilter) []uint64 {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\treturn f.unprotectedRows(start, filters...)\n}", "func (mc MultiCursor) GetRows() []int {\n\trowmap := make(map[int]bool)\n\tfor _, cursor := range mc.cursors {\n\t\trowmap[cursor.Row()] = true\n\t}\n\trows := []int{}\n\tfor row := range rowmap {\n\t\trows = append(rows, row)\n\t}\n\treturn rows\n}", "func (A *AugmentedSparseMatrix64) Nrows() int {\n\treturn A.a.Nrows() + A.a.Ncols()\n}", "func (A *CSRMatrix64) Nrows() int {\n\tif A.transposed {\n\t\treturn A.ncols\n\t} else {\n\t\treturn A.nrows\n\t}\n}", "func getNumberOfResults(dtData dtPaginationData, aux []interface{}) error {\n\trows, err := dtData.db.Table(dtData.tableName).\n\t\tSelect(\"COUNT(*)\").\n\t\tWhere(generateDTWhereQuery(dtData.dtColumns), aux...).\n\t\tOrder(dtData.dtSortingColumn.dbColumnName).\n\t\tRows()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not execute query to get the number of results %w\", err)\n\t}\n\n\tdefer func() {\n\t\t_ = rows.Close()\n\n\t\terr = rows.Err()\n\t}()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"row error occurred %w\", err)\n\t}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&final)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not scan row to &final %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func checkCols(game Game) []int {\n\tvar out []int\n\n\tfor i, card := range game.Cards {\n\t\tfor j := 0; j <= 4; j++ {\n\t\t\tif card.Rows[0].Squares[j].Called && card.Rows[1].Squares[j].Called && card.Rows[2].Squares[j].Called && card.Rows[3].Squares[j].Called && card.Rows[4].Squares[j].Called {\n\t\t\t\tout = append(out, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func generate(numRows int) [][]int {\n\tvar triangle [][]int\n\tif numRows <= 0 {\n\t\treturn triangle\n\t}\n\tfor i := 0; i < numRows; i++ {\n\t\tvar row []int\n\t\tfor j := 0; j < i+1; j++ {\n\t\t\tif j == 0 || j == i {\n\t\t\t\trow = append(row, 1)\n\t\t\t} else {\n\t\t\t\t/**\n\t\t\t\t * calculate element value:\n\t\t\t\t *\n\t\t\t\t * K(i)(j) = K(i-1)(j-1) + K(i-1)(j)\n\t\t\t\t *\n\t\t\t\t * except for the first and last element\n\t\t\t\t */\n\t\t\t\trow = append(row, triangle[i-1][j-1]+triangle[i-1][j])\n\t\t\t}\n\t\t}\n\t\ttriangle = append(triangle, row)\n\t}\n\treturn triangle\n}", "func (self *T) Cols() int {\n\treturn 2\n}", "func getTableRowAndColumnCount(table *goquery.Selection) (int, int) {\n\trows := 0\n\tcolumns := 0\n\ttable.Find(\"tr\").Each(func(_ int, tr *goquery.Selection) {\n\t\t// Look for rows\n\t\tstrRowSpan, _ := tr.Attr(\"rowspan\")\n\t\trowSpan, err := strconv.Atoi(strRowSpan)\n\t\tif err != nil {\n\t\t\trowSpan = 1\n\t\t}\n\t\trows += rowSpan\n\n\t\t// Now look for columns\n\t\tcolumnInThisRow := 0\n\t\ttr.Find(\"td\").Each(func(_ int, td *goquery.Selection) {\n\t\t\tstrColSpan, _ := tr.Attr(\"colspan\")\n\t\t\tcolSpan, err := strconv.Atoi(strColSpan)\n\t\t\tif err != nil {\n\t\t\t\tcolSpan = 1\n\t\t\t}\n\t\t\tcolumnInThisRow += colSpan\n\t\t})\n\n\t\tif columnInThisRow > columns {\n\t\t\tcolumns = columnInThisRow\n\t\t}\n\t})\n\n\treturn rows, columns\n}", "func rowFromPosition(pos int) int {\n return pos / 8\n}", "func (v Chunk) NCols() int {\n\treturn len(v.buf.Columns)\n}", "func (s *Slicer) NumZSlices() int {\n\treturn int(0.5 + (s.irmf.Max[2]-s.irmf.Min[2])/s.deltaZ)\n}", "func (planet *Planet) getMultiTileWidth(layer []Tile, x,y int) int {\n\toffsetX := 1\n\tfor layer[planet.GetTileIndex(x+offsetX,y)].OffsetX == int8(offsetX) {\n\t\toffsetX++\n\t}\n\treturn offsetX\n}", "func (qb *HuxQueryBuilder) NumRows(rows int) *HuxQueryBuilder {\n\tqb.numRows = rows\n\treturn qb\n}", "func (A *SymmetrizedMatrix64) Nrows() int {\n\treturn A.a.Ncols()\n}", "func (card *Card) N() []*cell { return card.columns[N-1] }", "func (f *fragment) unprotectedRows(start uint64, filters ...rowFilter) []uint64 {\n\tstartKey := rowToKey(start)\n\ti, _ := f.storage.Containers.Iterator(startKey)\n\trows := make([]uint64, 0)\n\tvar lastRow uint64 = math.MaxUint64\n\n\t// Loop over the existing containers.\n\tfor i.Next() {\n\t\tkey, c := i.Value()\n\n\t\t// virtual row for the current container\n\t\tvRow := key >> shardVsContainerExponent\n\n\t\t// skip dups\n\t\tif vRow == lastRow {\n\t\t\tcontinue\n\t\t}\n\n\t\t// apply filters\n\t\taddRow, done := true, false\n\t\tfor _, filter := range filters {\n\t\t\tvar d bool\n\t\t\taddRow, d = filter(vRow, key, c)\n\t\t\tdone = done || d\n\t\t\tif !addRow {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif addRow {\n\t\t\tlastRow = vRow\n\t\t\trows = append(rows, vRow)\n\t\t}\n\t\tif done {\n\t\t\treturn rows\n\t\t}\n\t}\n\treturn rows\n}", "func (m Mat2f) Rows() (row0, row1 Vec2f) {\n\treturn m.Row(0), m.Row(1)\n}", "func (m *matrix) GetRows() int {\n\treturn m.rows\n}", "func getFirstDrawResults(dtData dtPaginationData) error {\n\trows, err := dtData.db.Table(dtData.tableName).Select(\"COUNT(*)\").Rows()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"could not execute query to get the rowcount of the entire '%v' table %w\", dtData.tableName, err,\n\t\t)\n\t}\n\n\tdefer func() {\n\t\t_ = rows.Close()\n\n\t\terr = rows.Err()\n\t}()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"row error occurred %w\", err)\n\t}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&final)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not scan row to &final %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func rowsInFile(fileName string) (int, error) {\n\tfileReader, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer fileReader.Close()\n\treturn lineCounter(fileReader)\n}", "func (items IntSlice) Len() int { return len(items) }", "func initializeMiddleZone() [][]Piece {\n\trows := make([][]Piece, 3)\n\tfor i := range rows {\n\t\trows[i] = []Piece{nil, nil, nil, nil, nil, nil, nil, nil, nil}\n\t}\n\treturn rows\n}", "func (s *ServicesWidget) RowCount() int {\n\treturn len(s.filteredRows)\n}", "func (p *partitionImpl) GetNumRows() int {\n\treturn int(p.internalData.NumRows)\n}", "func (wf WindowFrame) RowCount() int {\n\treturn len(wf.Rows)\n}", "func (r *Result) GetRowN() []Nullable {\n\trowBuf := r.val.buffer\n\tret := make([]Nullable, len(rowBuf))\n\tfor i := range rowBuf {\n\t\tret[i] = rowBuf[i]\n\t}\n\treturn ret\n}", "func (m *Matrix) Rows() [][]int {\n\tcpy := make([][]int, m.nRows)\n\tfor i := range cpy {\n\t\tcpy[i] = make([]int, m.nCols)\n\t\tcopy(cpy[i], m.data[i])\n\t}\n\n\treturn cpy\n}", "func (m Matrix) Len() int { return len(m) }", "func (sheet *SheetData) NumberRows() int {\n\treturn len(sheet.Values)\n\n}", "func (*Array) NKeys() int { return 2 }", "func (A *Matrix) Cols() int {\n\treturn A.width\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 (p *Puzzle) Len() int {\r\n\treturn 4 + 4 + len(p.Random) + len(p.Padding)\r\n}", "func GetNumElements(results []string) int {\n\ti := 0\n for _, _ = range results {\n\t\t\ti++\n }\n return i\n}", "func (s *Slicer) NumXSlices() int {\n\tn := int(0.5 + (s.irmf.Max[0]-s.irmf.Min[0])/s.deltaX)\n\tif n%2 == 1 {\n\t\tn++\n\t}\n\treturn n\n}", "func (self *T) Cols() int {\n\treturn 1\n}", "func (card *Card) lastRowNum() int {\n\treturn len(card.rows)\n}", "func (ref *UIElement) RowCount() int64 {\n\tret, _ := ref.Int64Attr(RowCountAttribute)\n\treturn ret\n}", "func (ref *UIElement) Rows() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(RowsAttribute)\n}", "func (m *Matrix) Width() int {\n\treturn -1\n}", "func (dt *DataTable) Take(n int) DataTable {\n\tif n > len(dt.Rows) {\n\t\tn = len(dt.Rows)\n\t}\n\n\treturn DataTable{\n\t\tColumns: dt.Columns,\n\t\tRows: dt.Rows[:n],\n\t}\n}", "func (c *Column) numberOfIssues() int {\n\tn := 0\n\tfor _, card := range c.Cards {\n\t\tif card.ContentURL != \"\" {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}", "func (reader *Reader) GetNColumnIn() int {\n\treturn len(reader.InputMetadata)\n}", "func (ids IDSlice) N() Size {\n\treturn Size(len(ids))\n}", "func rowForIndex(ind int) int {\n\treturn ind / 9\n}", "func (m *matrixComplex) NumElements() int { return m.numCols * m.numRows }", "func (game Game) WinRow() [3]int {\n\treturn game.winRow\n}", "func main() {\n\tarray := [12][4][7][10]float64{}\n\n\tx := len(array)\n\ty := len(array[0])\n\tz := len(array[0][0])\n\tw := len(array[0][0][0])\n\tfmt.Println(\"x:\", x, \"y:\", y, \"z:\", z, \"w:\", w)\n}", "func generate(numRows int) [][]int {\n\tres := make([][]int, numRows)\n\tfor i := range res {\n\t\tres[i] = make([]int, i + 1)\n\t\tres[i][0] = 1\n\t\t// 头尾赋值\n\t\tres[i][i] = 1\n\t\tfor j := 1; j < i; j++ {\n\t\t\tres[i][j] = res[i-1][j]+res[i-1][j-1]\n\t\t}\n\t}\n\treturn res\n}", "func ex3() {\n\tx := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51}\n\tfmt.Println(x[:5])\n\tfmt.Println(x[5:])\n\tfmt.Println(x[2:7])\n\tfmt.Println(x[1:6])\n}", "func (board *Board) Len() int {\n\treturn board.Dimension * board.Dimension\n}", "func (r Result) Len() int { return len(r.rolls) }", "func (t *Table) NumRowsInConflict(ctx context.Context) (uint64, error) {\n\tif t.Format() == types.Format_DOLT {\n\t\tartIdx, err := t.table.GetArtifacts(ctx)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn artIdx.ConflictCount(ctx)\n\t}\n\n\tok, err := t.table.HasConflicts(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif !ok {\n\t\treturn 0, nil\n\t}\n\n\t_, cons, err := t.table.GetConflicts(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn cons.Count(), nil\n}", "func (ra *rowsAffectedError) RowsAffected() int64 {\n\treturn ra.rowsAffected\n}", "func selectCnt(d *sql.DB, sql string) (int, error) {\n\trows, err := d.Query(sql)\n\tdefer func() {\n\t\tif rows != nil {\n\t\t\trows.Close()\n\t\t}\n\t}()\n\tif err != nil {\n\t\t//if strings.Contains(err.Error(), \"newer than query schema version\")\n\t\treturn 0, err\n\t}\n\tvar cnt int\n\tfor rows.Next() {\n\t\tif rows.Err() != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif err := rows.Scan(&cnt); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn cnt, nil\n}", "func (p intSlice) Len() int { return len(p) }", "func (m M) Cols() int {\n\treturn m.c\n}", "func (dbi *DB) SelectRows(nums int, sqls string, arg ...string) ([]map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tvar resvar []map[string]string\r\n\tlimit := 0\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found, lsnr had been release automatically\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tline := make(map[string]string)\r\n\t\tfor i := 0; i < len(rows.Cols); i++ {\r\n\t\t\tline[rows.Cols[i]] = colvar[i]\r\n\t\t}\r\n\t\tresvar = append(resvar, line)\r\n\t\tlimit++\r\n\t\tif nums > 0 && limit >= nums {\r\n\t\t\trows.Close()\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\treturn resvar, nil\r\n}", "func (f *FieldValues) NumRow() int {\n\treturn f.rows\n}", "func (col Columns) Len() int {\n\tif col.NumLevels() == 0 {\n\t\treturn 0\n\t}\n\treturn col.Levels[0].Len()\n}", "func generate(numRows int) [][]int {\n\t// Accepted\n\t// 15/15 cases passed (0 ms)\n\t// Your runtime beats 100 % of golang submissions\n\t// Your memory usage beats 69.54 % of golang submissions (2 MB)\n\tif numRows < 1 {\n\t\treturn [][]int{}\n\t}\n\tres := make([][]int, numRows)\n\ti := 0\n\tfor i < numRows {\n\t\tres[i] = make([]int, i+1)\n\t\tres[i][0], res[i][i] = 1, 1\n\t\tj := 1\n\t\tfor j < i {\n\t\t\tres[i][j] = res[i-1][j-1] + res[i-1][j]\n\t\t\tj++\n\t\t}\n\t\ti++\n\t}\n\treturn res\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 (vp *baseVectorParty) GetElemCount(row int) uint32 {\n\tif vp.offsets == nil || row < 0 || row >= vp.length {\n\t\treturn 0\n\t}\n\treturn *(*uint32)(vp.offsets.GetValue(2*row + 1))\n}" ]
[ "0.6365174", "0.6365174", "0.62216914", "0.618833", "0.59803337", "0.59444803", "0.5942407", "0.5911823", "0.58158314", "0.57634497", "0.57372934", "0.56988037", "0.5666907", "0.56184083", "0.55306053", "0.5523928", "0.54944867", "0.5483164", "0.5455977", "0.54121286", "0.5412038", "0.5379336", "0.5343627", "0.53206503", "0.5299431", "0.5290902", "0.52872264", "0.52701783", "0.52619624", "0.52390206", "0.52111167", "0.5189662", "0.5143132", "0.51280236", "0.511866", "0.5070863", "0.5068258", "0.5032267", "0.50288576", "0.5003252", "0.5002522", "0.49980366", "0.49797636", "0.49796006", "0.49772793", "0.497643", "0.49741274", "0.49666125", "0.49660328", "0.49569926", "0.49533337", "0.49498612", "0.49465403", "0.4944923", "0.49385825", "0.49330074", "0.49265963", "0.4919473", "0.48999396", "0.4866712", "0.48524305", "0.48515004", "0.48417163", "0.4840864", "0.4839932", "0.48398873", "0.48352462", "0.48289755", "0.48276868", "0.48177767", "0.48142123", "0.481392", "0.47940284", "0.4791552", "0.47892147", "0.47793496", "0.47361106", "0.47305816", "0.47222167", "0.47158527", "0.47142914", "0.47136846", "0.47127756", "0.47127247", "0.4704476", "0.46985552", "0.46931452", "0.46898106", "0.46834436", "0.4676005", "0.46726185", "0.46712872", "0.46678263", "0.4667693", "0.46656498", "0.4662304", "0.4653126", "0.4652254", "0.4646507", "0.46378344" ]
0.64513195
0
rowToStartWith returns c.row1, except at start.
func (c *CSVInterpolator) rowToStartWith() int64 { if c.row == 1 { return 1 } return c.row - 1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func lineStart(f *token.File, line int) token.Pos {\n\t// Use binary search to find the start offset of this line.\n\t//\n\t// TODO(rstambler): eventually replace this function with the\n\t// simpler and more efficient (*go/token.File).LineStart, added\n\t// in go1.12.\n\n\tmin := 0 // inclusive\n\tmax := f.Size() // exclusive\n\tfor {\n\t\toffset := (min + max) / 2\n\t\tpos := f.Pos(offset)\n\t\tposn := f.Position(pos)\n\t\tif posn.Line == line {\n\t\t\treturn pos - (token.Pos(posn.Column) - 1)\n\t\t}\n\n\t\tif min+1 >= max {\n\t\t\treturn token.NoPos\n\t\t}\n\n\t\tif posn.Line < line {\n\t\t\tmin = offset\n\t\t} else {\n\t\t\tmax = offset\n\t\t}\n\t}\n}", "func rowFromPosition(pos int) int {\n return pos / 8\n}", "func (p *HbaseClient) GetRowOrBefore(tableName Text, row Text, family Text) (r []*TCell, err error) {\n\tif err = p.sendGetRowOrBefore(tableName, row, family); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowOrBefore()\n}", "func findBeginOfLine(r io.ReaderAt, offset int64) (first int64, err error) {\n\tfor i := offset; i >= 0; i-- {\n\t\tif i == 0 {\n\t\t\tfirst = 0\n\t\t\tbreak\n\t\t}\n\n\t\tbuf := make([]byte, 1)\n\t\tif _, err = r.ReadAt(buf, i); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif i == offset && rune(buf[0]) == '\\n' {\n\t\t\tcontinue\n\t\t}\n\t\tif rune(buf[0]) == '\\n' {\n\t\t\tfirst = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func buildXRefTableStartingAt(ctx *model.Context, offset *int64) error {\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: begin\")\n\n\trs := ctx.Read.RS\n\tconf := ctx.Configuration\n\thv, eolCount, err := headerVersion(rs, conf.HeaderBufSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.HeaderVersion = hv\n\tctx.Read.EolCount = eolCount\n\toffs := map[int64]bool{}\n\txrefSectionCount := 0\n\n\tfor offset != nil {\n\n\t\tif offs[*offset] {\n\t\t\toffset, err = offsetLastXRefSection(ctx, ctx.Read.FileSize-*offset)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif offs[*offset] {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\toffs[*offset] = true\n\n\t\toff, err := tryXRefSection(ctx, rs, offset, &xrefSectionCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif off == nil || *off != 0 {\n\t\t\toffset = off\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Read.Println(\"buildXRefTableStartingAt: found xref stream\")\n\t\tctx.Read.UsingXRefStreams = true\n\t\trd, err := newPositionedReader(rs, offset)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif offset, err = parseXRefStream(rd, offset, ctx); err != nil {\n\t\t\tlog.Read.Printf(\"bypassXRefSection after %v\\n\", err)\n\t\t\t// Try fix for corrupt single xref section.\n\t\t\treturn bypassXrefSection(ctx)\n\t\t}\n\n\t}\n\n\tpostProcess(ctx, xrefSectionCount)\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: end\")\n\n\treturn nil\n}", "func (c Coordinate) Row() int { return c.row }", "func (file *File) SearchFromStart(searchTerm string) (row, col int, err error) {\n\tloop := false\n\tcursor := cursor.MakeCursor(0, -1)\n\trow, col, err = file.buffer.Search(searchTerm, cursor, loop)\n\treturn\n}", "func (p *partitionImpl) getRow(row *rowImpl, rowNum int) sif.Row {\n\trow.rowNum = rowNum\n\trow.partition = p\n\treturn row\n}", "func (pi *PixelIterator) GetPreviousIteratorRow() (pws []*PixelWand) {\n\tnum := C.size_t(0)\n\tpp := C.PixelGetPreviousIteratorRow(pi.pi, &num)\n\tif pp == nil {\n\t\treturn\n\t}\n\tfor i := 0; i < int(num); i++ {\n\t\tcpw := C.get_pw_at(pp, C.size_t(i))\n\t\t// PixelWand is a private pointer, borrowed from the pixel\n\t\t// iterator. We don't want to reference count it. It will\n\t\t// get destroyed by C API when PixelIterator is destroyed.\n\t\tpws = append(pws, &PixelWand{pw: cpw})\n\t}\n\truntime.KeepAlive(pi)\n\treturn\n}", "func CursorToNextRow() string {\n\tout := \"\"\n\tout += fmt.Sprint(cursorDown(1))\n\tout += fmt.Sprint(cursorLeft(2))\n\n\treturn out\n}", "func (card *Card) getRow(rowNum int) (error, []*cell) {\n\tif card.isValidRow(rowNum) {\n\t\treturn nil, card.rows[rowNum]\n\t}\n\treturn fmt.Errorf(\"Invalid row number: %d from %d\", rowNum, len(card.rows)), []*cell{}\n}", "func (p *SASQueryParameters) StartRowKey() string {\n\treturn p.startRk\n}", "func (sr SourceRange) Start() SourceLocation {\n\treturn SourceLocation{C.clang_getRangeStart(sr.c)}\n}", "func (c *CSVInterpolator) NextRow() ([]string, error) {\n\tc.row++\n\trowsToGet := c.numRows()\n\n\trows, err := c.rp.GetRows(c.rowToStartWith(), rowsToGet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rowsToGet != rowsNeededToInterpolate {\n\t\trows = [][]string{nil, rows[0], rows[1]}\n\t}\n\n\tif rows[1] == nil {\n\t\treturn nil, io.EOF\n\t}\n\n\treturn MiddleRow(rows, c.decimalPlaces), nil\n}", "func newRowIterator(tbl *DoltTable, ctx *sql.Context, partition *doltTablePartition) (*doltTableRowIter, error) {\n\trowData, err := tbl.table.GetRowData(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mapIter types.MapIterator\n\tvar end types.LesserValuable\n\tif partition == nil {\n\t\tmapIter, err = rowData.BufferedIterator(ctx)\n\t} else {\n\t\tendIter, err := rowData.IteratorAt(ctx, partition.end)\n\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t} else if err == nil {\n\t\t\tkeyTpl, _, err := endIter.Next(ctx)\n\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif keyTpl != nil {\n\t\t\t\tend, err = keyTpl.(types.Tuple).AsSlice()\n\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\t\t}\n\n\t\tmapIter, err = rowData.BufferedIteratorAt(ctx, partition.start)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &doltTableRowIter{table: tbl, rowData: rowData, ctx: ctx, nomsIter: mapIter, end: end, nbf: rowData.Format()}, nil\n}", "func (p *partitionImpl) GetRow(rowNum int) sif.Row {\n\treturn &rowImpl{rowNum, p}\n}", "func (f *fragment) minRow(filter *Row) (uint64, uint64) {\n\tminRowID, hasRowID := f.minRowID()\n\tif hasRowID {\n\t\tif filter == nil {\n\t\t\treturn minRowID, 1\n\t\t}\n\t\t// iterate from min row ID and return the first that intersects with filter.\n\t\tfor i := minRowID; i <= f.maxRowID; i++ {\n\t\t\trow := f.row(i).Intersect(filter)\n\t\t\tcount := row.Count()\n\t\t\tif count > 0 {\n\t\t\t\treturn i, count\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, 0\n}", "func (pi *PixelIterator) SetFirstIteratorRow() {\n\tC.PixelSetFirstIteratorRow(pi.pi)\n\truntime.KeepAlive(pi)\n}", "func posFromRowColumn(r int, c int) int {\n return r * 8 + c\n}", "func getRow(block [][]float32, index int) []float32 {\n\trow := block[index][:]\n\treturn row\n}", "func (self *BpNode) get_start(key types.Hashable) (i int, leaf *BpNode) {\n\tif self.Internal() {\n\t\treturn self.internal_get_start(key)\n\t} else {\n\t\treturn self.leaf_get_start(key)\n\t}\n}", "func rowForIndex(ind int) int {\n\treturn ind / 9\n}", "func WindowStart(t, every, offset int64) int64 {\n\tmod := Modulo(t, every)\n\toff := Modulo(offset, every)\n\tbeg := t - mod + off\n\tif mod < off {\n\t\tbeg -= every\n\t}\n\treturn beg\n}", "func getStatementStart(src []byte) []byte {\n\tpos := indexOfNonSpaceChar(src)\n\tif pos == -1 {\n\t\treturn nil\n\t}\n\n\tsrc = src[pos:]\n\tif src[0] != charComment {\n\t\treturn src\n\t}\n\n\t// skip comment section\n\tpos = bytes.IndexFunc(src, isCharFunc('\\n'))\n\tif pos == -1 {\n\t\treturn nil\n\t}\n\n\treturn getStatementStart(src[pos:])\n}", "func NewLineStartSplitFunc(re *regexp.Regexp) bufio.SplitFunc {\n\treturn func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\tfirstLoc := re.FindIndex(data)\n\t\tif firstLoc == nil {\n\t\t\treturn 0, nil, nil // read more data and try again.\n\t\t}\n\t\tfirstMatchStart := firstLoc[0]\n\t\tfirstMatchEnd := firstLoc[1]\n\n\t\tif firstMatchStart != 0 {\n\t\t\t// the beginning of the file does not match the start pattern, so return a token up to the first match so we don't lose data\n\t\t\tadvance = firstMatchStart\n\t\t\ttoken = data[0:firstMatchStart]\n\t\t\treturn\n\t\t}\n\n\t\tif firstMatchEnd == len(data) {\n\t\t\t// the first match goes to the end of the buffer, so don't look for a second match\n\t\t\treturn 0, nil, nil\n\t\t}\n\n\t\tsecondLocOffset := firstMatchEnd + 1\n\t\tsecondLoc := re.FindIndex(data[secondLocOffset:])\n\t\tif secondLoc == nil {\n\t\t\treturn 0, nil, nil // read more data and try again\n\t\t}\n\t\tsecondMatchStart := secondLoc[0] + secondLocOffset\n\n\t\tadvance = secondMatchStart // start scanning at the beginning of the second match\n\t\ttoken = data[firstMatchStart:secondMatchStart] // the token begins at the first match, and ends at the beginning of the second match\n\t\terr = nil\n\t\treturn\n\t}\n}", "func (r *Rope) Before(at int, fn func(r rune) bool) (retVal int, retRune rune, err error) {\n\ts := skiplist{r: r}\n\tvar k, prev *knot\n\tvar offset int\n\tvar char rune\n\n\tif k, offset, _, err = s.find(at); err != nil {\n\t\treturn -1, -1, err\n\t}\n\n\tchar, _ = utf8.DecodeRune(k.data[offset:])\n\tif fn(char) {\n\t\treturn at, char, nil\n\t}\n\n\t// if it's within this block, then return immediately, otherwise, get previous block\n\tvar befores, start int\n\tsize := 1\n\tfor end := len(k.data[:offset]); end > start; end -= size {\n\t\tchar, size = utf8.DecodeLastRune(k.data[start:end])\n\t\tif fn(char) {\n\t\t\treturn at - befores, char, nil\n\t\t}\n\t\tbefores += size\n\t}\n\n\t// otherwise we'd have to iterate thru the blocks\n\tbefores = offset + 1\n\tfor {\n\t\tfor it := &r.Head; it != nil; it = it.nexts[0].knot {\n\t\t\tif it == k {\n\t\t\t\t// if prev == nil {\n\t\t\t\t// \tprev = it\n\t\t\t\t// }\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprev = it\n\t\t}\n\t\tstart = 0\n\t\tsize = 1\n\t\tfor end := len(prev.data) - 1; end > start; end -= size {\n\t\t\tchar, size = utf8.DecodeLastRune(prev.data[start:end])\n\t\t\tif fn(char) {\n\t\t\t\treturn at - befores, char, nil\n\t\t\t}\n\t\t\tbefores += size\n\t\t}\n\t\tk = prev\n\t\t// if k == &r.Head {\n\t\t// \tbreak\n\t\t// }\n\t}\n\treturn\n}", "func row() (*html.Node, error) {\n\tdoc, err := htmlquery.Parse(strings.NewReader(tableSample))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trow, err := htmlquery.Query(doc, \"//tr\")\n\tif row != nil || err != nil {\n\t\treturn row, err\n\t}\n\treturn nil, nil\n}", "func (t *Tensor) GetRow(idx int64) *Tensor {\n\tif len(t.Dims) != 2 || idx >= t.Dims[0] {\n\t\treturn nil\n\t}\n\tbegin := t.Dims[1] * idx\n\treturn t.GetSubTensor(begin, t.Dims[1])\n}", "func (o TableRangePartitioningRangePtrOutput) Start() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TableRangePartitioningRange) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Start\n\t}).(pulumi.IntPtrOutput)\n}", "func (o Int64RangeMatchOutput) RangeStart() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Int64RangeMatch) *string { return v.RangeStart }).(pulumi.StringPtrOutput)\n}", "func (pi *PixelIterator) GetIteratorRow() int {\n\tret := int(C.PixelGetIteratorRow(pi.pi))\n\truntime.KeepAlive(pi)\n\treturn ret\n}", "func (t *Table) Row(i int) []interface{} {\n\tif i < 0 || i >= len(t.r) {\n\t\treturn nil\n\t} else {\n\t\treturn t.r[i].row(t.header.w)\n\t}\n}", "func (o *Cell) GetPrevX() int { return o.X }", "func (o Int64RangeMatchPtrOutput) RangeStart() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Int64RangeMatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RangeStart\n\t}).(pulumi.StringPtrOutput)\n}", "func (tv *TextView) WordBefore(tp TextPos) *TextBufEdit {\n\ttxt := tv.Buf.Line(tp.Ln)\n\tch := tp.Ch\n\tch = ints.MinInt(ch, len(txt))\n\tst := ch\n\tfor i := ch - 1; i >= 0; i-- {\n\t\tif i == 0 { // start of line\n\t\t\tst = 0\n\t\t\tbreak\n\t\t}\n\t\tr1 := txt[i]\n\t\tr2 := txt[i-1]\n\t\tif tv.IsWordBreak(r1, r2) {\n\t\t\tst = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\tif st != ch {\n\t\treturn tv.Buf.Region(TextPos{Ln: tp.Ln, Ch: st}, tp)\n\t}\n\treturn nil\n}", "func (m *sparse) Rows() func() *sparseRow {\n\ti := 0\n\tr := &sparseRow{}\n\n\treturn func() *sparseRow {\n\t\tif i == (len(m.ptr) - 1) {\n\t\t\treturn nil\n\t\t}\n\n\t\tstart := m.ptr[i]\n\t\tend := m.ptr[i+1]\n\n\t\tr.index = i\n\t\tr.ind = m.ind[start:end]\n\t\tr.val = m.val[start:end]\n\t\ti++\n\n\t\treturn r\n\t}\n}", "func GetRow(rowIndex int) []int {\n\tif rowIndex == 0 {\n\t\treturn []int{1}\n\t}\n\toldRow := GetRow(rowIndex - 1)\n\tnthRow := make([]int, rowIndex+1)\n\tnthRow[0] = 1\n\tfor i := 1; i < rowIndex; i++ {\n\t\tnthRow[i] = oldRow[i] + oldRow[i-1]\n\t}\n\tnthRow[rowIndex] = 1\n\treturn nthRow\n}", "func (r *baseNsRange) Start() int { return r.start }", "func extractBeforeSeparator(s string) string {\n\tloc := rtrwSeparatorRegex.FindStringIndex(s)\n\tif loc == nil {\n\t\treturn s\n\t} else {\n\t\treturn s[0:loc[0]]\n\t}\n}", "func (ref *UIElement) RowIndexRange() Range {\n\tret, _ := ref.RangeAttr(RowIndexRangeAttribute)\n\treturn ret\n}", "func StartedAtLT(v time.Time) predicate.Session {\n\treturn predicate.Session(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldStartedAt), v))\n\t})\n}", "func (tb *TextBuf) CommentStart(ln int) int {\n\tif !tb.IsValidLine(ln) {\n\t\treturn -1\n\t}\n\tcomst, _ := tb.Opts.CommentStrs()\n\tif comst == \"\" {\n\t\treturn -1\n\t}\n\ttb.LinesMu.RLock()\n\tdefer tb.LinesMu.RUnlock()\n\treturn runes.Index(tb.Line(ln), []rune(comst))\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 (m Matrix) RowAt(rowIndex int) ([]float64, error) {\n\tif rowIndex >= m.RowCount {\n\t\treturn nil, errors.New(\"given row index is out of range in given matrix\")\n\t}\n\treturn m.Matrix[rowIndex], nil\n}", "func (r *FlakeRegion) StartedAtOrBefore(t int) float64 {\n\tif t > r.First {\n\t\treturn 1\n\t}\n\tdist := GeometricDist{P: r.FailureProbability}\n\treturn 1 - dist.CDF(r.First-t-1)\n}", "func (h *HandlersApp01sqVendor) RowPrev(w http.ResponseWriter, r *http.Request) {\n\tvar rcd App01sqVendor.App01sqVendor\n\tvar err error\n\tvar i int\n\tvar key string\n\n\tlog.Printf(\"hndlrVendor.RowPrev(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Get the prior key(s).\n\ti = 0\n\tkey = r.FormValue(fmt.Sprintf(\"key%d\", i))\n\trcd.Id, _ = strconv.ParseInt(key, 0, 64)\n\n\ti++\n\n\t// Get the next row and display it.\n\terr = h.db.RowPrev(&rcd)\n\tif err != nil {\n\n\t\tlog.Printf(\"...end Vendor.RowNext(Error:400) - No Key\\n\")\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\th.RowDisplay(w, &rcd, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.RowPrev()\\n\")\n\n}", "func (f *fragment) rows(start uint64, filters ...rowFilter) []uint64 {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\treturn f.unprotectedRows(start, filters...)\n}", "func (o TableRangePartitioningRangeOutput) Start() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TableRangePartitioningRange) int { return v.Start }).(pulumi.IntOutput)\n}", "func commentStartIndex(line string) int {\n\treturn commentStartRegex.FindStringIndex(line)[0]\n}", "func (xs *Sheet) InsertRow(rowFirst int, rowLast int) int {\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetInsertRowW\").\n\t\tCall(xs.self, I(rowFirst), I(rowLast))\n\treturn int(tmp)\n}", "func (db *Database) NewIteratorWithStart(start []byte) database.Iterator {\n\treturn &iter{\n\t\tdb: db,\n\t\tIterator: db.DB.NewIterator(&util.Range{Start: start}, nil),\n\t}\n}", "func (t *Table) selPrev() {\r\n\r\n\t// If selected row is first, nothing to do\r\n\tsel := t.rowCursor\r\n\tif sel == 0 {\r\n\t\treturn\r\n\t}\r\n\t// If no selected row, selects last visible row\r\n\tif sel < 0 {\r\n\t\tt.rowCursor = t.lastRow\r\n\t\tt.recalc()\r\n\t\tt.Dispatch(OnChange, nil)\r\n\t\treturn\r\n\t}\r\n\t// Selects previous row and selects previous\r\n\tprev := sel - 1\r\n\tt.rowCursor = prev\r\n\r\n\t// Scroll up if necessary\r\n\tif prev < t.firstRow && t.firstRow > 0 {\r\n\t\tt.scrollUp(1)\r\n\t} else {\r\n\t\tt.recalc()\r\n\t}\r\n\tt.Dispatch(OnChange, nil)\r\n}", "func (xs *Sheet) InsertRowAndKeepRanges(rowFirst int, rowLast int) int {\n\ttmp, _, _ := xs.xb.lib.NewProc(\"xlSheetInsertRowAndKeepRangesW\").\n\t\tCall(xs.self, I(rowFirst), I(rowLast))\n\treturn int(tmp)\n}", "func (m *Matrix) Row(cur int) []qrvalue {\n\tif cur >= m.height || cur < 0 {\n\t\treturn nil\n\t}\n\n\tcol := make([]qrvalue, m.height)\n\tfor w := 0; w < m.width; w++ {\n\t\tcol[w] = m.mat[w][cur]\n\t}\n\treturn col\n}", "func (q *QQwry) getMiddleOffset(start uint32, end uint32) uint32 {\n\trecords := ((end - start) / INDEX_LEN) >> 1\n\treturn start + records*INDEX_LEN\n}", "func (h *HandlersApp01sqVendor) RowFirst(w http.ResponseWriter, r *http.Request) {\n\tvar rcd App01sqVendor.App01sqVendor\n\tvar err error\n\n\tlog.Printf(\"hndlrVendor.RowFirst(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\n\t\tlog.Printf(\"...end hndlrVendor.RowFirst(Error:405) - Not GET\\n\")\n\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Get the next row and display it.\n\terr = h.db.RowFirst(&rcd)\n\tif err != nil {\n\n\t\tlog.Printf(\"...end hndlrVendor.RowFirst(Error:400) - No Key\\n\")\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\th.RowDisplay(w, &rcd, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.RowFirst()\\n\")\n\n}", "func GetRegionKeyChromStartPos(rk uint64) uint64 {\n\treturn uint64(C.get_regionkey_chrom_startpos(C.uint64_t(rk)))\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) HeaderRowRange()(*ItemItemsItemWorkbookTablesItemHeaderRowRangeRequestBuilder) {\n return NewItemItemsItemWorkbookTablesItemHeaderRowRangeRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (logSeeker *LogSeeker) BSearchBegin(begin int64, end int64, startValue string, fieldSep rune, fieldIndex int, jsonField string) (offset int64, err error) {\n\n\tif begin > end {\n\t\t//not found\n\t\treturn -1, nil\n\t}\n\n\toffset, err = logSeeker.SeekLinePosition(begin)\n\n\tfield, err := logSeeker.readLineField(offset, fieldSep, fieldIndex, jsonField)\n\n\tif startValue < field {\n\t\t//found\n\t\treturn 0, nil\n\t}\n\n\toffset, err = logSeeker.SeekLinePosition(end - 2)\n\n\tfield, err = logSeeker.readLineField(offset, fieldSep, fieldIndex, jsonField)\n\n\t// fmt.Printf(\"scan end %d-%d ,%s %d\\n\", end, offset, field, fieldIndex)\n\n\tif startValue > field {\n\t\t//not found\n\t\treturn -1, nil\n\t}\n\n\tmid := (begin + end) / 2\n\n\tvar lastOffset int64 = -1\n\n\tfor end > begin {\n\n\t\toffset, err = logSeeker.SeekLinePosition(mid)\n\t\t// fmt.Printf(\"offset:lastOffset %d %d \\n\", offset, lastOffset)\n\t\tif lastOffset >= 0 && lastOffset == offset {\n\t\t\t// repeat find the same row\n\t\t\tbreak\n\t\t}\n\n\t\tfield, err = logSeeker.readLineField(offset, fieldSep, fieldIndex, jsonField)\n\t\t// fmt.Printf(\"scan-b %s, begin %d, %d mid:%d\\n\", field, begin, end, mid)\n\n\t\tif field < startValue && offset == begin {\n\t\t\treturn\n\t\t}\n\n\t\tif offset == begin {\n\t\t\toffset = lastOffset\n\t\t\treturn\n\t\t}\n\n\t\tif field >= startValue {\n\t\t\tlastOffset = offset\n\t\t\tend = mid\n\t\t} else {\n\t\t\tbegin = mid + 1\n\t\t}\n\n\t\tmid = (begin + end) / 2\n\n\t}\n\treturn lastOffset, nil\n}", "func (fn *formulaFuncs) ROW(argsList *list.List) formulaArg {\n\tif argsList.Len() > 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"ROW requires at most 1 argument\")\n\t}\n\tif argsList.Len() == 1 {\n\t\tif argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {\n\t\t\treturn newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRanges.Front().Value.(cellRange).From.Row))\n\t\t}\n\t\tif argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {\n\t\t\treturn newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRefs.Front().Value.(cellRef).Row))\n\t\t}\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"invalid reference\")\n\t}\n\t_, row, _ := CellNameToCoordinates(fn.cell)\n\treturn newNumberFormulaArg(float64(row))\n}", "func row(k int) int { return k % 4 }", "func (tv *TextView) CursorStartLine() {\n\twupdt := tv.TopUpdateStart()\n\tdefer tv.TopUpdateEnd(wupdt)\n\ttv.ValidateCursor()\n\torg := tv.CursorPos\n\tpos := tv.CursorPos\n\n\tgotwrap := false\n\tif wln := tv.WrappedLines(pos.Ln); wln > 1 {\n\t\tsi, ri, _ := tv.WrappedLineNo(pos)\n\t\tif si > 0 {\n\t\t\tri = 0\n\t\t\tnwc, _ := tv.Renders[pos.Ln].SpanPosToRuneIdx(si, ri)\n\t\t\tpos.Ch = nwc\n\t\t\ttv.CursorPos = pos\n\t\t\ttv.CursorCol = ri\n\t\t\tgotwrap = true\n\t\t}\n\t}\n\tif !gotwrap {\n\t\ttv.CursorPos.Ch = 0\n\t\ttv.CursorCol = tv.CursorPos.Ch\n\t}\n\t// fmt.Printf(\"sol cursorcol: %v\\n\", tv.CursorCol)\n\ttv.SetCursor(tv.CursorPos)\n\ttv.ScrollCursorToLeft()\n\ttv.RenderCursor(true)\n\ttv.CursorSelect(org)\n}", "func firstIndex(sequence []byte, K int, start int, end int) int {\n var j int\n for i:=start; i<end-K+1; i++ {\n for j=i; j<i+K; j++ {\n if sequence[j]!='A' && sequence[j]!='C' && sequence[j]!='G' && sequence[j]!='T' {\n break\n }\n }\n if j==i+K {\n return i\n }\n }\n return -1\n}", "func (c ColDecimal32) Row(i int) Decimal32 {\n\treturn c[i]\n}", "func (pi *PixelIterator) GetCurrentIteratorRow() (pws []*PixelWand) {\n\tnum := C.size_t(0)\n\tpp := C.PixelGetCurrentIteratorRow(pi.pi, &num)\n\tif pp == nil {\n\t\treturn\n\t}\n\tfor i := 0; i < int(num); i++ {\n\t\tcpw := C.get_pw_at(pp, C.size_t(i))\n\t\t// PixelWand is a private pointer, borrowed from the pixel\n\t\t// iterator. We don't want to reference count it. It will\n\t\t// get destroyed by C API when PixelIterator is destroyed.\n\t\tpws = append(pws, &PixelWand{pw: cpw})\n\t}\n\truntime.KeepAlive(pi)\n\treturn\n}", "func (self *TraitPixbuf) GetRowstride() (return__ int) {\n\tvar __cgo__return__ C.int\n\t__cgo__return__ = C.gdk_pixbuf_get_rowstride(self.CPointer)\n\treturn__ = int(__cgo__return__)\n\treturn\n}", "func GetCursorRow() (int, error) {\n\tvar row int\n\tscr := getScreen()\n\tfd := int(scr.output.Fd())\n\toldState, err := term.MakeRaw(fd)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tdefer term.Restore(fd, oldState)\n\n\t// capture keyboard output from echo\n\treader := bufio.NewReader(os.Stdin)\n\n\t// request a \"Report Cursor Position\" response from the device: <ESC>[{ROW};{COLUMN}R\n\t// great resource: http://www.termsys.demon.co.uk/vtansi.htm\n\t_, err = fmt.Fprint(scr.output, \"\\x1b[6n\")\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"unable to get screen position\")\n\t}\n\n\t// capture the response up until the expected \"R\"\n\ttext, err := reader.ReadSlice('R')\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"unable to read stdin\")\n\t}\n\n\t// parse the row and column\n\tif strings.Contains(string(text), \";\") {\n\t\tre := regexp.MustCompile(`\\d+;\\d+`)\n\t\tline := re.FindString(string(text))\n\t\trow, err = strconv.Atoi(strings.Split(line, \";\")[0])\n\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"invalid row value: '%s'\", line)\n\t\t}\n\t} else {\n\t\treturn -1, fmt.Errorf(\"unable to fetch position\")\n\t}\n\n\treturn row, nil\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 (p *PatchModifier) getHunkStart(patchLines []string, lineNumber int) (int, error) {\n\t// find the hunk that we're modifying\n\thunkStart := 0\n\tfor index, line := range patchLines {\n\t\tif strings.HasPrefix(line, \"@@\") {\n\t\t\thunkStart = index\n\t\t}\n\t\tif index == lineNumber {\n\t\t\treturn hunkStart, nil\n\t\t}\n\t}\n\n\treturn 0, errors.New(p.Tr.SLocalize(\"CantFindHunk\"))\n}", "func (mc MultiCursor) MinMaxRow() (minRow, maxRow int) {\n\tminRow = mc.cursors[0].row\n\tmaxRow = mc.cursors[0].row\n\tfor _, cursor := range mc.cursors {\n\t\tif cursor.row < minRow {\n\t\t\tminRow = cursor.row\n\t\t}\n\t\tif cursor.row > maxRow {\n\t\t\tmaxRow = cursor.row\n\t\t}\n\t}\n\treturn minRow, maxRow\n}", "func (root *mTreap) start(mask, match treapIterType) treapIter {\n\tf := treapFilter(mask, match)\n\treturn treapIter{f, root.treap.findMinimal(f)}\n}", "func WorkplaceLT(v string) predicate.User {\n\treturn predicate.User(sql.FieldLT(FieldWorkplace, v))\n}", "func (c *index) SeekFirst(r kv.Retriever) (iter table.IndexIterator, err error) {\n\tupperBound := c.prefix.PrefixNext()\n\tit, err := r.Iter(c.prefix, upperBound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &indexIter{it: it, idx: c, prefix: c.prefix}, nil\n}", "func newRowIterator(ctx *sql.Context, tbl *doltdb.Table, projCols []string, partition *doltTablePartition) (sql.RowIter, error) {\n\tsch, err := tbl.GetSchema(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif schema.IsKeyless(sch) {\n\t\t// would be more optimal to project columns into keyless tables also\n\t\treturn newKeylessRowIterator(ctx, tbl, projCols, partition)\n\t} else {\n\t\treturn newKeyedRowIter(ctx, tbl, projCols, partition)\n\t}\n}", "func getPosForRandImport(rowID int64, sourceID int32, numInstances int) importRandPosition {\n\t// We expect r.pos to increment by numInstances for each row.\n\t// Therefore, assuming that rowID increments by 1 for every row,\n\t// we will initialize the position as rowID * numInstances + sourceID << rowIDBits.\n\trowIDWithMultiplier := int64(numInstances) * rowID\n\tpos := (int64(sourceID) << rowIDBits) ^ rowIDWithMultiplier\n\treturn importRandPosition(pos)\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 moveCursorLeft(positionCursor *int, numberDigits int,listOfNumbers [6]int) {\n\n\tif *positionCursor == 0 { \t\t\t\t\t\t // Scenario 1: position of cursor at the beginning of list\n\n\t\t*positionCursor=numberDigits-1\t\t\t\t // set it to the end\n\n\t\tpositionCursor = &listOfNumbers[numberDigits-1] // sets address of position to be that of the correct element\n\n\t} else {\t\t\t\t\t\t\t\t\t\t // Scenario 2: position of cursor is not at the beginning of list\n\n\t\t*positionCursor--\t\t\t\t\t\t\t // decrease the value of position of the cursor\n\n\t\tvar temp = *positionCursor\t\t\t\t\t // temp variable for position of cursor\n\n\t\tpositionCursor = &listOfNumbers[temp] \t // sets address of position to be that of the correct element\n\t}\n}", "func (m *TuiModel) GetRow() int {\n\treturn int(math.Max(float64(m.mouseEvent.Y-headerHeight), 0)) + m.viewport.YOffset\n}", "func (db *Database) NewIteratorWithStart(start []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(start)\n\treturn &iterator{\n\t\tit: it,\n\t\tdb: db,\n\t}\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 (f *fragment) rowFromStorage(rowID uint64) *Row {\n\t// Only use a subset of the containers.\n\t// NOTE: The start & end ranges must be divisible by container width.\n\t//\n\t// Note that OffsetRange now returns a new bitmap which uses frozen\n\t// containers which will use copy-on-write semantics. The actual bitmap\n\t// and Containers object are new and not shared, but the containers are\n\t// shared.\n\tdata := f.storage.OffsetRange(f.shard*ShardWidth, rowID*ShardWidth, (rowID+1)*ShardWidth)\n\n\trow := &Row{\n\t\tsegments: []rowSegment{{\n\t\t\tdata: data,\n\t\t\tshard: f.shard,\n\t\t\twritable: true,\n\t\t}},\n\t}\n\trow.invalidateCount()\n\n\treturn row\n}", "func (ctx *TestContext) getRowMap(rowIndex int, table *messages.PickleStepArgument_PickleTable) map[string]string {\n\trowHeader := table.Rows[0]\n\tsourceRow := table.Rows[rowIndex]\n\n\trowMap := map[string]string{}\n\tfor i := 0; i < len(rowHeader.Cells); i++ {\n\t\tvalue := sourceRow.Cells[i].Value\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\trowMap[rowHeader.Cells[i].Value] = value\n\t}\n\n\treturn rowMap\n}", "func RepaircostLT(v int) predicate.CarRepairrecord {\n\treturn predicate.CarRepairrecord(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldRepaircost), v))\n\t})\n}", "func (matrix Matrix4) Row(rowIndex int) vector.Vector {\n\tvec := vector.Vector{0, 0, 0, 0}\n\tfor i := range matrix[rowIndex] {\n\t\tvec[i] = matrix[rowIndex][i]\n\t}\n\treturn vec\n}", "func (t *LineTable) findFileLine(entry uint64, filetab, linetab uint32, filenum, line int32, cutab []byte) uint64 {\n\tif filetab == 0 || linetab == 0 {\n\t\treturn 0\n\t}\n\n\tfp := t.pctab[filetab:]\n\tfl := t.pctab[linetab:]\n\tfileVal := int32(-1)\n\tfilePC := entry\n\tlineVal := int32(-1)\n\tlinePC := entry\n\tfileStartPC := filePC\n\tfor t.step(&fp, &filePC, &fileVal, filePC == entry) {\n\t\tfileIndex := fileVal\n\t\tif t.version == ver116 || t.version == ver118 {\n\t\t\tfileIndex = int32(t.binary.Uint32(cutab[fileVal*4:]))\n\t\t}\n\t\tif fileIndex == filenum && fileStartPC < filePC {\n\t\t\t// fileIndex is in effect starting at fileStartPC up to\n\t\t\t// but not including filePC, and it's the file we want.\n\t\t\t// Run the PC table looking for a matching line number\n\t\t\t// or until we reach filePC.\n\t\t\tlineStartPC := linePC\n\t\t\tfor linePC < filePC && t.step(&fl, &linePC, &lineVal, linePC == entry) {\n\t\t\t\t// lineVal is in effect until linePC, and lineStartPC < filePC.\n\t\t\t\tif lineVal == line {\n\t\t\t\t\tif fileStartPC <= lineStartPC {\n\t\t\t\t\t\treturn lineStartPC\n\t\t\t\t\t}\n\t\t\t\t\tif fileStartPC < linePC {\n\t\t\t\t\t\treturn fileStartPC\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlineStartPC = linePC\n\t\t\t}\n\t\t}\n\t\tfileStartPC = filePC\n\t}\n\treturn 0\n}", "func (r *Record) Start() int {\n\treturn r.Pos\n}", "func (f Fetcher) GetStartStopRange (c MyContext) (int, int, error) {\n\tvar start, end int\n\tvar err error\n\n\tstart, err = strconv.Atoi(c.Ctx.Param(\"start\"))\n\tif err != nil {\n\t\treturn start, end, err\n\t}\n\tend, err = strconv.Atoi(c.Ctx.Param(\"end\"))\n\tif err != nil {\n\t\treturn start, end, err\n\t}\n\n\treturn start, end, err\n}", "func (m *Mapper) LineAndColumn(byteOffset int) (line, column int, err error) {\n\tif byteOffset > len(m.content) || byteOffset < 0 {\n\t\terr = errInvalidOffset\n\t\treturn\n\t}\n\tif byteOffset == len(m.content) {\n\t\t// Offset points to end of file.\n\t\tline = len(m.offsets) - 2\n\t\tcolumn = utf8.RuneCountInString(m.content[m.offsets[line]:m.offsets[line+1]])\n\t\treturn\n\t}\n\n\tline = sort.Search(len(m.offsets), func(i int) bool {\n\t\treturn m.offsets[i] > byteOffset\n\t}) - 1\n\n\tlineStartOffset := m.offsets[line]\n\n\tlineText := m.content[m.offsets[line]:m.offsets[line+1]]\n\n\tcolumn = -1\n\tfor lineOffset := range lineText {\n\t\tcolumn++\n\t\tif lineOffset+lineStartOffset >= byteOffset {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (gd *Definition) PointToRowCol(x, y float64) (row, col int) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tif gd.Rotation != 0. {\n\t\tlog.Fatalf(\" Definition.PointToRowCol todo\")\n\t}\n\n\trow = -1\n\tcol = -1\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif y > gd.Norig {\n\t\t\treturn\n\t\t}\n\t\tfor {\n\t\t\trow++\n\t\t\tif row > gd.Nrow {\n\t\t\t\trow = -1 // gd.Nrow +1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif gd.Norig-float64(row+1)*gd.Cwidth <= y {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif x < gd.Eorig {\n\t\t\treturn\n\t\t}\n\t\tfor {\n\t\t\tcol++\n\t\t\tif col > gd.Ncol {\n\t\t\t\tcol = -1 // gd.Ncol +1\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif gd.Eorig+float64(col+1)*gd.Cwidth >= x {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n\treturn\n}", "func (m *Matrix) SepRow(start, end int) (matrix *Matrix) {\n\tmatrix = Copy(m)\n\tif end < start {\n\t\tmatrix.err = errors.New(\"The argument values are invalid\")\n\t\treturn\n\t} else if end > m.row || start < 1 {\n\t\tmatrix.err = errors.New(\"The value are out of matrix\")\n\t\treturn\n\t}\n\ts := (start - 1) * m.column\n\te := (end - 1) * m.column\n\tmatrix = New(end-start+1, m.column, m.matrix[s:e+m.column])\n\treturn\n}", "func (s *Store) lookupPrecedingReplica(key roachpb.RKey) *Replica {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.mu.replicasByKey.LookupPrecedingReplica(context.Background(), key)\n}", "func (validation *Validation) InRow(name string, index int, _validation *Validation) *Validation {\n\treturn validation.merge(fmt.Sprintf(\"%s[%v]\", name, index), _validation)\n}", "func MatchBefore(fset *token.FileSet, readFile ReadFile, end token.Pos, pattern interface{}) (token.Pos, token.Pos, error) {\n\tf := fset.File(end)\n\tcontent, err := readFile(f.Name())\n\tif err != nil {\n\t\treturn token.NoPos, token.NoPos, fmt.Errorf(\"invalid file: %v\", err)\n\t}\n\tposition := f.Position(end)\n\tstartOffset := f.Offset(f.LineStart(position.Line))\n\tendOffset := f.Offset(end)\n\tline := content[startOffset:endOffset]\n\tmatchStart, matchEnd := -1, -1\n\tswitch pattern := pattern.(type) {\n\tcase string:\n\t\tbytePattern := []byte(pattern)\n\t\tmatchStart = bytes.Index(line, bytePattern)\n\t\tif matchStart >= 0 {\n\t\t\tmatchEnd = matchStart + len(bytePattern)\n\t\t}\n\tcase []byte:\n\t\tmatchStart = bytes.Index(line, pattern)\n\t\tif matchStart >= 0 {\n\t\t\tmatchEnd = matchStart + len(pattern)\n\t\t}\n\tcase *regexp.Regexp:\n\t\tmatch := pattern.FindIndex(line)\n\t\tif len(match) > 0 {\n\t\t\tmatchStart = match[0]\n\t\t\tmatchEnd = match[1]\n\t\t}\n\t}\n\tif matchStart < 0 {\n\t\treturn token.NoPos, token.NoPos, nil\n\t}\n\treturn f.Pos(startOffset + matchStart), f.Pos(startOffset + matchEnd), nil\n}", "func (m Matrix3) GetRow(row int) (r Vector3) {\n\tfor i := range r {\n\t\tr[i] = m.At(row, i)\n\t}\n\treturn\n}", "func PositionLT(v int) predicate.QueueItem {\n\treturn predicate.QueueItem(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldPosition), v))\n\t})\n}", "func (c *Cursor) First() {\n\tc.pos = c.start\n}", "func findBlockLineRange(f *ir.Func, block *ir.Block) [2]int {\n\tfuncStr := f.LLString()\n\tblockStr := block.LLString()\n\tpos := strings.Index(funcStr, blockStr)\n\tif pos == -1 {\n\t\tpanic(fmt.Errorf(\"unable to locate contents of basic block %s in contents of function %s\", block.Ident(), f.Ident()))\n\t}\n\tbefore := funcStr[:pos]\n\tstart := 1 + strings.Count(before, \"\\n\")\n\tn := strings.Count(blockStr, \"\\n\")\n\tend := start + n\n\treturn [2]int{start, end}\n}", "func (w *WorkSheet) Row(i int) *Row {\n\trow := w.rows[uint16(i)]\n\tif row != nil {\n\t\trow.wb = w.wb\n\t}\n\treturn row\n}", "func (f *Field) Start() Pos {\n\tif f.Alias != nil {\n\t\treturn f.Alias.Start\n\t}\n\treturn f.Name.Start\n}", "func (f Formatter) FindBeginIndex(content []byte) int {\n\tbeginIndex := bytes.IndexByte(content, beginSymbol[0])\n\ttempIndex := bytes.IndexByte(content, beginSymbol[1])\n\tif beginIndex > tempIndex && tempIndex != -1 {\n\t\tbeginIndex = tempIndex\n\t}\n\treturn beginIndex\n}" ]
[ "0.6097574", "0.6046121", "0.564214", "0.5352695", "0.53002346", "0.5286634", "0.52708083", "0.52110296", "0.51418424", "0.5137238", "0.5119742", "0.5109105", "0.5045511", "0.50126594", "0.49783966", "0.49702695", "0.49633923", "0.49345207", "0.49129394", "0.4888165", "0.48820737", "0.48758253", "0.48711318", "0.48521358", "0.4812771", "0.4807335", "0.48055822", "0.48018658", "0.47844288", "0.47652122", "0.4758277", "0.47540274", "0.47530866", "0.47503212", "0.47453701", "0.47118062", "0.47074866", "0.4703595", "0.47013098", "0.46991053", "0.46967772", "0.46828294", "0.46811676", "0.46792492", "0.4672186", "0.46677798", "0.46664864", "0.46661374", "0.4651515", "0.46495858", "0.46466526", "0.4646054", "0.46449375", "0.4641572", "0.4631355", "0.46262544", "0.46242", "0.46226275", "0.46107867", "0.46033052", "0.45900816", "0.45885825", "0.45869604", "0.4586565", "0.45804048", "0.45756334", "0.45605192", "0.4560074", "0.45595068", "0.4556489", "0.45518994", "0.45441204", "0.45414537", "0.453461", "0.4531621", "0.45293403", "0.45268893", "0.45267493", "0.45250297", "0.4516831", "0.45167175", "0.45116773", "0.45116612", "0.45081466", "0.45064452", "0.44993827", "0.44951376", "0.44856054", "0.44809517", "0.44782764", "0.44703853", "0.44675437", "0.44541556", "0.44511148", "0.44503227", "0.4447393", "0.44412762", "0.44373405", "0.4436211", "0.44274104" ]
0.8255374
0
XXX_OneofWrappers is for the internal use of the proto package.
func (*CampaignExtensionSettingOperation) XXX_OneofWrappers() []interface{} { return []interface{}{ (*CampaignExtensionSettingOperation_Create)(nil), (*CampaignExtensionSettingOperation_Update)(nil), (*CampaignExtensionSettingOperation_Remove)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*DRB) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_NotUsed)(nil),\n\t\t(*DRB_Rohc)(nil),\n\t\t(*DRB_UplinkOnlyROHC)(nil),\n\t}\n}", "func (*Interface) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t\t(*Interface_Gre)(nil),\n\t\t(*Interface_Gtpu)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*GroupMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GroupMod_L2Iface)(nil),\n\t\t(*GroupMod_L3Unicast)(nil),\n\t\t(*GroupMod_MplsIface)(nil),\n\t\t(*GroupMod_MplsLabel)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_NewRoundStep)(nil),\n\t\t(*Message_NewValidBlock)(nil),\n\t\t(*Message_Proposal)(nil),\n\t\t(*Message_ProposalPol)(nil),\n\t\t(*Message_BlockPart)(nil),\n\t\t(*Message_Vote)(nil),\n\t\t(*Message_HasVote)(nil),\n\t\t(*Message_VoteSetMaj23)(nil),\n\t\t(*Message_VoteSetBits)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Init)(nil),\n\t\t(*Message_File)(nil),\n\t\t(*Message_Resize)(nil),\n\t\t(*Message_Signal)(nil),\n\t}\n}", "func (*Example) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Example_A)(nil),\n\t\t(*Example_BJk)(nil),\n\t}\n}", "func (*ExampleMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ExampleMsg_SomeString)(nil),\n\t\t(*ExampleMsg_SomeNumber)(nil),\n\t\t(*ExampleMsg_SomeBool)(nil),\n\t}\n}", "func (*WALMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*WALMessage_EventDataRoundState)(nil),\n\t\t(*WALMessage_MsgInfo)(nil),\n\t\t(*WALMessage_TimeoutInfo)(nil),\n\t\t(*WALMessage_EndHeight)(nil),\n\t}\n}", "func (*Modulation) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Modulation_Lora)(nil),\n\t\t(*Modulation_Fsk)(nil),\n\t\t(*Modulation_LrFhss)(nil),\n\t}\n}", "func (*TestVersion2) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion2_E)(nil),\n\t\t(*TestVersion2_F)(nil),\n\t}\n}", "func (*TestVersion1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion1_E)(nil),\n\t\t(*TestVersion1_F)(nil),\n\t}\n}", "func (*CodebookType_Type1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookType_Type1_TypeI_SinglePanel)(nil),\n\t\t(*CodebookType_Type1_TypeI_MultiPanell)(nil),\n\t}\n}", "func (*DRB_ToAddMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_ToAddMod_Eps_BearerIdentity)(nil),\n\t\t(*DRB_ToAddMod_Sdap_Config)(nil),\n\t}\n}", "func (*TestVersion3) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion3_E)(nil),\n\t\t(*TestVersion3_F)(nil),\n\t}\n}", "func (*Bitmaps) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bitmaps_OneSlot)(nil),\n\t\t(*Bitmaps_TwoSlots)(nil),\n\t\t(*Bitmaps_N2)(nil),\n\t\t(*Bitmaps_N4)(nil),\n\t\t(*Bitmaps_N5)(nil),\n\t\t(*Bitmaps_N8)(nil),\n\t\t(*Bitmaps_N10)(nil),\n\t\t(*Bitmaps_N20)(nil),\n\t\t(*Bitmaps_N40)(nil),\n\t}\n}", "func (*Bit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bit_DecimalValue)(nil),\n\t\t(*Bit_LongValue)(nil),\n\t}\n}", "func (*SeldonMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SeldonMessage_Data)(nil),\n\t\t(*SeldonMessage_BinData)(nil),\n\t\t(*SeldonMessage_StrData)(nil),\n\t\t(*SeldonMessage_JsonData)(nil),\n\t\t(*SeldonMessage_CustomData)(nil),\n\t}\n}", "func (*TestVersionFD1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersionFD1_E)(nil),\n\t\t(*TestVersionFD1_F)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Pubkey)(nil),\n\t\t(*Message_EncK)(nil),\n\t\t(*Message_Mta)(nil),\n\t\t(*Message_Delta)(nil),\n\t\t(*Message_ProofAi)(nil),\n\t\t(*Message_CommitViAi)(nil),\n\t\t(*Message_DecommitViAi)(nil),\n\t\t(*Message_CommitUiTi)(nil),\n\t\t(*Message_DecommitUiTi)(nil),\n\t\t(*Message_Si)(nil),\n\t}\n}", "func (*TestUnit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestUnit_GceTestCfg)(nil),\n\t\t(*TestUnit_HwTestCfg)(nil),\n\t\t(*TestUnit_MoblabVmTestCfg)(nil),\n\t\t(*TestUnit_TastVmTestCfg)(nil),\n\t\t(*TestUnit_VmTestCfg)(nil),\n\t}\n}", "func (*Tag) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tag_DecimalValue)(nil),\n\t\t(*Tag_LongValue)(nil),\n\t\t(*Tag_StringValue)(nil),\n\t}\n}", "func (*Record) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Record_Local_)(nil),\n\t\t(*Record_Ledger_)(nil),\n\t\t(*Record_Multi_)(nil),\n\t\t(*Record_Offline_)(nil),\n\t}\n}", "func (*GeneratedObject) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GeneratedObject_DestinationRule)(nil),\n\t\t(*GeneratedObject_EnvoyFilter)(nil),\n\t\t(*GeneratedObject_ServiceEntry)(nil),\n\t\t(*GeneratedObject_VirtualService)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_Deal)(nil),\n\t\t(*Packet_Response)(nil),\n\t\t(*Packet_Justification)(nil),\n\t}\n}", "func (*Response) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Response_ImageVersion)(nil),\n\t\t(*Response_ErrorDescription)(nil),\n\t}\n}", "func (*FlowMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FlowMod_Vlan)(nil),\n\t\t(*FlowMod_TermMac)(nil),\n\t\t(*FlowMod_Mpls1)(nil),\n\t\t(*FlowMod_Unicast)(nil),\n\t\t(*FlowMod_Bridging)(nil),\n\t\t(*FlowMod_Acl)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*P4Data) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*P4Data_Bitstring)(nil),\n\t\t(*P4Data_Varbit)(nil),\n\t\t(*P4Data_Bool)(nil),\n\t\t(*P4Data_Tuple)(nil),\n\t\t(*P4Data_Struct)(nil),\n\t\t(*P4Data_Header)(nil),\n\t\t(*P4Data_HeaderUnion)(nil),\n\t\t(*P4Data_HeaderStack)(nil),\n\t\t(*P4Data_HeaderUnionStack)(nil),\n\t\t(*P4Data_Enum)(nil),\n\t\t(*P4Data_Error)(nil),\n\t\t(*P4Data_EnumValue)(nil),\n\t}\n}", "func (*SSB_ConfigMobility) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SSB_ConfigMobility_ReleaseSsb_ToMeasure)(nil),\n\t\t(*SSB_ConfigMobility_SetupSsb_ToMeasure)(nil),\n\t}\n}", "func (*SpCellConfig) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SpCellConfig_ReleaseRlf_TimersAndConstants)(nil),\n\t\t(*SpCellConfig_SetupRlf_TimersAndConstants)(nil),\n\t}\n}", "func (*ServerMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerMessage_State)(nil),\n\t\t(*ServerMessage_Runtime)(nil),\n\t\t(*ServerMessage_Event)(nil),\n\t\t(*ServerMessage_Response)(nil),\n\t\t(*ServerMessage_Notice)(nil),\n\t}\n}", "func (*ParaP2PSubMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ParaP2PSubMsg_CommitTx)(nil),\n\t\t(*ParaP2PSubMsg_SyncMsg)(nil),\n\t}\n}", "func (*ServerAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerAuctionMessage_Challenge)(nil),\n\t\t(*ServerAuctionMessage_Success)(nil),\n\t\t(*ServerAuctionMessage_Error)(nil),\n\t\t(*ServerAuctionMessage_Prepare)(nil),\n\t\t(*ServerAuctionMessage_Sign)(nil),\n\t\t(*ServerAuctionMessage_Finalize)(nil),\n\t\t(*ServerAuctionMessage_Account)(nil),\n\t}\n}", "func (*Body) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Body_AsBytes)(nil),\n\t\t(*Body_AsString)(nil),\n\t}\n}", "func (*TagField) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TagField_DoubleValue)(nil),\n\t\t(*TagField_StringValue)(nil),\n\t\t(*TagField_BoolValue)(nil),\n\t\t(*TagField_TimestampValue)(nil),\n\t\t(*TagField_EnumValue_)(nil),\n\t}\n}", "func (*DatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*GatewayMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GatewayMsg_Demand)(nil),\n\t\t(*GatewayMsg_Supply)(nil),\n\t\t(*GatewayMsg_Target)(nil),\n\t\t(*GatewayMsg_Mbus)(nil),\n\t\t(*GatewayMsg_MbusMsg)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*DataType) XXX_OneofWrappers() []interface{} {\r\n\treturn []interface{}{\r\n\t\t(*DataType_ListElementType)(nil),\r\n\t\t(*DataType_StructType)(nil),\r\n\t\t(*DataType_TimeFormat)(nil),\r\n\t}\r\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Prepare)(nil),\n\t\t(*Message_Promise)(nil),\n\t\t(*Message_Accept)(nil),\n\t\t(*Message_Accepted)(nil),\n\t\t(*Message_Alert)(nil),\n\t}\n}", "func (*Test) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Test_Get)(nil),\n\t\t(*Test_Create)(nil),\n\t\t(*Test_Set)(nil),\n\t\t(*Test_Update)(nil),\n\t\t(*Test_UpdatePaths)(nil),\n\t\t(*Test_Delete)(nil),\n\t\t(*Test_Query)(nil),\n\t\t(*Test_Listen)(nil),\n\t}\n}", "func (*BWP_DownlinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_DownlinkCommon_ReleasePdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_ReleasePdsch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdsch_ConfigCommon)(nil),\n\t}\n}", "func (*DownlinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DownlinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_FskModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_ImmediatelyTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_DelayTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_GpsEpochTimingInfo)(nil),\n\t}\n}", "func (*RpcMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RpcMessage_RequestHeader)(nil),\n\t\t(*RpcMessage_ResponseHeader)(nil),\n\t}\n}", "func (*Domain_Attribute) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Domain_Attribute_BoolValue)(nil),\n\t\t(*Domain_Attribute_IntValue)(nil),\n\t}\n}", "func (*CellStatusResp) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusResp_CellStatus)(nil),\n\t\t(*CellStatusResp_ErrorMsg)(nil),\n\t}\n}", "func (*ClientAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ClientAuctionMessage_Commit)(nil),\n\t\t(*ClientAuctionMessage_Subscribe)(nil),\n\t\t(*ClientAuctionMessage_Accept)(nil),\n\t\t(*ClientAuctionMessage_Reject)(nil),\n\t\t(*ClientAuctionMessage_Sign)(nil),\n\t\t(*ClientAuctionMessage_Recover)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*Replay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Replay_Http)(nil),\n\t\t(*Replay_Sqs)(nil),\n\t\t(*Replay_Amqp)(nil),\n\t\t(*Replay_Kafka)(nil),\n\t}\n}", "func (*ReportConfigInterRAT) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReportConfigInterRAT_Periodical)(nil),\n\t\t(*ReportConfigInterRAT_EventTriggered)(nil),\n\t\t(*ReportConfigInterRAT_ReportCGI)(nil),\n\t}\n}", "func (*Class) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Class_PerInstance)(nil),\n\t\t(*Class_Lumpsum)(nil),\n\t}\n}", "func (*OneOfMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OneOfMessage_BinaryValue)(nil),\n\t\t(*OneOfMessage_StringValue)(nil),\n\t\t(*OneOfMessage_BooleanValue)(nil),\n\t\t(*OneOfMessage_IntValue)(nil),\n\t\t(*OneOfMessage_Int64Value)(nil),\n\t\t(*OneOfMessage_DoubleValue)(nil),\n\t\t(*OneOfMessage_FloatValue)(nil),\n\t\t(*OneOfMessage_MsgValue)(nil),\n\t}\n}", "func (*ReceiveReply) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReceiveReply_Record_)(nil),\n\t\t(*ReceiveReply_LiiklusEventRecord_)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t\t(*ServiceSpec_ReplicatedJob)(nil),\n\t\t(*ServiceSpec_GlobalJob)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_PexRequest)(nil),\n\t\t(*Message_PexAddrs)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*ChangeResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ChangeResponse_Ok)(nil),\n\t\t(*ChangeResponse_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*RequestCreateGame) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RequestCreateGame_LocalMap)(nil),\n\t\t(*RequestCreateGame_BattlenetMapName)(nil),\n\t}\n}", "func (*CellStatusReq) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusReq_IsPlayer)(nil),\n\t\t(*CellStatusReq_CellStatus)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Request)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*CreateDatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CreateDatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*InputMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InputMessage_Init)(nil),\n\t\t(*InputMessage_Data)(nil),\n\t}\n}", "func (*UplinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*UplinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*UplinkTXInfo_FskModulationInfo)(nil),\n\t\t(*UplinkTXInfo_LrFhssModulationInfo)(nil),\n\t}\n}", "func (*APool) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*APool_DisableHealthCheck)(nil),\n\t\t(*APool_HealthCheck)(nil),\n\t}\n}", "func (*BWP_UplinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_UplinkCommon_ReleaseRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePucch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPucch_ConfigCommon)(nil),\n\t}\n}", "func (*M) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_OneofInt32)(nil),\n\t\t(*M_OneofInt64)(nil),\n\t}\n}", "func (*LoadParams) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*LoadParams_ClosedLoop)(nil),\n\t\t(*LoadParams_Poisson)(nil),\n\t}\n}", "func (*M_Submessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_Submessage_SubmessageOneofInt32)(nil),\n\t\t(*M_Submessage_SubmessageOneofInt64)(nil),\n\t}\n}", "func (*TestnetPacketData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestnetPacketData_NoData)(nil),\n\t\t(*TestnetPacketData_FooPacket)(nil),\n\t}\n}", "func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoEightOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_PacketPing)(nil),\n\t\t(*Packet_PacketPong)(nil),\n\t\t(*Packet_PacketMsg)(nil),\n\t}\n}", "func (*MetricsData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MetricsData_BoolValue)(nil),\n\t\t(*MetricsData_StringValue)(nil),\n\t\t(*MetricsData_Int64Value)(nil),\n\t\t(*MetricsData_DoubleValue)(nil),\n\t\t(*MetricsData_DistributionValue)(nil),\n\t}\n}", "func (*InstructionResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InstructionResponse_Register)(nil),\n\t\t(*InstructionResponse_ProcessBundle)(nil),\n\t\t(*InstructionResponse_ProcessBundleProgress)(nil),\n\t\t(*InstructionResponse_ProcessBundleSplit)(nil),\n\t\t(*InstructionResponse_FinalizeBundle)(nil),\n\t}\n}", "func (*FieldType) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FieldType_PrimitiveType_)(nil),\n\t\t(*FieldType_EnumType_)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*Tracing) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tracing_Zipkin_)(nil),\n\t\t(*Tracing_Lightstep_)(nil),\n\t\t(*Tracing_Datadog_)(nil),\n\t\t(*Tracing_Stackdriver_)(nil),\n\t}\n}", "func (*DynamicReplay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DynamicReplay_AuthRequest)(nil),\n\t\t(*DynamicReplay_AuthResponse)(nil),\n\t\t(*DynamicReplay_OutboundMessage)(nil),\n\t\t(*DynamicReplay_ReplayMessage)(nil),\n\t}\n}" ]
[ "0.8822406", "0.8802782", "0.8744387", "0.8744387", "0.8744387", "0.8744387", "0.8718898", "0.8718898", "0.8715439", "0.871463", "0.8701507", "0.8701507", "0.8700693", "0.8688847", "0.8680149", "0.8676449", "0.86735517", "0.86709", "0.8667012", "0.8652376", "0.8647903", "0.8639938", "0.86350936", "0.86337095", "0.8632409", "0.86293143", "0.86182773", "0.8615037", "0.86130875", "0.8608868", "0.8604991", "0.85999936", "0.8592669", "0.85904926", "0.8585885", "0.8585885", "0.8585885", "0.85813594", "0.85794765", "0.8579175", "0.8572109", "0.8565196", "0.8564467", "0.85633004", "0.85603684", "0.85602015", "0.85569656", "0.855515", "0.8547816", "0.8547816", "0.8547816", "0.85453683", "0.8544673", "0.85443664", "0.85440636", "0.8543363", "0.8541551", "0.8540363", "0.8539645", "0.85379696", "0.8535508", "0.8535508", "0.8535508", "0.8535508", "0.8535508", "0.8535508", "0.85278064", "0.85237384", "0.85195273", "0.8517181", "0.85165817", "0.85163164", "0.85145897", "0.85124683", "0.85124683", "0.85124683", "0.85124683", "0.8511987", "0.85118794", "0.85064226", "0.85042953", "0.8502699", "0.85017544", "0.8498517", "0.8493939", "0.8492558", "0.84908164", "0.8489719", "0.8488209", "0.8486931", "0.8486458", "0.8485267", "0.84835654", "0.84834564", "0.84807646", "0.84807163", "0.84757465", "0.84757465", "0.84757465", "0.84733397", "0.84719443" ]
0.0
-1
sendRequest sends a HTTP request to the macaddress API.
func (c *Client) sendRequest(method, term string, body io.Reader) (*http.Response, error) { // Compose URL rel := &url.URL{} targetURL := c.BaseURL.ResolveReference(rel) // Write body var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) err := json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } } // New HTTP GET request req, err := http.NewRequest(method, targetURL.String(), body) if err != nil { return nil, err } if body != nil { req.Header.Set("Content-Type", "application/json") } req.Header.Set("Accept", "application/json") // Add api key to query if c.APIKey != "" { q := url.Values{} q.Add("apiKey", c.APIKey) q.Add("output", c.Output) q.Add("search", term) req.URL.RawQuery = q.Encode() } // log.Printf("Doing request: %s", targetURL.String()) return (c.httpClient).Do(req) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *BitcoinClient) sendRequest(req *http.Request) (*http.Response, error) {\n\tres, err := b.Client.Do(req)\n\tif err != nil {\n\t\tlog.Println(ErrUnresponsive)\n\t\treturn nil, ErrUnresponsive\n\t}\n\n\treturn res, nil\n}", "func sendRequest(c net.Conn, mti string) {\n\tconnectionId := c.RemoteAddr().String()\n\n\tpayload := createRequest(mti)\n\trequest := fmt.Sprintf(\"%s:%s\\n\", mti, payload)\n\n\tlog.Printf(\"SEND[%s] length=%d, request=%s\", connectionId, len(request), request)\n\tc.Write([]byte(string(request)))\n}", "func SendRequest(m, u string, h map[string]string) (*http.Response, []byte, error) {\n\treq, err := CreateRequest(m, u, h)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\thttpClient := &http.Client{Timeout: time.Second * 10}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\treturn resp, body, nil\n}", "func sendRequest(config Configuration, payload []byte, url string) {\n\tfmt.Println(\"Sending request to remote...\")\n\tclient := &http.Client{}\n\trequest, err := http.NewRequest(\"POST\", url, strings.NewReader(string(payload)))\n\trequest.SetBasicAuth(config.Login, config.Password)\n\tresp, err := client.Do(request)\n\n\tif err != nil {\n\t\tfmt.Println(\"Request connection error!\")\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Request sent. Status:\", resp.Status)\n}", "func sendRequest(endpoint string, params map[string]string) ([]byte, error) {\n\turl, err := encodeRequest(endpoint, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tglog.V(2).Infof(\"Sending request to %s\", url)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed getting response from %s: %v\", url, err)\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tglog.Errorf(\"Error reading the response %v: %v\", resp, err)\n\t\treturn nil, err\n\t}\n\tglog.V(4).Infof(\"Received response: %s\", string(body))\n\treturn body, nil\n}", "func (j Jumio) sendRequest(request *Request) (response *Response, errorCode *int, err error) {\n\tbody, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\theaders := j.headers()\n\theaders[\"Content-Type\"] = contentType\n\theaders[\"Content-Length\"] = fmt.Sprintf(\"%d\", len(body))\n\n\tstatusCode, resp, err := http.Post(j.baseURL+performNetverifyEndpoint, headers, body)\n\tif err != nil {\n\t\treturn\n\t}\n\tif statusCode != stdhttp.StatusOK {\n\t\terrorCode = &statusCode\n\t\te := ErrorResponse{}\n\t\tif err = json.Unmarshal(resp, &e); err != nil {\n\t\t\terr = errors.New(\"http error\")\n\t\t\treturn\n\t\t}\n\t\terr = e\n\t\treturn\n\t}\n\n\tresponse = &Response{}\n\terr = json.Unmarshal(resp, response)\n\n\treturn\n}", "func (url *URL) SendRequest() (*Request, error) {\n\tresp, err := http.Get(url.Address)\n\treq := new(Request)\n\treq.UrlId = url.ID\n\tif err != nil {\n\t\treturn req, err\n\t}\n\treq.Result = resp.StatusCode\n\treturn req, nil\n}", "func (self *BlobReplicator) SendRequest(hash SHA256, addr string) {\n\tm := self.NewGetBlobMessage(hash)\n\tc := self.d.Pool.Pool.Addresses[addr]\n\tif c == nil {\n\t\tlog.Panic(\"ERROR: Address does not exist\")\n\t}\n\tself.d.Pool.Pool.SendMessage(c, m)\n}", "func SendRequest(cta []byte) int {\n\tr, err := http.Get(SiteURL + hex.EncodeToString(cta))\n\tif err != nil {\n\t\tfmt.Printf(\"Err: %s\\n\", err.Error())\n\t}\n\n\t// fmt.Printf(\"%x: %d\\n\", cta, r.StatusCode)\n\treturn r.StatusCode\n}", "func (emailHunter *EmailHunter) sendRequest(formValues url.Values, emailHunterURL string) (*http.Response, error) {\n\tformValues.Set(\"api_key\", emailHunter.APIKey)\n\treq, err := http.NewRequest(\"GET\", emailHunterURL, strings.NewReader(formValues.Encode()))\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tresp, err := emailHunter.HTTPClient.Do(req)\n\n\treturn resp, err\n}", "func (mc *MockClient) SendRequest(Method, Url string, bdy io.Reader, hdr http.Header, cookies []*http.Cookie) (*http.Response, error) {\n\tresponse, ok := mc.getResponse(Method, Url)\n\tif !ok {\n\t\t//return nil, errors.New(\"No Mock data for given Method+Url\")\n\t\treturn nil, fmt.Errorf(\"No Mock data for %s\", Method+Url)\n\t}\n\treturn &response, nil\n}", "func (c *Client) sendRequest(\n\tmethod, URL string,\n\treqReader0 io.Reader,\n\tlength int64,\n\theaders http.Header,\n\texpectedStatus []int,\n\tlogger logging.Logger,\n) (*http.Response, error) {\n\treqReader, err := seekable(reqReader0, length)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawResp, err := c.sendRateLimitedRequest(method, URL, headers, reqReader, length, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfoundStatus := false\n\tif len(expectedStatus) == 0 {\n\t\texpectedStatus = []int{http.StatusOK}\n\t}\n\tfor _, status := range expectedStatus {\n\t\tif rawResp.StatusCode == status {\n\t\t\tfoundStatus = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !foundStatus && len(expectedStatus) > 0 {\n\t\terr = handleError(URL, rawResp)\n\t\trawResp.Body.Close()\n\t\treturn nil, err\n\t}\n\treturn rawResp, err\n}", "func sendRequest(data url.Values, link string) ([]byte, error) {\n\t//Create request\n\treq, err := http.NewRequest(\"POST\", link, strings.NewReader(data.Encode()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Set headers of HTTP request\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\treq.Header.Add(\"Connection\", \"close\")\n\n\t// Create client\n\tclient := &http.Client{}\n\n\t//Do request\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn content, nil\n}", "func SendRequest(method string, uri string, args ...interface{}) (responseBody []byte, statusCode int, err error) {\n\tmethod = strings.ToUpper(method)\n\n\tswitch method {\n\tcase \"GET\":\n\t\tresp, statusCode, err := sendGet(method, uri, args...)\n\t\treturn resp, statusCode, err\n\n\tcase \"POST\", \"PUT\":\n\t\tresp, statusCode, err := sendPost(method, uri, args...)\n\t\treturn resp, statusCode, err\n\n\tdefault:\n\t\terr := errors.New(\"Request method is not supported\")\n\t\treturn nil, http.StatusMethodNotAllowed, err\n\t}\n}", "func sendRequest(req *http.Request, credentials Credentials) ([]byte, error) {\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Connection\", \"close\")\n\treq.Header.Add(\"Authorization\", credentials.AuthToken)\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\treturn data, err\n}", "func (c *Client) doRequest(\n method string,\n route string,\n queryValues map[string]string,\n body []byte,\n) (*RawResponse, error) {\n req := fasthttp.AcquireRequest()\n resp := fasthttp.AcquireResponse()\n defer func() {\n if req != nil {\n req.SetConnectionClose()\n fasthttp.ReleaseRequest(req)\n }\n if resp != nil {\n resp.SetConnectionClose()\n fasthttp.ReleaseResponse(resp)\n }\n }()\n\n uri, err := utils.GetUri(c.apiUrl, []string{route}, queryValues)\n if err != nil {\n return nil, err\n }\n req.SetRequestURI(uri.String())\n\n if body != nil {\n req.Header.SetContentType(\"application/json\")\n req.SetBody(body)\n }\n\n req.Header.SetMethod(method)\n\n err = c.fastHttpClient.Do(req, resp)\n if err != nil {\n return nil, err\n }\n\n return &RawResponse{\n StatusCode: resp.StatusCode(),\n Body: resp.Body(),\n }, nil\n}", "func sendRequest(ctx context.Context, method, addr string, reqBody string) ([]byte, error) {\n\tclient := http.Client{}\n\t//nolint:staticcheck\n\treq := &http.Request{}\n\tvar err error\n\n\tif method == \"POST\" {\n\t\tform := url.Values{}\n\t\tform.Set(\"message\", reqBody)\n\t\tform.Set(\"parse_mode\", \"HTML\")\n\t\treqReader := strings.NewReader(form.Encode())\n\t\treq, err = http.NewRequestWithContext(ctx, method, addr, reqReader)\n\t\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t} else {\n\t\treq, err = http.NewRequestWithContext(ctx, method, addr, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\t}()\n\n\tvar body []byte\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tbody, err = ioutil.ReadAll(resp.Body)\n\t\tclose(done)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\t<-done\n\t\terr = resp.Body.Close()\n\t\tif err == nil {\n\t\t\terr = ctx.Err()\n\t\t}\n\tcase <-done:\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"received code %d; body: %s\", resp.StatusCode, string(body))\n\t}\n\n\treturn body, nil\n}", "func (c *Client) sendJSONRequest(ctx context.Context, url string, bodyMap map[string]string) (bodyBytes []byte, err error) {\n\tbodyString, err := json.Marshal(bodyMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(bodyString))\n\tif err != nil {\n\t\treturn\n\t}\n\treq = req.WithContext(ctx)\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tatHeader, err := c.GetApplicationAccessTokenHeader()\n\tif err == nil {\n\t\treq.Header.Set(\"Authorization\", atHeader)\n\t} else {\n\t\treturn\n\t}\n\n\tresp, err := c.httpCli.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (t *Transport) SendRequest(url string, resources []string) {\n\tt.adsRequestCh.Put(&resourceRequest{\n\t\turl: url,\n\t\tresources: resources,\n\t})\n}", "func sendRequest(aUrl string, aData url.Values) (*http.Response, []byte) {\n\t//Build the request\n\treq, err := http.NewRequest(\"POST\", aUrl, strings.NewReader(aData.Encode()) )\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n req.Header.Add(\"Content-Length\", strconv.Itoa(len(aData.Encode())))\n\n\t//Send the request\n client := &http.Client{}\n resp, err := client.Do(req)\n if err != nil {\n panic(err)\n }\n defer resp.Body.Close()\n\t\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\n\t//Print the response\n\tfmt.Println(\"response Status:\", resp.Status)\n\tfmt.Println(\"response Headers:\", resp.Header)\n\tfmt.Println(\"response Body:\", string(body))\n\t\n\treturn resp, body\n}", "func (s *Standard) sendRequest(context service.Context, requestMethod string, requestURL string, responseObject interface{}) error {\n\n\tserverToken := s.serverToken()\n\tif serverToken == \"\" {\n\t\treturn errors.Newf(\"client\", \"unable to obtain server token for %s %s\", requestMethod, requestURL)\n\t}\n\n\trequest, err := http.NewRequest(requestMethod, requestURL, nil)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"client\", \"unable to create new request for %s %s\", requestMethod, requestURL)\n\t}\n\n\tif err = service.CopyRequestTrace(context.Request(), request); err != nil {\n\t\treturn errors.Wrapf(err, \"client\", \"unable to copy request trace\")\n\t}\n\n\trequest.Header.Add(TidepoolAuthenticationTokenHeaderName, serverToken)\n\n\tresponse, err := s.httpClient.Do(request)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"client\", \"unable to perform request %s %s\", requestMethod, requestURL)\n\t}\n\tdefer response.Body.Close()\n\n\tswitch response.StatusCode {\n\tcase http.StatusOK:\n\t\tif responseObject != nil {\n\t\t\tif err = json.NewDecoder(response.Body).Decode(responseObject); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"client\", \"error decoding JSON response from %s %s\", request.Method, request.URL.String())\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase http.StatusUnauthorized:\n\t\treturn NewUnauthorizedError()\n\tdefault:\n\t\treturn NewUnexpectedResponseError(response, request)\n\t}\n}", "func (c *Client) SendRequest(method string, rawURL string, data url.Values,\n\theaders map[string]interface{}) (*http.Response, error) {\n\tu, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalueReader := &strings.Reader{}\n\tgoVersion := runtime.Version()\n\n\tif method == http.MethodGet {\n\t\tif data != nil {\n\t\t\tv, _ := form.EncodeToStringWith(data, delimiter, escapee, keepZeros)\n\t\t\tregex := regexp.MustCompile(`\\.\\d+`)\n\t\t\ts := regex.ReplaceAllString(v, \"\")\n\n\t\t\tu.RawQuery = s\n\t\t}\n\t}\n\n\tif method == http.MethodPost {\n\t\tvalueReader = strings.NewReader(data.Encode())\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), valueReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.SetBasicAuth(c.basicAuth())\n\n\t// E.g. \"User-Agent\": \"twilio-go/1.0.0 (darwin amd64) go/go1.17.8\"\n\tuserAgent := fmt.Sprintf(\"twilio-go/%s (%s %s) go/%s\", LibraryVersion, runtime.GOOS, runtime.GOARCH, goVersion)\n\n\tif len(c.UserAgentExtensions) > 0 {\n\t\tuserAgent += \" \" + strings.Join(c.UserAgentExtensions, \" \")\n\t}\n\n\treq.Header.Add(\"User-Agent\", userAgent)\n\n\tif method == http.MethodPost {\n\t\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t}\n\n\tfor k, v := range headers {\n\t\treq.Header.Add(k, fmt.Sprint(v))\n\t}\n\n\treturn c.doWithErr(req)\n}", "func SendRequest(endpoint string, data []byte) (*http.Response, error) {\n\n\ttr := &http.Transport{\n\t\tMaxIdleConns: 10,\n\t\tIdleConnTimeout: 30 * time.Second,\n\t\tDisableCompression: true,\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err = client.Post(endpoint, \"application/json\", bytes.NewBuffer(data))\n\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn resp, nil\n}", "func SendRequest(workflowID string) (string, error) {\n\taccessKey, clusterID, serverAddr, err := getAgentConfigMapData()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpayload := `{\"query\": \"mutation { gitopsNotifer(clusterInfo: { cluster_id: \\\"` + clusterID + `\\\", access_key: \\\"` + accessKey + `\\\"}, workflow_id: \\\"` + workflowID + `\\\")\\n}\"}`\n\treq, err := http.NewRequest(\"POST\", serverAddr, bytes.NewBuffer([]byte(payload)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"URL is not reachable or Bad request\", nil\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(body), nil\n}", "func (a *netAPI) doRequest(ctx context.Context, urlString string, resp proto.Message) error {\n\thttpReq, err := http.NewRequest(\"GET\", urlString, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.Header.Add(\"Content-Type\", \"application/json\")\n\thttpReq.Header.Add(\"User-Agent\", userAgentString)\n\thttpReq = httpReq.WithContext(ctx)\n\thttpResp, err := a.client.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpResp.Body.Close()\n\tif httpResp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"webrisk: unexpected server response code: %d\", httpResp.StatusCode)\n\t}\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn protojson.Unmarshal(body, resp)\n}", "func (c *NATSTestClient) SendRequest(subj string, payload []byte, cb mq.Response) {\n\t// Validate max control line size\n\t// 7 = nats inbox prefix length\n\t// 22 = nuid size\n\tif len(subj)+7+22 > nats.MAX_CONTROL_LINE_SIZE {\n\t\tgo cb(\"\", nil, mq.ErrSubjectTooLong)\n\t\treturn\n\t}\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tvar p interface{}\n\terr := json.Unmarshal(payload, &p)\n\tif err != nil {\n\t\tpanic(\"test: error unmarshaling request payload: \" + err.Error())\n\t}\n\n\tr := &Request{\n\t\tSubject: subj,\n\t\tRawPayload: payload,\n\t\tPayload: p,\n\t\tc: c,\n\t\tcb: cb,\n\t}\n\n\tc.Tracef(\"<== %s: %s\", subj, payload)\n\tif c.connected {\n\t\tc.reqs <- r\n\t} else {\n\t\tc.Errorf(\"Connection closed\")\n\t}\n}", "func (qiwi *PersonalAPI) sendRequest(apiKey, method, spath string, data map[string]interface{}) (body []byte, err error) {\n\treq, err := qiwi.newRequest(apiKey, method, spath, data)\n\n\tresponse, err := qiwi.httpClient.Do(req)\n\n\tif err != nil && response == nil {\n\n\t\treturn nil, err\n\n\t}\n\n\tbody, err = ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\n\t\tif response.Body != nil {\n\t\t\tresponse.Body.Close()\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tif response.StatusCode == 400 {\n\n\t\tvar res TransferError\n\n\t\terr = json.Unmarshal(body, &res)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"%s : %s\", res.Code, res.Message)\n\t}\n\n\tif response.StatusCode != 200 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\n\tif response.Body != nil {\n\t\tresponse.Body.Close()\n\t}\n\n\treturn body, nil\n\n}", "func (m *ConsensusNetworkMock) SendRequest(p network.Request, p1 core.RecordRef) (r error) {\n\tatomic.AddUint64(&m.SendRequestPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SendRequestCounter, 1)\n\n\tif m.SendRequestMock.mockExpectations != nil {\n\t\ttestify_assert.Equal(m.t, *m.SendRequestMock.mockExpectations, ConsensusNetworkMockSendRequestParams{p, p1},\n\t\t\t\"ConsensusNetwork.SendRequest got unexpected parameters\")\n\n\t\tif m.SendRequestFunc == nil {\n\n\t\t\tm.t.Fatal(\"No results are set for the ConsensusNetworkMock.SendRequest\")\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tif m.SendRequestFunc == nil {\n\t\tm.t.Fatal(\"Unexpected call to ConsensusNetworkMock.SendRequest\")\n\t\treturn\n\t}\n\n\treturn m.SendRequestFunc(p, p1)\n}", "func (c *Client) doRequest(url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(c.payload))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.Username != \"\" && c.Password != \"\" {\n\t\treq.SetBasicAuth(c.Username, c.Password)\n\t}\n\n\tif c.HttpClient == nil {\n\t\tc.HttpClient = &http.Client{}\n\t}\n\n\treq.ContentLength = int64(len(c.payload))\n\n\treq.Header.Add(\"Content-Type\", \"text/xml;charset=UTF-8\")\n\treq.Header.Add(\"Accept\", \"text/xml\")\n\treq.Header.Add(\"SOAPAction\", c.SoapAction)\n\n\tresp, err := c.HttpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func sendRequest(cmd *cobra.Command, args []string) {\n\tswitch args[0] {\n\tcase \"item\":\n\t\turls := buildURLs(itemAddr, args[1:]...)\n\t\tdone := distributeRequests(urls...)\n\t\tfor i := 0; i < len(urls); i++ {\n\t\t\t<-done\n\t\t}\n\n\tcase \"order\":\n\t\turls := buildURLs(orderAddr, args[1:]...)\n\t\tdone := distributeRequests(urls...)\n\t\tfor i := 0; i < len(urls); i++ {\n\t\t\t<-done\n\t\t}\n\n\tcase \"all\":\n\t\turls := []string{}\n\t\turls = append(urls, buildURLs(itemAddr, args[1:]...)...)\n\t\turls = append(urls, buildURLs(orderAddr, args[1:]...)...)\n\t\trand.Shuffle(len(urls), func(i, j int) {\n\t\t\turls[i], urls[j] = urls[j], urls[i]\n\t\t})\n\n\t\tdone := distributeRequests(urls...)\n\t\tfor j := 0; j < len(urls); j++ {\n\t\t\t<-done\n\t\t}\n\t}\n}", "func (k *Client) doRequest(r *request) (*http.Response, error) {\n\treq, err := http.NewRequest(r.method, k.baseURL+r.url, r.body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tif r.query != nil {\n\t\treq.URL.RawQuery = r.query.Encode()\n\t}\n\treturn k.httpClient.Do(req)\n}", "func sendRequest(Url *url.URL) []byte {\n\tresp, err := http.Get(Url.String())\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\tpanic(\"Fehler beim Request senden\")\n\t}\n\tif resp.StatusCode != 200 {\n\t\tfmt.Println(\"Response: \", resp.StatusCode)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Fehler beim lesen des response Body\")\n\t}\n\t//time.Sleep(100 * time.Millisecond)\n\treturn body\n}", "func (c *Client) SendRequest(to *introduce.PleaseIntroduceTo, myDID, theirDID string) error {\n\terr := c.service.HandleOutbound(service.NewDIDCommMsgMap(&introduce.Request{\n\t\tType: introduce.RequestMsgType,\n\t\tPleaseIntroduceTo: to,\n\t}), myDID, theirDID)\n\n\treturn err\n}", "func (c *Client) SendRequest(request ocpp.Request) error {\n\tif !c.dispatcher.IsRunning() {\n\t\treturn fmt.Errorf(\"ocppj client is not started, couldn't send request\")\n\t}\n\tcall, err := c.CreateCall(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonMessage, err := call.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Message will be processed by dispatcher. A dedicated mechanism allows to delegate the message queue handling.\n\tif err = c.dispatcher.SendRequest(RequestBundle{Call: call, Data: jsonMessage}); err != nil {\n\t\tlog.Errorf(\"error dispatching request [%s, %s]: %v\", call.UniqueId, call.Action, err)\n\t\treturn err\n\t}\n\tlog.Debugf(\"enqueued CALL [%s, %s]\", call.UniqueId, call.Action)\n\treturn nil\n}", "func sendRequest(c *xgb.Conn, Event Event, DataType uint32) []byte {\n\tsize := 104\n\tb := 0\n\tbuf := make([]byte, size)\n\n\tc.ExtLock.RLock()\n\tbuf[b] = c.Extensions[\"XEVIE\"]\n\tc.ExtLock.RUnlock()\n\tb += 1\n\n\tbuf[b] = 3 // 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\t{\n\t\tstructBytes := Event.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += len(structBytes)\n\t}\n\n\txgb.Put32(buf[b:], DataType)\n\tb += 4\n\n\tb += 64 // padding\n\n\treturn buf\n}", "func (req *Request) SendRequest(url, method string, bodyData []byte, headers []string, skipTLS bool, timeout time.Duration) *datastructure.Response {\n\n\t// Create a custom request\n\tvar (\n\t\terr error\n\t\tresponse datastructure.Response\n\t\tstart time.Time\n\t)\n\n\tstart = time.Now()\n\n\tif !strings.HasPrefix(url, \"http://\") && !strings.HasPrefix(url, \"https://\") {\n\t\t_error := errors.New(\"PREFIX_URL_NOT_VALID\")\n\t\tlog.Debug(\"sendRequest | Error! \", _error, \" URL: \", url)\n\t\tresponse.Error = _error\n\t\treturn &response\n\t}\n\n\tmethod = strings.ToUpper(method)\n\n\t// Validate method\n\tif !req.methodIsAllowed(method) {\n\t\tlog.Debug(\"sendRequest | Method [\" + method + \"] is not allowed!\")\n\t\t_error := errors.New(\"METHOD_NOT_ALLOWED\")\n\t\tresponse.Error = _error\n\t\treturn &response\n\t}\n\n\t// Manage TLS configuration\n\treq.SetTLS(skipTLS)\n\t// Set infinite timeout as default http/net\n\treq.SetTimeout(timeout)\n\n\treq.URL = url\n\treq.Data = bodyData\n\n\tswitch req.Method {\n\tcase \"GET\":\n\t\treq.initGetRequest()\n\t\treq.Req, err = http.NewRequest(req.Method, req.URL, nil)\n\tcase \"POST\":\n\t\treq.initPostRequest()\n\t\treq.Req, err = http.NewRequest(req.Method, req.URL, bytes.NewReader(req.Data))\n\tcase \"PUT\":\n\t\treq.Req, err = http.NewRequest(req.Method, req.URL, nil)\n\tcase \"DELETE\":\n\t\treq.Req, err = http.NewRequest(req.Method, req.URL, nil)\n\tdefault:\n\t\tlog.Debug(\"sendRequest | Unknown method -> \" + method)\n\t\terr = errors.New(\"HTTP_METHOD_NOT_MANAGED\")\n\t}\n\n\tif err != nil {\n\t\tlog.Debug(\"sendRequest | Error while initializing a new request -> \", err)\n\t\tresponse.Error = err\n\t\treturn &response\n\t}\n\terr = req.CreateHeaderList(headers...)\n\tif err != nil {\n\t\tlog.Debug(\"sendRequest | Error while initializing the headers -> \", err)\n\t\tresponse.Error = err\n\t\treturn &response\n\t}\n\n\tcontentlengthPresent := false\n\tif strings.Compare(req.Req.Header.Get(\"Content-Length\"), \"\") == 0 {\n\t\tcontentlengthPresent = true\n\t}\n\n\tif req.Method == \"POST\" && !contentlengthPresent {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\tlog.Debug(\"sendRequest | Content-length not provided, setting new one -> \", contentLength)\n\t\treq.Req.Header.Add(\"Content-Length\", contentLength)\n\t}\n\n\tlog.Debugf(\"sendRequest | Executing request .. %+v\\n\", req.Req)\n\tclient := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Debug(\"Error executing request | ERR:\", err)\n\t\tresponse.Error = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\treturn &response\n\t}\n\tdefer resp.Body.Close()\n\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\tlog.Debug(\"sendRequest | Request executed, reading response ...\")\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Debug(\"sendRequest | Unable to read response! | Err: \", err)\n\t\tresponse.Error = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\treturn &response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"sendRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn &response\n}", "func SendGetRequest(url string, tlsCfg *tls.Config) (string, error) {\n\treturn SendRequest(url, GetMethod, nil, tlsCfg)\n}", "func sendRequest(r *http.Request) *httptest.ResponseRecorder {\n\trecorder := httptest.NewRecorder()\n\tapp.Router.ServeHTTP(recorder, r)\n\n\treturn recorder\n}", "func SendRequest(r *protoTypes.Request, client protoTypes.FraudtestClient) bool {\n\tfmt.Println(\"Sending\", r, \"to\", outboundLocation)\n\n\t// Set Timeout\n\tctx, cancel := CreateContextWithTimeout(r)\n\tdefer cancel()\n\n\trpcReturn := make(chan *protoTypes.SuccessIndicator)\n\n\tgo func() {\n\t\tsuccess, err := client.TransferMessage(ctx, r)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error occurred when sending message\", err)\n\t\t}\n\t\trpcReturn <- success\n\t}()\n\n\tselect {\n\tcase success := <-rpcReturn:\n\t\tfmt.Println(\"Call was successful!\", success)\n\t\treturn success.Success\n\tcase <-ctx.Done():\n\t\tfmt.Println(\"Timeout occurred!\")\n\t\treturn false\n\t}\n\n}", "func SendHttpRequest(method, url, payload string) (int, string, error) {\n\treturn util.SendHttpRequest(\n\t\tmethod,\n\t\turl,\n\t\tpayload,\n\t\t[]string{access.CLIENT_CERT_SN_KEY, TestOperatorSerialNumber})\n}", "func SendRequestToCONIKS(addr string, msg []byte) ([]byte, error) {\n\tscheme := \"unix\"\n\tunixaddr := &net.UnixAddr{Name: addr, Net: scheme}\n\n\tconn, err := net.DialUnix(scheme, nil, unixaddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\t_, err = conn.Write(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn.CloseWrite()\n\tvar buf bytes.Buffer\n\tif _, err := io.CopyN(&buf, conn, 8192); err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (c *Context) SendRequest(method string, path string, headers map[string]string) (*http.Response, error) {\n\treq, err := http.NewRequest(method, c.Env.ClusterRoot+path, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not send request %s\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\treturn c.client.Do(req)\n}", "func (r GetMacieSessionRequest) Send(ctx context.Context) (*GetMacieSessionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &GetMacieSessionResponse{\n\t\tGetMacieSessionOutput: r.Request.Data.(*GetMacieSessionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func SendRequest(url, msg string, params map[string]string) ([]mxj.Map, error) {\n\tyfrequest, ok := yfRequests[msg]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid request '%s'\", msg)\n\t}\n\n\tlocal := yfrequest.Request\n\n\t// Check that all vars are filled\n\tfor _, name := range yfrequest.Params {\n\t\tif value, ok := params[name]; ok {\n\t\t\tlocal = strings.Replace(local, name, value, -1)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"incomplete request. No value for param '%s'\", name)\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, strings.NewReader(local))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"text/xml;charset=UTF-8\")\n\treq.Header.Add(\"SOAPAction\", `\"\"`)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read body first to close early, instead of passing to mxj.NewXmlReader.\n\t// Apparently causes less YF errors.\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Body.Close()\n\n\tm, err := mxj.NewMapXml(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"request error HTTP %d ->\\n%s\", resp.StatusCode, parseError(m))\n\t}\n\n\treturn parseResponse(m, yfrequest.Call, yfrequest.Resource)\n}", "func (c *Client) SendRequest(req *Request, option *SignOption) (bceResponse *Response, err error) {\n\tif option == nil {\n\t\toption = &SignOption{}\n\t}\n\n\toption.AddHeader(\"User-Agent\", c.GetUserAgent())\n\toption.AddHeader(\"Content-Type\", \"application/json\")\n\tif c.RetryPolicy == nil {\n\t\tc.RetryPolicy = NewDefaultRetryPolicy(3, 20*time.Second)\n\t}\n\tvar buf []byte\n\tif req.Body != nil {\n\t\tbuf, _ = ioutil.ReadAll(req.Body)\n\t}\n\n\tfor i := 0; ; i++ {\n\t\tbceResponse, err = nil, nil\n\t\tif option.Credentials != nil {\n\t\t\tGenerateAuthorization(*option.Credentials, *req, option)\n\t\t} else {\n\t\t\tGenerateAuthorization(*c.Credentials, *req, option)\n\t\t}\n\t\tif c.debug {\n\t\t\tutil.Debug(\"\", fmt.Sprintf(\"Request: httpMethod = %s, requestUrl = %s, requestHeader = %v\",\n\t\t\t\treq.Method, req.URL.String(), req.Header))\n\t\t}\n\t\tt0 := time.Now()\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\t\tresp, httpError := c.httpClient.Do(req.raw())\n\t\tt1 := time.Now()\n\t\tbceResponse = NewResponse(resp)\n\t\tif c.debug {\n\t\t\tutil.Debug(\"\", fmt.Sprintf(\"http request: %s do use time: %v\", req.URL.String(), t1.Sub(t0)))\n\t\t\tstatusCode := -1\n\t\t\tresString := \"\"\n\t\t\tvar resHead http.Header\n\t\t\tif resp != nil {\n\t\t\t\tstatusCode = resp.StatusCode\n\t\t\t\tre, err := bceResponse.GetBodyContent()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Debug(\"\", fmt.Sprintf(\"getbodycontent error: %v\", err))\n\t\t\t\t}\n\t\t\t\tresString = string(re)\n\t\t\t\tresHead = resp.Header\n\t\t\t}\n\t\t\tutil.Debug(\"\", fmt.Sprintf(\"Response: status code = %d, httpMethod = %s, requestUrl = %s\",\n\t\t\t\tstatusCode, req.Method, req.URL.String()))\n\t\t\tutil.Debug(\"\", fmt.Sprintf(\"Response Header: = %v\", resHead))\n\t\t\tutil.Debug(\"\", fmt.Sprintf(\"Response body: = %s\", resString))\n\t\t}\n\n\t\tif httpError != nil {\n\t\t\tduration := c.RetryPolicy.GetDelayBeforeNextRetry(httpError, i+1)\n\t\t\tif duration <= 0 {\n\t\t\t\terr = httpError\n\t\t\t\treturn bceResponse, err\n\t\t\t}\n\t\t\ttime.Sleep(duration)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.StatusCode >= http.StatusBadRequest {\n\t\t\terr = buildError(bceResponse)\n\t\t}\n\t\tif err == nil {\n\t\t\treturn bceResponse, err\n\t\t}\n\n\t\tduration := c.RetryPolicy.GetDelayBeforeNextRetry(err, i+1)\n\t\tif duration <= 0 {\n\t\t\treturn bceResponse, err\n\t\t}\n\n\t\ttime.Sleep(duration)\n\t}\n}", "func (c *ClientConn) Request() error {\n\tbuf := common.GetWriteBuffer()\n\tdefer common.PutWriteBuffer(buf)\n\n\tbuf.Write([]byte(c.user.Hex))\n\tbuf.Write(crlf)\n\tbuf.WriteByte(socks5.CmdConnect)\n\tbuf.Write(socks5.ParseAddr(c.target))\n\tbuf.Write(crlf)\n\tn, err := c.Conn.Write(buf.Bytes())\n\tc.sent += uint64(n)\n\n\treturn err\n}", "func (k *KeKahu) doRequest(req *http.Request) (*http.Response, error) {\n\tres, err := k.client.Do(req)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"could not make http request: %s\", err)\n\t\treturn res, err\n\t}\n\n\tdebug(\"%s %s %s\", req.Method, req.URL.String(), res.Status)\n\n\t// Check the status from the client\n\tif res.StatusCode < 200 || res.StatusCode > 299 {\n\t\tres.Body.Close()\n\t\treturn res, fmt.Errorf(\"could not access Kahu service: %s\", res.Status)\n\t}\n\n\treturn res, nil\n}", "func SendRequestZsmart(method string, url string, jsonStr string) ([]byte, error) {\n\tpayload := strings.NewReader(jsonStr)\n\n\treq, _ := http.NewRequest(method, url, payload)\n\treq.Header.Add(\"requestID\", conf.Param.ZSmartRequestID)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"username\", conf.Param.ZSmartUserName)\n\treq.Header.Add(\"password\", conf.Param.ZSmartPassword)\n\treq.Header.Add(\"Cache-Control\", \"no-cache\")\n\n\tres, e := http.DefaultClient.Do(req)\n\tif e != nil {\n\t\tlogging.Logf(\"%s\", e)\n\t\tlogging.Logf(\"Failed to send request to zsmart\")\n\t\treturn nil, e\n\t}\n\n\tdefer res.Body.Close()\n\tbody, e := ioutil.ReadAll(res.Body)\n\tif e != nil {\n\t\tlogging.Logf(\"%s\", e)\n\t\tlogging.Logf(\"Failed to send request to zsmart\")\n\t\treturn nil, e\n\t}\n\n\treturn body, e\n}", "func (rs *RequestSender) send(req *http.Request) (res *http.Response, err error) {\n\tif req.URL == nil {\n\t\treturn nil, ErrURLUnset\n\t}\n\tif rs.tracer != nil {\n\t\ttf := rs.tracer.Start(req)\n\t\tif tf != nil {\n\t\t\tdefer func() { tf.Finish(req, res, err) }()\n\t\t}\n\t}\n\tres, err = rs.client.Do(req)\n\treturn\n}", "func DoRequest(url string, params url.Values) ([]byte, error) {\n\t// fmt.Println(\"Params: \", params.Encode())\n\treturn reqPost(url, strings.NewReader(params.Encode()))\n}", "func SendPostRequest(url string, jsonStr []byte, tlsCfg *tls.Config) (string, error) {\n\treturn SendRequest(url, PostMethod, jsonStr, tlsCfg)\n}", "func (c Client) doRequest(method, path string) ([]byte, error) {\n\tif method == \"\" {\n\t\treturn nil, errors.New(\"method is nil\")\n\t}\n\n\treq, err := http.NewRequest(method, c.baseURL+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.httpClient == nil {\n\t\treturn nil, errors.New(\"httpClient is nil\")\n\t}\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.New(\"did not recive statusCode 200\")\n\t}\n\n\treturn body, nil\n}", "func (c *Client) sendRequest(ctx context.Context, req *http.Request, result interface{}, overrideToken ...string) error {\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json; charset=utf-8\")\n\n\tvar token string\n\tif len(overrideToken) > 0 {\n\t\ttoken = overrideToken[0]\n\t} else {\n\t\taccessToken, err := c.getAccessToken(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttoken = accessToken\n\t}\n\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\treq = req.WithContext(ctx)\n\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn c.parseError(res)\n\t}\n\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"status_code\": res.StatusCode,\n\t\t\"url\": req.URL.String(),\n\t}).Info(string(body))\n\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) sendRequest(method, path string, item *models.QueueItem) (*http.Response, error) {\n\turl := c.QueueAPIURL + path\n\n\treqBody, err := json.Marshal(item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(method, url, bytes.NewReader(reqBody))\n\n\tlogContext := log.Data{\"request_method\": method, \"path\": path}\n\tif err != nil {\n\t\tlog.Error(err, logContext)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\t// any errors here are due to transport errors, not 4xx/5xx responses\n\tif err != nil {\n\t\tlog.Error(err, logContext)\n\t\treturn nil, err\n\t}\n\n\treturn resp, err\n}", "func (ch *clientSecureChannel) sendRequest(ctx context.Context, op *ua.ServiceOperation) error {\n\t// Check if time to renew security token.\n\tif !ch.tokenRenewalTime.IsZero() && time.Now().After(ch.tokenRenewalTime) {\n\t\tch.tokenRenewalTime = ch.tokenRenewalTime.Add(60000 * time.Millisecond)\n\t\tch.renewToken(ctx)\n\t}\n\n\tch.sendingSemaphore.Lock()\n\tdefer ch.sendingSemaphore.Unlock()\n\n\treq := op.Request()\n\n\tif ch.trace {\n\t\tb, _ := json.MarshalIndent(req, \"\", \" \")\n\t\tlog.Printf(\"%s%s\", reflect.TypeOf(req).Elem().Name(), b)\n\t}\n\n\tswitch req := req.(type) {\n\tcase *ua.OpenSecureChannelRequest:\n\t\terr := ch.sendOpenSecureChannelRequest(ctx, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *ua.CloseSecureChannelRequest:\n\t\terr := ch.sendServiceRequest(ctx, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// send a success response to ourselves (the server will just close it's socket).\n\t\tselect {\n\t\tcase op.ResponseCh() <- &ua.CloseSecureChannelResponse{ResponseHeader: ua.ResponseHeader{RequestHandle: req.RequestHandle, Timestamp: time.Now()}}:\n\t\tdefault:\n\t\t}\n\tdefault:\n\t\terr := ch.sendServiceRequest(ctx, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Client) doRequest(method string, fullUrl string, body io.Reader) (*http.Response, error) {\n\tc.headers[\"Accept\"] = \"application/json\"\n\tclient := &http.Client{}\n\tlog.Println(\"teamcity-sdk Request:\", method, fullUrl)\n\treq, _ := http.NewRequest(method, fullUrl, body)\n\tfor k, v := range c.headers {\n\t\treq.Header.Add(k, v)\n\t}\n\treturn client.Do(req)\n}", "func DoRequest(url string, headers map[string]string, httpMethod string, data interface{}) ([]byte, error) {\n\n\t// Create the http request\n\t// Encode the data and set its content type in the case of an http POST\n\tvar req *http.Request\n\tvar err error\n\tif httpMethod == http.MethodPost {\n\t\treq, err = http.NewRequest(httpMethod, url, Encode(data))\n\t} else if httpMethod == http.MethodGet {\n\t\treq, err = http.NewRequest(httpMethod, url, nil)\n\t} else {\n\t\terr = errors.New(fmt.Sprintf(\"unrecognized httpMethod %v\", httpMethod))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor key, value := range headers {\n\t\treq.Header.Set(key, value)\n\t}\n\n\t// Attempt to do http request\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// If not StatusOK, return error\n\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"failed to send %v request to %v\", httpMethod, url))\n\t}\n\n\t// Return success\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\treturn bytes, nil\n\n}", "func (client *Client) sendRequest(ctx context.Context, options *request.Options, results interface{}) (*request.Content, error) {\n\tif options == nil {\n\t\treturn nil, errors.ArgumentMissing.With(\"options\")\n\t}\n\toptions.Context = ctx\n\toptions.Logger = client.Logger\n\toptions.UserAgent = \"BOX Client \" + VERSION\n\tif client.IsAuthenticated() {\n\t\toptions.Authorization = request.BearerAuthorization(client.Auth.Token.AccessToken)\n\t}\n\n\tresponse, err := request.Send(options, results)\n\n\t// TODO: We need to get access to the response headers\n\t// boxRequestID := res.Header.Get(\"Box-Request-Id\")\n\n\tif err != nil {\n\t\tvar details *RequestError\n\t\tif jerr := response.UnmarshalContentJSON(&details); jerr == nil {\n\t\t\tvar httperr *errors.Error\n\t\t\tif errors.As(err, &httperr) {\n\t\t\t\tdetails.StatusCode = httperr.Code\n\t\t\t}\n\t\t\tif errors.Is(err, errors.HTTPBadRequest) && errors.Is(details, InvalidGrant) {\n\t\t\t\treturn nil, errors.Unauthorized.Wrap(details)\n\t\t\t}\n\t\t\tif errors.Is(err, errors.HTTPUnauthorized) {\n\t\t\t\treturn nil, errors.Unauthorized.Wrap(details)\n\t\t\t}\n\t\t\tif errors.Is(err, errors.HTTPNotFound) {\n\t\t\t\treturn nil, errors.NotFound.Wrap(details)\n\t\t\t}\n\t\t\treturn nil, errors.WithStack(details)\n\t\t}\n\t\tif errors.Is(err, errors.HTTPUnauthorized) {\n\t\t\treturn nil, errors.Unauthorized.Wrap(err)\n\t\t}\n\t\tif errors.Is(err, errors.HTTPNotFound) {\n\t\t\treturn nil, errors.NotFound.Wrap(err)\n\t\t}\n\t}\n\treturn response, err\n}", "func (m *HostNetworkMock) SendRequest(p network.Request, p1 core.RecordRef) (r network.Future, r1 error) {\n\tatomic.AddUint64(&m.SendRequestPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SendRequestCounter, 1)\n\n\tif m.SendRequestMock.mockExpectations != nil {\n\t\ttestify_assert.Equal(m.t, *m.SendRequestMock.mockExpectations, HostNetworkMockSendRequestParams{p, p1},\n\t\t\t\"HostNetwork.SendRequest got unexpected parameters\")\n\n\t\tif m.SendRequestFunc == nil {\n\n\t\t\tm.t.Fatal(\"No results are set for the HostNetworkMock.SendRequest\")\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tif m.SendRequestFunc == nil {\n\t\tm.t.Fatal(\"Unexpected call to HostNetworkMock.SendRequest\")\n\t\treturn\n\t}\n\n\treturn m.SendRequestFunc(p, p1)\n}", "func (d *driver) DoHTTPRequest(account keppel.Account, r *http.Request) (*http.Response, error) {\n\tresultChan := make(chan uint16, 1)\n\td.getPortRequestChan <- getPortRequest{\n\t\tAccount: account,\n\t\tResult: resultChan,\n\t}\n\n\tr.URL.Scheme = \"http\"\n\tr.URL.Host = fmt.Sprintf(\"localhost:%d\", <-resultChan)\n\treturn http.DefaultClient.Do(r)\n}", "func DoRequestImpl(requestType string, BaseURL string, uri string, target string) string {\n\t// Build the URL\n\trequestURL := fmt.Sprintf(\"%s%s%s\", BaseURL, uri, target)\n\t//fmt.Printf(requestURL)\n\t// Make an insecure request\n\tclient := &http.Client{}\n\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\treq, err := http.NewRequest(requestType, requestURL, nil)\n\n\t// Prepare for auth\n\tUsername = viper.GetString(\"Username\")\n\tPassword = viper.GetString(\"Password\")\n\treq.SetBasicAuth(Username, Password)\n\n\t// Do the request\n\trs, err := client.Do(req)\n\n\t// Process response\n\tif err != nil {\n\t\tpanic(err) // More idiomatic way would be to print the error and die unless it's a serious error\n\t}\n\tdefer rs.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(rs.Body)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbodyString := string(bodyBytes)\n\n\treturn bodyString\n}", "func send(conn *net.Conn, request []byte) error {\n\tvar err error\n\tvar n int\n\tn, err = (*conn).Write(request)\n\n\tfor n < len(request) {\n\t\tn, err = (*conn).Write(request[n:])\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func send(conn *net.Conn, request []byte) error {\n\tvar err error\n\tvar n int\n\tn, err = (*conn).Write(request)\n\n\tfor n < len(request) {\n\t\tn, err = (*conn).Write(request[n:])\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func SendPostRequest(url string, request interface{}, response interface{}, headers ...Header) error {\n\tb, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"serialization of request failed\")\n\t}\n\tlog.WithField(\"details\", string(b)).Infof(\"---- Sending HTTP Request to %s\", url)\n\n\tc := &http.Client{}\n\tr, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"creating request to %s failed\", url)\n\t}\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tfor _, h := range headers {\n\t\tr.Header.Add(h.Name, h.Value)\n\t}\n\tresp, err := c.Do(r)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"sending request to %s failed\", url)\n\t}\n\tdefer resp.Body.Close()\n\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deserialization of response failed\")\n\t}\n\tlog.WithField(\"details\", response).Infof(\"---- Receiving HTTP response from %s\", url)\n\treturn nil\n}", "func sendRequest(conn net.Conn, text string) {\n message := text;\n \n if _,err := conn.Write([]byte(message + \"\\n\")); err != nil {\n log.Fatal(err)\n }\n}", "func (s *Client) doRequest(req *http.Request) ([]byte, error) {\n\treq.Header.Add(\"PddToken\", s.PddToken)\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif 200 != resp.StatusCode {\n\t\treturn nil, fmt.Errorf(\"%s\", body)\n\t}\n\n\treturn body, nil\n}", "func (c *CoinbaseAPIKeyAuth) makeRequest(req *http.Request) ([]byte, error) {\n\treq.Header.Set(\"CB-ACCESS-KEY\", c.APIKey)\n\treq.Header.Set(\"CB-VERSION\", time.Now().Format(\"20060102\"))\n\treq.Header.Set(\"CB-ACCESS-TIMESTAMP\", \"2017-03-27\")\n\tbv := []byte(time.Now().Format(\"20060102\") + \"GET\" + req.URL.String())\n\thasher := sha256.New()\n\thasher.Write(bv)\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\treq.Header.Set(\"CB-ACCESS-SIGN\", sha)\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(req)\n\n\t// Make sure we close the body stream no matter what\n\tdefer resp.Body.Close()\n\n\t// Read body\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//fmt.Println(string(body))\n\n\t// Check status code\n\tif resp.StatusCode != 200 {\n\t\tfmt.Println(string(body))\n\t\treturn nil, fmt.Errorf(\"Invalid HTTP response code: %d\", resp.StatusCode)\n\t}\n\n\t// Return\n\treturn body, nil\n}", "func (twd *TCPWaveDriver) RequestAddress(config NetConfig, subnetAddr net.IPNet, macAddr string,\n containerName string, containerID string) (string,error){\n\n // Create network\n var network *twc.Network\n var err error\n networkAddress := strings.Split(config.IPAM.ContainerNetwork, \"/\")[0]\n network,err = twd.ObjMgr.GetNetwork(config.IPAM.ContainerNetwork, config.IPAM.Org)\n if err!=nil{\n glog.Infof(\"Creating Network with address : %s\", config.IPAM.ContainerNetwork)\n network = &twc.Network{}\n network.Name = config.IPAM.NetworkName\n network.Description = \"Kubernetes Network\"\n network.Organization = config.IPAM.Org\n addrBits := strings.Split(networkAddress, \".\")\n addr1,_ := strconv.Atoi(addrBits[0])\n network.Addr1 = addr1\n addr2,_ := strconv.Atoi(addrBits[1])\n network.Addr2 = addr2\n addr3,_ := strconv.Atoi(addrBits[2])\n network.Addr3 = addr3\n addr4,_ := strconv.Atoi(addrBits[3])\n network.Addr4 = addr4\n network.DMZVisible = \"no\"\n network.MaskLen = int(config.IPAM.NetMaskLength)\n _,err1 := twd.ObjMgr.CreateNetwork(*network)\n if err1!=nil{\n return \"\", err1\n }\n }\n // Create Subnet\n var subnet *twc.Subnet\n subnet,err = twd.ObjMgr.GetSubnet(subnetAddr.String(), config.IPAM.Org)\n if err!=nil {\n glog.Infof(\"Creating Subnet with address : %s\", subnetAddr.String())\n subnet = &twc.Subnet{MaskLen: 26}\n subnet.Name = \"K8S Subnet\"\n subnet.Description = \"subnet for kubernetes\"\n subnet.Organization = config.IPAM.Org\n subNtAddr := strings.Split(subnetAddr.String(), \"/\")[0]\n addrBits := strings.Split(subNtAddr, \".\")\n glog.Info(\"Address Bits Array : \" + addrBits[3])\n addr1,_ := strconv.Atoi(addrBits[0])\n subnet.Addr1 = addr1\n addr2,_ := strconv.Atoi(addrBits[1])\n subnet.Addr2 = addr2\n addr3,_ := strconv.Atoi(addrBits[2])\n subnet.Addr3 = addr3\n addr4,_ := strconv.Atoi(addrBits[3])\n subnet.Addr4 = addr4\n subnet.RouterAddr = addrBits[0] + \".\" + addrBits[1] + \".\" + addrBits[2] + \".\" + strconv.Itoa(addr4 + 1)\n subnet.NetworkAddr = networkAddress\n subnet.PrimaryDomain = config.IPAM.Domain\n _,err1 := twd.ObjMgr.CreateSubnet(*subnet)\n if err1!=nil{\n return \"\", err1\n }\n }\n\n // Fetch available IP from IPAM\n ip,err2 := twd.ObjMgr.GetNextFreeIP(subnetAddr.String(), config.IPAM.Org)\n if err2!=nil{\n return \"\",err2\n }\n\n mac := macAddr\n glog.Infof(\"Free Ip received from IPAM = %s , mac addr = %s\", ip, mac)\n\n if config.Type == \"bridge\" {\n\t\thwAddr, err := hwaddr.GenerateHardwareAddr4(net.ParseIP(ip), hwaddr.PrivateMACPrefix)\n glog.Infof(\"Computed Mac addr for bridge type: %s\", hwAddr.String())\n mac = hwAddr.String()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Problem while generating hardware address using ip: %s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n _, err = twd.ObjMgr.CreateIPAddress(ip, mac, subnetAddr.IP.String(), config.IPAM.Domain, config.IPAM.Org, containerName)\n if err!=nil{\n return \"\", err\n }\n glog.Infof(\"Ip Created in IPAM = %s\", ip)\n return ip, nil\n}", "func (cbr ClaimableBalanceRequest) HTTPRequest(horizonURL string) (*http.Request, error) {\n\tendpoint, err := cbr.BuildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn http.NewRequest(\"GET\", horizonURL+endpoint, nil)\n}", "func (m *Manager) SendRequest(streamID int, req []byte) ([]byte, error) {\n\tm.providersLock.Lock()\n\tprovider, found := m.providers[streamID]\n\tm.providersLock.Unlock()\n\n\tif found {\n\t\treturn provider.SendRequest(req)\n\t}\n\treturn nil, fmt.Errorf(\"stream provider %d not found\", streamID)\n}", "func SendPostRequest(url, endpoint, jsonStr string) (int, error) {\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s%s\", url, endpoint), bytes.NewBuffer([]byte(jsonStr)))\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn resp.StatusCode, nil\n}", "func (c *Client) Request(ip net.IP) error {\n\tif c.ip == nil {\n\t\treturn errNoIPv4Addr\n\t}\n\n\t// Create ARP packet for broadcast address to attempt to find the\n\t// hardware address of the input IP address\n\tarp, err := NewPacket(OperationRequest, c.ifi.HardwareAddr, c.ip, ethernet.Broadcast, ip)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.WriteTo(arp, ethernet.Broadcast)\n}", "func (vk *VKApi) SendAPIRequest(method string, parameters map[string]interface{}) ([]byte, error) {\n\t//Format API endpoint\n\tu, err := url.Parse(apiUrl + method)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Fill mandatory parameters\n\tparameters[\"access_token\"] = vk.userToken\n\tparameters[\"v\"] = apiVersion\n\n\t// Format URL-encoded key-value parameters\n\trequest := url.Values{}\n\tfor k, v := range parameters {\n\t\tswitch v.(type) {\n\t\tcase string:\n\t\t\trequest.Add(k, v.(string))\n\t\tdefault:\n\t\t\trequest.Add(k, fmt.Sprint(v))\n\t\t}\n\t}\n\n\t// Send request and read response\n\tresp, err := http.PostForm(u.String(), request)\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\t//Read response body and check for errors\n\trBody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tvar apiResp responses.ApiRawResponse\n\n\tif err := json.Unmarshal(rBody, &apiResp); err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tif apiResp.Error.GetCode() != 0 {\n\t\treturn []byte{}, apiResp.Error\n\t}\n\n\treturn apiResp.Response, nil\n}", "func (vk *VK) AppsSendRequest(params map[string]string) (response AppsSendRequestResponse, vkErr Error) {\n\tvk.RequestUnmarshal(\"apps.sendRequest\", params, &response, &vkErr)\n\treturn\n}", "func (p *Ppspp) SendRequest(start ChunkID, end ChunkID, remote PeerID, sid SwarmID) error {\n\tglog.Infof(\"SendReq Chunk %v-%v, to %v, on %v\", start, end, remote, sid)\n\tswarm, ok1 := p.swarms[sid]\n\tif !ok1 {\n\t\treturn fmt.Errorf(\"SendRequest could not find %v\", sid)\n\t}\n\tours, ok2 := swarm.chans[remote]\n\tif !ok2 {\n\t\treturn fmt.Errorf(\"SendRequest could not find channel for %v on %v\", remote, sid)\n\t}\n\tc, ok3 := p.chans[ours]\n\tif !ok3 {\n\t\treturn fmt.Errorf(\"SendRequest could not find channel %v\", ours)\n\t}\n\th := RequestMsg{Start: start, End: end}\n\tm := Msg{Op: Request, Data: h}\n\td := Datagram{ChanID: c.theirs, Msgs: []Msg{m}}\n\treturn p.sendDatagram(d, ours)\n}", "func doRequest(client amqpcommand.Client, request *amqp.Message) (*amqp.Message, error) {\n\t// If by chance we got disconnected while waiting for the request\n\tresponse, err := client.RequestWithTimeout(request, 10*time.Second)\n\treturn response, err\n}", "func sendRequest(req *graphql.Request) (interface{}, error) {\n\tctx := context.Background()\n\tURL := os.Getenv(\"NOTIFICATIONS_URL\")\n\n\tif URL == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing required environment variable NOTIFICATIONS_URL\")\n\t}\n\n\tclient := graphql.NewClient(URL)\n\tclient.Log = func(s string) {\n\t\tfmt.Println(s)\n\t}\n\n\tvar data interface{}\n\terr := client.Run(ctx, req, &data)\n\treturn data, err\n}", "func (general *General) sendRequestMessage(peerIndex int, args *RequestMessageArgs, reply *RequestMessageReply) bool {\n\terr := general.CallHost(peerIndex, \"RequestMessage\", args, reply)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *MockStream) SendRequest(req *envoy_service_discovery.DiscoveryRequest) error {\n\tsubCtx, cancel := context.WithTimeout(s.ctx, s.recvTimeout)\n\n\tselect {\n\tcase <-subCtx.Done():\n\t\tcancel()\n\t\tif errors.Is(subCtx.Err(), context.Canceled) {\n\t\t\treturn io.EOF\n\t\t}\n\t\treturn subCtx.Err()\n\tcase s.recv <- req:\n\t\tcancel()\n\t\treturn nil\n\t}\n}", "func doRequest(requestMethod, requestUrl,\n\trequestData string) (*http.Response, error) {\n\t// These will hold the return value.\n\tvar res *http.Response\n\tvar err error\n\n\t\n\t// Convert method to uppercase for easier checking.\n\tupperRequestMethod := strings.ToUpper(requestMethod)\n\tswitch upperRequestMethod {\n\tcase \"GET\":\n\t\t// Use the HTTP library Get() method.\n\t\tres, err = http.Get(requestUrl)\n\t\t//fmt.Printf(\"!!! res=\", res)\n\t\t//fmt.Printf(\"error=\", err.Error())\n\n\tdefault:\n\t\t// We doń't know how to handle this request.\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"invalid --request_method provided : %s\",\n\t\t\t\trequestMethod)\n\t}\n\n\treturn res, err\n}", "func (request *request) send() (*response, error) {\n\thttpClient, err := request.channel.socksProxy.GetHTTPClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpResponse, err := httpClient.Post(\n\t\tstring(request.server),\n\t\t\"application/x-www-form-urlencoded\",\n\t\tstrings.NewReader(request.encode()),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif httpResponse.StatusCode != http.StatusOK {\n\t\treturn nil, errp.New(\"Proxy Server did not respond with OK http status code, it is probably offline\")\n\t}\n\tdefer func() { _ = httpResponse.Body.Close() }()\n\tbody, err := io.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar serverResponse response\n\terr = json.Unmarshal(body, &serverResponse)\n\treturn &serverResponse, err\n}", "func DoRequest(configuration Configuration, url string, method string) *http.Response {\n\treq, err := http.NewRequest(method, url, nil)\n\n\treq.SetBasicAuth(configuration.Username, configuration.Password)\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn resp\n}", "func BroadcastTxRequest(cliCtx context.CLIContext) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar req BroadcastReq\n\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\terr = cliCtx.Codec.UnmarshalJSON(body, &req)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttxBytes, err := cliCtx.Codec.MarshalBinaryLengthPrefixed(req.Tx)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcliCtx = cliCtx.WithBroadcastMode(req.Mode)\n\n\t\tres, err := cliCtx.BroadcastTx(txBytes)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\trest.PostProcessResponse(w, cliCtx, res)\n\t}\n}", "func (c *Direct) sendMapRequest(ctx context.Context, maxPolls int, cb func(*netmap.NetworkMap)) error {\n\tc.mu.Lock()\n\tpersist := c.persist\n\tserverURL := c.serverURL\n\tserverKey := c.serverKey\n\thostinfo := c.hostinfo.Clone()\n\tbackendLogID := hostinfo.BackendLogID\n\tlocalPort := c.localPort\n\tep := append([]string(nil), c.endpoints...)\n\teverEndpoints := c.everEndpoints\n\tc.mu.Unlock()\n\n\tif persist.PrivateNodeKey.IsZero() {\n\t\treturn errors.New(\"privateNodeKey is zero\")\n\t}\n\tif backendLogID == \"\" {\n\t\treturn errors.New(\"hostinfo: BackendLogID missing\")\n\t}\n\n\tallowStream := maxPolls != 1\n\tc.logf(\"[v1] PollNetMap: stream=%v :%v ep=%v\", allowStream, localPort, ep)\n\n\tvlogf := logger.Discard\n\tif Debug.NetMap {\n\t\t// TODO(bradfitz): update this to use \"[v2]\" prefix perhaps? but we don't\n\t\t// want to upload it always.\n\t\tvlogf = c.logf\n\t}\n\n\trequest := tailcfg.MapRequest{\n\t\tVersion: tailcfg.CurrentMapRequestVersion,\n\t\tKeepAlive: c.keepAlive,\n\t\tNodeKey: tailcfg.NodeKey(persist.PrivateNodeKey.Public()),\n\t\tDiscoKey: c.discoPubKey,\n\t\tEndpoints: ep,\n\t\tStream: allowStream,\n\t\tHostinfo: hostinfo,\n\t\tDebugFlags: c.debugFlags,\n\t\tOmitPeers: cb == nil,\n\t}\n\tvar extraDebugFlags []string\n\tif hostinfo != nil && ipForwardingBroken(hostinfo.RoutableIPs) {\n\t\textraDebugFlags = append(extraDebugFlags, \"warn-ip-forwarding-off\")\n\t}\n\tif health.RouterHealth() != nil {\n\t\textraDebugFlags = append(extraDebugFlags, \"warn-router-unhealthy\")\n\t}\n\tif len(extraDebugFlags) > 0 {\n\t\told := request.DebugFlags\n\t\trequest.DebugFlags = append(old[:len(old):len(old)], extraDebugFlags...)\n\t}\n\tif c.newDecompressor != nil {\n\t\trequest.Compress = \"zstd\"\n\t}\n\t// On initial startup before we know our endpoints, set the ReadOnly flag\n\t// to tell the control server not to distribute out our (empty) endpoints to peers.\n\t// Presumably we'll learn our endpoints in a half second and do another post\n\t// with useful results. The first POST just gets us the DERP map which we\n\t// need to do the STUN queries to discover our endpoints.\n\t// TODO(bradfitz): we skip this optimization in tests, though,\n\t// because the e2e tests are currently hyperspecific about the\n\t// ordering of things. The e2e tests need love.\n\tif len(ep) == 0 && !everEndpoints && !inTest() {\n\t\trequest.ReadOnly = true\n\t}\n\n\tbodyData, err := encode(request, &serverKey, &c.machinePrivKey)\n\tif err != nil {\n\t\tvlogf(\"netmap: encode: %v\", err)\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tmachinePubKey := tailcfg.MachineKey(c.machinePrivKey.Public())\n\tt0 := time.Now()\n\tu := fmt.Sprintf(\"%s/machine/%s/map\", serverURL, machinePubKey.HexString())\n\n\treq, err := http.NewRequestWithContext(ctx, \"POST\", u, bytes.NewReader(bodyData))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := c.httpc.Do(req)\n\tif err != nil {\n\t\tvlogf(\"netmap: Do: %v\", err)\n\t\treturn err\n\t}\n\tvlogf(\"netmap: Do = %v after %v\", res.StatusCode, time.Since(t0).Round(time.Millisecond))\n\tif res.StatusCode != 200 {\n\t\tmsg, _ := ioutil.ReadAll(res.Body)\n\t\tres.Body.Close()\n\t\treturn fmt.Errorf(\"initial fetch failed %d: %.200s\",\n\t\t\tres.StatusCode, strings.TrimSpace(string(msg)))\n\t}\n\tdefer res.Body.Close()\n\n\tif cb == nil {\n\t\tio.Copy(ioutil.Discard, res.Body)\n\t\treturn nil\n\t}\n\n\t// If we go more than pollTimeout without hearing from the server,\n\t// end the long poll. We should be receiving a keep alive ping\n\t// every minute.\n\tconst pollTimeout = 120 * time.Second\n\ttimeout := time.NewTimer(pollTimeout)\n\ttimeoutReset := make(chan struct{})\n\tpollDone := make(chan struct{})\n\tdefer close(pollDone)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-pollDone:\n\t\t\t\tvlogf(\"netmap: ending timeout goroutine\")\n\t\t\t\treturn\n\t\t\tcase <-timeout.C:\n\t\t\t\tc.logf(\"map response long-poll timed out!\")\n\t\t\t\tcancel()\n\t\t\t\treturn\n\t\t\tcase <-timeoutReset:\n\t\t\t\tif !timeout.Stop() {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-timeout.C:\n\t\t\t\t\tcase <-pollDone:\n\t\t\t\t\t\tvlogf(\"netmap: ending timeout goroutine\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvlogf(\"netmap: reset timeout timer\")\n\t\t\t\ttimeout.Reset(pollTimeout)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar lastDERPMap *tailcfg.DERPMap\n\tvar lastUserProfile = map[tailcfg.UserID]tailcfg.UserProfile{}\n\tvar lastParsedPacketFilter []filter.Match\n\tvar collectServices bool\n\n\t// If allowStream, then the server will use an HTTP long poll to\n\t// return incremental results. There is always one response right\n\t// away, followed by a delay, and eventually others.\n\t// If !allowStream, it'll still send the first result in exactly\n\t// the same format before just closing the connection.\n\t// We can use this same read loop either way.\n\tvar msg []byte\n\tvar previousPeers []*tailcfg.Node // for delta-purposes\n\tfor i := 0; i < maxPolls || maxPolls < 0; i++ {\n\t\tvlogf(\"netmap: starting size read after %v (poll %v)\", time.Since(t0).Round(time.Millisecond), i)\n\t\tvar siz [4]byte\n\t\tif _, err := io.ReadFull(res.Body, siz[:]); err != nil {\n\t\t\tvlogf(\"netmap: size read error after %v: %v\", time.Since(t0).Round(time.Millisecond), err)\n\t\t\treturn err\n\t\t}\n\t\tsize := binary.LittleEndian.Uint32(siz[:])\n\t\tvlogf(\"netmap: read size %v after %v\", size, time.Since(t0).Round(time.Millisecond))\n\t\tmsg = append(msg[:0], make([]byte, size)...)\n\t\tif _, err := io.ReadFull(res.Body, msg); err != nil {\n\t\t\tvlogf(\"netmap: body read error: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tvlogf(\"netmap: read body after %v\", time.Since(t0).Round(time.Millisecond))\n\n\t\tvar resp tailcfg.MapResponse\n\t\tif err := c.decodeMsg(msg, &resp); err != nil {\n\t\t\tvlogf(\"netmap: decode error: %v\")\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.KeepAlive {\n\t\t\tvlogf(\"netmap: got keep-alive\")\n\t\t} else {\n\t\t\tvlogf(\"netmap: got new map\")\n\t\t}\n\t\tselect {\n\t\tcase timeoutReset <- struct{}{}:\n\t\t\tvlogf(\"netmap: sent timer reset\")\n\t\tcase <-ctx.Done():\n\t\t\tc.logf(\"[v1] netmap: not resetting timer; context done: %v\", ctx.Err())\n\t\t\treturn ctx.Err()\n\t\t}\n\t\tif resp.KeepAlive {\n\t\t\tcontinue\n\t\t}\n\n\t\tundeltaPeers(&resp, previousPeers)\n\t\tpreviousPeers = cloneNodes(resp.Peers) // defensive/lazy clone, since this escapes to who knows where\n\t\tfor _, up := range resp.UserProfiles {\n\t\t\tlastUserProfile[up.ID] = up\n\t\t}\n\n\t\tif resp.DERPMap != nil {\n\t\t\tvlogf(\"netmap: new map contains DERP map\")\n\t\t\tlastDERPMap = resp.DERPMap\n\t\t}\n\t\tif resp.Debug != nil {\n\t\t\tif resp.Debug.LogHeapPprof {\n\t\t\t\tgo logheap.LogHeap(resp.Debug.LogHeapURL)\n\t\t\t}\n\t\t\tsetControlAtomic(&controlUseDERPRoute, resp.Debug.DERPRoute)\n\t\t\tsetControlAtomic(&controlTrimWGConfig, resp.Debug.TrimWGConfig)\n\t\t}\n\t\t// Temporarily (2020-06-29) support removing all but\n\t\t// discovery-supporting nodes during development, for\n\t\t// less noise.\n\t\tif Debug.OnlyDisco {\n\t\t\tfiltered := resp.Peers[:0]\n\t\t\tfor _, p := range resp.Peers {\n\t\t\t\tif !p.DiscoKey.IsZero() {\n\t\t\t\t\tfiltered = append(filtered, p)\n\t\t\t\t}\n\t\t\t}\n\t\t\tresp.Peers = filtered\n\t\t}\n\t\tif Debug.StripEndpoints {\n\t\t\tfor _, p := range resp.Peers {\n\t\t\t\t// We need at least one endpoint here for now else\n\t\t\t\t// other code doesn't even create the discoEndpoint.\n\t\t\t\t// TODO(bradfitz): fix that and then just nil this out.\n\t\t\t\tp.Endpoints = []string{\"127.9.9.9:456\"}\n\t\t\t}\n\t\t}\n\n\t\tif pf := resp.PacketFilter; pf != nil {\n\t\t\tlastParsedPacketFilter = c.parsePacketFilter(pf)\n\t\t}\n\n\t\tif v, ok := resp.CollectServices.Get(); ok {\n\t\t\tcollectServices = v\n\t\t}\n\n\t\t// Get latest localPort. This might've changed if\n\t\t// a lite map update occured meanwhile. This only affects\n\t\t// the end-to-end test.\n\t\t// TODO(bradfitz): remove the NetworkMap.LocalPort field entirely.\n\t\tc.mu.Lock()\n\t\tlocalPort = c.localPort\n\t\tc.mu.Unlock()\n\n\t\tnm := &netmap.NetworkMap{\n\t\t\tSelfNode: resp.Node,\n\t\t\tNodeKey: tailcfg.NodeKey(persist.PrivateNodeKey.Public()),\n\t\t\tPrivateKey: persist.PrivateNodeKey,\n\t\t\tMachineKey: machinePubKey,\n\t\t\tExpiry: resp.Node.KeyExpiry,\n\t\t\tName: resp.Node.Name,\n\t\t\tAddresses: resp.Node.Addresses,\n\t\t\tPeers: resp.Peers,\n\t\t\tLocalPort: localPort,\n\t\t\tUser: resp.Node.User,\n\t\t\tUserProfiles: make(map[tailcfg.UserID]tailcfg.UserProfile),\n\t\t\tDomain: resp.Domain,\n\t\t\tDNS: resp.DNSConfig,\n\t\t\tHostinfo: resp.Node.Hostinfo,\n\t\t\tPacketFilter: lastParsedPacketFilter,\n\t\t\tCollectServices: collectServices,\n\t\t\tDERPMap: lastDERPMap,\n\t\t\tDebug: resp.Debug,\n\t\t}\n\t\taddUserProfile := func(userID tailcfg.UserID) {\n\t\t\tif _, dup := nm.UserProfiles[userID]; dup {\n\t\t\t\t// Already populated it from a previous peer.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif up, ok := lastUserProfile[userID]; ok {\n\t\t\t\tnm.UserProfiles[userID] = up\n\t\t\t}\n\t\t}\n\t\taddUserProfile(nm.User)\n\t\tmagicDNSSuffix := nm.MagicDNSSuffix()\n\t\tnm.SelfNode.InitDisplayNames(magicDNSSuffix)\n\t\tfor _, peer := range resp.Peers {\n\t\t\tpeer.InitDisplayNames(magicDNSSuffix)\n\t\t\tif !peer.Sharer.IsZero() {\n\t\t\t\tif c.keepSharerAndUserSplit {\n\t\t\t\t\taddUserProfile(peer.Sharer)\n\t\t\t\t} else {\n\t\t\t\t\tpeer.User = peer.Sharer\n\t\t\t\t}\n\t\t\t}\n\t\t\taddUserProfile(peer.User)\n\t\t}\n\t\tif resp.Node.MachineAuthorized {\n\t\t\tnm.MachineStatus = tailcfg.MachineAuthorized\n\t\t} else {\n\t\t\tnm.MachineStatus = tailcfg.MachineUnauthorized\n\t\t}\n\t\tif len(resp.DNS) > 0 {\n\t\t\tnm.DNS.Nameservers = resp.DNS\n\t\t}\n\t\tif len(resp.SearchPaths) > 0 {\n\t\t\tnm.DNS.Domains = resp.SearchPaths\n\t\t}\n\t\tif Debug.ProxyDNS {\n\t\t\tnm.DNS.Proxied = true\n\t\t}\n\n\t\t// Printing the netmap can be extremely verbose, but is very\n\t\t// handy for debugging. Let's limit how often we do it.\n\t\t// Code elsewhere prints netmap diffs every time, so this\n\t\t// occasional full dump, plus incremental diffs, should do\n\t\t// the job.\n\t\tnow := c.timeNow()\n\t\tif now.Sub(c.lastPrintMap) >= 5*time.Minute {\n\t\t\tc.lastPrintMap = now\n\t\t\tc.logf(\"[v1] new network map[%d]:\\n%s\", i, nm.Concise())\n\t\t}\n\n\t\tc.mu.Lock()\n\t\tc.expiry = &nm.Expiry\n\t\tc.mu.Unlock()\n\n\t\tcb(nm)\n\t}\n\tif ctx.Err() != nil {\n\t\treturn ctx.Err()\n\t}\n\treturn nil\n}", "func (mb *client) send(request *ProtocolDataUnit) (response *ProtocolDataUnit, err error) {\n\taduRequest, err := mb.packager.Encode(request)\n\tif err != nil {\n\t\treturn\n\t}\n\taduResponse, err := mb.transporter.Send(aduRequest)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = mb.packager.Verify(aduRequest, aduResponse); err != nil {\n\t\treturn\n\t}\n\tresponse, err = mb.packager.Decode(aduResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Check correct function code returned (exception)\n\tif response.FunctionCode != request.FunctionCode {\n\t\terr = responseError(response)\n\t\treturn\n\t}\n\tif response.Data == nil || len(response.Data) == 0 {\n\t\t// Empty response\n\t\terr = fmt.Errorf(\"modbus: response data is empty\")\n\t\treturn\n\t}\n\treturn\n}", "func (h *HitBTC) SendHTTPRequest(ctx context.Context, ep exchange.URL, path string, result interface{}) error {\n\tendpoint, err := h.API.Endpoints.GetURL(ep)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem := &request.Item{\n\t\tMethod: http.MethodGet,\n\t\tPath: endpoint + path,\n\t\tResult: result,\n\t\tVerbose: h.Verbose,\n\t\tHTTPDebugging: h.HTTPDebugging,\n\t\tHTTPRecording: h.HTTPRecording,\n\t}\n\n\treturn h.SendPayload(ctx, marketRequests, func() (*request.Item, error) {\n\t\treturn item, nil\n\t}, request.UnauthenticatedRequest)\n}", "func (fc FlarumClient) sendApiRequest(method string, path string, payload map[string]interface{}) (response map[string]interface{}, err error) {\n\turl := request.PROTOCOL_HTTP + fc.url + FORUM_API_SUFFIX + path\n\n\t// Convert map to a JSON string\n\tpayloadString, err := json.Marshal(payload)\n\n\treq, err := http.NewRequest(method, url, bytes.NewBuffer(payloadString))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Token \"+fc.token+\"; userId=1\")\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\n\tif err == nil {\n\t\tif resp.StatusCode != 200 {\n\t\t\terr = errors.New(\"Forum returned a code other than 200\")\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\tvar bodyMap map[string]interface{}\n\t\t\tjson.Unmarshal(body, &bodyMap)\n\t\t\treturn bodyMap, err\n\t\t}\n\t}\n\n\treturn map[string]interface{}{}, err\n}", "func SendQueryRequest(requestData RequestData) (string, error) {\n\treq, errNewRequest := http.NewRequest(\"GET\", requestData.Url, strings.NewReader(requestData.Data))\n\tif errNewRequest != nil {\n\t\treturn \"\", errNewRequest\n\t}\n\treq.Header.Set(\"Authorization\", requestData.Token.TokenType+\" \"+requestData.Token.AccessToken)\n\n\tresponse, errDo := DoRequest(req)\n\tif errDo != nil {\n\t\treturn \"\", errDo\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err2 := ioutil.ReadAll(response.Body)\n\tif err2 != nil {\n\t\treturn \"\", err2\n\t}\n\tif response.StatusCode == http.StatusOK || response.StatusCode == http.StatusNoContent {\n\t\treturn string(body), nil\n\t} else {\n\t\treturn \"\", errors.New(\"heartbeat request failed, status is \" + strconv.Itoa(response.StatusCode))\n\t}\n}", "func (i *Instance) doRequest(ctx context.Context, url string) (map[string]interface{}, error) {\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf(\"%s%s\", i.address, url), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := i.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode >= 200 && resp.StatusCode < 300 {\n\t\tvar data map[string]interface{}\n\n\t\terr = json.NewDecoder(resp.Body).Decode(&data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn data, nil\n\t}\n\n\tvar res ResponseError\n\n\terr = json.NewDecoder(resp.Body).Decode(&res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(res.Errors) > 0 {\n\t\treturn nil, fmt.Errorf(res.Errors[0].Msg)\n\t}\n\n\treturn nil, fmt.Errorf(\"%v\", res)\n}", "func SendRequest(r Request) (Response, error) {\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(r.Method, r.URL, bytes.NewBuffer(r.Body))\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\tif resp.StatusCode != r.OkStatusCode {\n\t\tvar hubspotErrorResponse HubspotError\n\t\terr = json.Unmarshal([]byte(body), &hubspotErrorResponse)\n\t\treturn Response{Body: []byte(hubspotErrorResponse.ErrorType), StatusCode: resp.StatusCode}, fmt.Errorf(hubspotErrorResponse.ErrorType)\n\t}\n\treturn Response{Body: body, StatusCode: resp.StatusCode}, nil\n}", "func DoSendRequestHelper(d Doer, key string, url string, sms SMS) (SMSResponse, error) {\n\tm := smsSetOptions(sms)\n\tm[\"Key\"] = key\n\tq := urlEncode(m)\n\n\treq, err := http.NewRequest(\"GET\", url+\"?\"+q, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// identify this client to the clockwork SMS API\n\tuserAgent := \"Clockwork Go wrapper/\" + Version()\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treq.Header.Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\n\tresp, err := d.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, ErrStatusCode\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseSendResponseBody(string(body))\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func sendHTTPRequestToKTT(kttClient *KttClient, request *http.Request) KttResponse {\n\t//Perform POST request against KTT only in \"normal\" mode\n\tif applicationMode == \"normal\" {\n\n\t\tresponse, err := kttClient.Client.Do(request)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer response.Body.Close()\n\n\t\tlog.Printf(\"Status code %v\", response.StatusCode)\n\n\t\tif response.StatusCode == http.StatusCreated {\n\t\t\tstatistics.TicketsCreated += 1\n\t\t\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tbodyString := string(bodyBytes)\n\t\t\t//fmt.Println(bodyString)\n\t\t\treturn KttResponse(bodyString)\n\t\t} else {\n\t\t\tstatistics.Errors += 1\n\t\t}\n\n\t}\n\n\tif applicationMode == \"test\" {\n\t\tlog.Println(\"In test mode, pass ticket creation...\")\n\t}\n\n\treturn \"\"\n}", "func (h *HUOBIHADAX) SendHTTPRequest(path string, result interface{}) error {\n\treturn h.SendPayload(http.MethodGet, path, nil, nil, result, false, false, h.Verbose, h.HTTPDebugging)\n}", "func (client Client) MakeRequest(action string, body, output interface{}) error {\n\tif body == nil {\n\t\tbody = struct{}{}\n\t}\n\tmarshalled, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", client.Endpoint, bytes.NewReader(marshalled))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-JNAP-Authorization\", client.Authorization)\n\treq.Header.Set(\"X-JNAP-Action\", \"http://linksys.com/jnap/\"+action)\n\n\tres, err := HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\t// the status should be 200 even if there is an error\n\tif res.StatusCode != 200 {\n\t\treturn ErrStatusCode\n\t}\n\n\tresponse := jnapResponse{\n\t\tOutput: output,\n\t}\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(response.Result)\n\n\tif response.Result != \"OK\" {\n\t\tif response.Error != \"\" {\n\t\t\treturn errors.New(response.Error)\n\t\t}\n\t\treturn errors.New(response.Result)\n\t}\n\n\treturn nil\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, \"[email protected] \"+env.AppID)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn d.client.Do(c, req, res)\n}", "func (h *httpCloud) sendHTTPRequest(requestType string, url string, requestBody io.Reader) ([]byte, error) {\n\treq, err := http.NewRequest(requestType, url, requestBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &http.Client{\n\t\tTransport: http.DefaultTransport,\n\t\tTimeout: HttpProviderTimeout,\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn body, nil\n\t}\n}", "func (pr *PJProjector) SendRequest(request PJRequest) (*PJResponse, error) {\n\tif err := request.Validate(); err != nil { //malformed command, don't send\n\t\treturn nil, err\n\t} else { //send request and parse response into struct\n\t\tresponse, requestError := pr.sendRawRequest(request)\n\t\tif requestError != nil {\n\t\t\treturn nil, requestError\n\t\t} else {\n\t\t\treturn response, nil\n\t\t}\n\t}\n}", "func (t *UdpClient) execRequest(message *proto.Msg) (*proto.Msg, error) {\r\n\tdata, err := pb.Marshal(message)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tif len(data) > MAX_UDP_SIZE {\r\n\t\treturn nil, fmt.Errorf(\"unable to send message, too large for udp\")\r\n\t}\r\n\tif _, err = t.conn.Write(data); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn nil, nil\r\n}", "func (s *Surf) httpRequest(param *DownloadParam) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(param.GetMethod(), param.GetUrl().String(), param.GetBody())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header = param.GetHeader()\n\n\tif param.GetTryTimes() <= 0 {\n\t\tfor {\n\t\t\tresp, err = param.GetClient().Do(req)\n\t\t\tif err != nil {\n\t\t\t\tif !param.IsEnableCookie() {\n\t\t\t\t\treq.Header.Set(\"User-Agent\", FKUserAgent.GlobalUserAgent.CreateRandomWebBrowserUA())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(param.GetRetryPause())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t} else {\n\t\tfor i := 0; i < param.GetTryTimes(); i++ {\n\t\t\tresp, err = param.GetClient().Do(req)\n\t\t\tif err != nil {\n\t\t\t\tif !param.IsEnableCookie() {\n\t\t\t\t\treq.Header.Set(\"User-Agent\", FKUserAgent.GlobalUserAgent.CreateRandomWebBrowserUA())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(param.GetRetryPause())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn resp, err\n}" ]
[ "0.6527724", "0.6464387", "0.59520745", "0.5895073", "0.58694565", "0.5826567", "0.57553387", "0.5727773", "0.56963766", "0.5684396", "0.55931616", "0.55735636", "0.5555725", "0.54407734", "0.54397285", "0.5354053", "0.533775", "0.5321918", "0.5321016", "0.53103495", "0.53047705", "0.52790785", "0.52747077", "0.5250128", "0.52482355", "0.52256936", "0.5212991", "0.5202151", "0.5200985", "0.5193178", "0.51914185", "0.51513463", "0.5146776", "0.5123293", "0.51182437", "0.51146907", "0.51024204", "0.50978917", "0.5090204", "0.5086269", "0.50739676", "0.5066571", "0.50465006", "0.5028714", "0.50139457", "0.4995129", "0.49944773", "0.49936002", "0.49890742", "0.4988381", "0.49855217", "0.4978906", "0.49627286", "0.49610132", "0.49489537", "0.4944402", "0.49353182", "0.4926644", "0.49226716", "0.48881292", "0.48756617", "0.48756588", "0.48756588", "0.48747018", "0.48733184", "0.48728198", "0.48625985", "0.48508045", "0.48345977", "0.48334455", "0.4828374", "0.48194295", "0.48190874", "0.48147905", "0.48143038", "0.48080242", "0.4802102", "0.47934255", "0.47797275", "0.4775085", "0.47649938", "0.47576493", "0.4757048", "0.47482744", "0.4745876", "0.47445524", "0.4742947", "0.47306946", "0.47126693", "0.4711441", "0.47074133", "0.47067076", "0.47064137", "0.4700199", "0.4699864", "0.4690492", "0.46875668", "0.46869454", "0.4682235", "0.46653384" ]
0.56158775
10
Search term: MAC address or OUI
func (c *Client) Search(term string) (*Response, error) { httpResp, err := c.sendRequest("GET", term, nil) if err != nil { return nil, err } result := &Response{} if httpResp.StatusCode == http.StatusOK { defer httpResp.Body.Close() body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return nil, err } err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result, nil } var ErrNotFound = errors.New("Error with status code " + strconv.Itoa(httpResp.StatusCode)) return nil, ErrNotFound }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func findMacFromIPInArpTable(ip string) string {\n\tfile, err := os.Open(\"/proc/net/arp\")\n\tdefer file.Close()\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to open /proc/net/route\")\n\t}\n\tscanner := bufio.NewScanner(file)\n\tscanner.Split(bufio.ScanLines)\n\n\tscanner.Scan() // skip first line as it's a header\n\n\tfor scanner.Scan() {\n\t\ts := strings.Fields(scanner.Text())\n\t\tif s[0] == ip {\n\t\t\treturn string(s[3]) // we don't expect to find more than one\n\t\t}\n\t}\n\treturn \"\"\n}", "func (oui *OUIMap) Find(mac string) string {\n\tmac = strings.TrimSpace(mac)\n\tmac = strings.ReplaceAll(mac, \":\", \"\")\n\tmac = strings.ReplaceAll(mac, \"-\", \"\")\n\tif len(mac) > 6 {\n\t\tmac = strings.ToUpper(mac)\n\t\tif n, ok := oui.Map[mac[:6]]; ok {\n\t\t\treturn n\n\t\t}\n\t}\n\treturn \"Unknown\"\n}", "func macAddr(primaryIp string) (string, []string, error) {\n var primaryMAC string\n // get all network interfaces\n ifas, err := net.Interfaces()\n if err != nil {\n return \"\", nil, err\n }\n // fetch mac addresses from all interfaces\n var as []string\n for _, ifa := range ifas {\n addrs, err2 := ifa.Addrs()\n if err2 != nil {\n return \"\", nil, fmt.Errorf(\"cannot retrieve list of unicast interface addresses for network interface: %s\", err2)\n }\n // var ip net.IP\n for _, addr := range addrs {\n var ip net.IP\n switch v := addr.(type) {\n case *net.IPNet:\n ip = v.IP\n case *net.IPAddr:\n ip = v.IP\n }\n // process IP address\n if ip.To4() != nil && ip.To4().String() == primaryIp {\n primaryMAC = ifa.HardwareAddr.String()\n break\n }\n }\n a := ifa.HardwareAddr.String()\n if a != \"\" {\n as = append(as, a)\n }\n }\n return primaryMAC, as, nil\n}", "func (rl ReservedAddressList) FindMAC(mac net.HardwareAddr) *ReservedAddress {\n\tfor _, r := range rl {\n\t\tif r.HwAddr.String() == mac.String() {\n\t\t\treturn &r\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *networkInterfaceImpl) Mac(p graphql.ResolveParams) (string, error) {\n\ti := p.Source.(types.NetworkInterface)\n\treturn i.MAC, nil\n}", "func isMAC(fl FieldLevel) bool {\n\t_, err := net.ParseMAC(fl.Field().String())\n\n\treturn err == nil\n}", "func (internet *Internet) MacAddress() string {\n\tvar parts []string\n\tfor i := 0; i < 6; i++ {\n\t\tparts = append(parts, fmt.Sprintf(\"%02x\", internet.faker.random.Intn(256)))\n\t}\n\treturn strings.Join(parts, \":\")\n}", "func getMacAddress() net.HardwareAddr {\n\tinterfaces, err := net.Interfaces()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tfor _, inter := range interfaces {\n\t\tif inter.HardwareAddr != nil && len(inter.HardwareAddr) > 0 && inter.Flags&net.FlagLoopback == 0 && inter.Flags&net.FlagUp != 0 && inter.Flags&net.FlagMulticast != 0 && inter.Flags&net.FlagBroadcast != 0 {\n\t\t\taddrs, _ := inter.Addrs()\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tif addr.String() != \"\" {\n\t\t\t\t\treturn inter.HardwareAddr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"WARNING: didn't find mac address, using default one\")\n\treturn []byte{0x48, 0x5d, 0x60, 0x7c, 0xee, 0x22} //default because we couldn't find the real one\n}", "func parseMAC(s string) net.HardwareAddr {\n\tha, err := net.ParseMAC(s)\n\tpanicIfError(err)\n\treturn ha\n}", "func FindL2oamDevice(macAddress string) L2oamDevice {\n\tmapMutex.Lock()\n\tdefer mapMutex.Unlock()\n\tmac := strings.Replace(macAddress, \":\", \"\", -1)\n\tonu, ok := deviceMap[mac]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn onu\n\n}", "func (l *Libvirt) InterfaceLookupByMacString(Mac string) (rIface Interface, err error) {\n\tvar buf []byte\n\n\targs := InterfaceLookupByMacStringArgs {\n\t\tMac: Mac,\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(129, 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// Iface: Interface\n\t_, err = dec.Decode(&rIface)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func getMacAddr() (addr string) {\n\tinterfaces, err := net.Interfaces()\n\tif err == nil {\n\t\tfor _, i := range interfaces {\n\t\t\tlog.Printf(\"读取窗口信息%v %s %s\", i.Flags, i.Name, i.HardwareAddr.String())\n\n\t\t\tif i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 {\n\t\t\t\t// Don't use random as we have a real address\n\n\t\t\t\taddr = i.HardwareAddr.String()\n\t\t\t\t//break\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func MAC(str string) bool {\n\t_, err := net.ParseMAC(str)\n\treturn err == nil\n}", "func (internet Internet) MacAddress(v reflect.Value) (interface{}, error) {\n\treturn internet.macAddress(), nil\n}", "func ListenMac(filters ...func(iface net.Interface) bool) (net.HardwareAddr, error) {\n\tmac, _, err := ListenAddr(filters...)\n\treturn mac, err\n}", "func getMacAddr(name string) (addr string) {\n\tinterfaces, err := net.Interfaces()\n\tif err == nil {\n\t\tfor _, i := range interfaces {\n\t\t\tif i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 {\n\t\t\t\tif name == i.Name {\n\t\t\t\t\t// Don't use random as we have a real address\n\t\t\t\t\taddr = i.HardwareAddr.String()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func Find(vmName string, purge bool) (string, error) {\n\n\tmac, err := getMACAddr(vmName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Debug(\"found mac: %s for vm: %s\", mac, vmName)\n\tvar pong bool\n\n\tif purge {\n\t\tlog.Debug(\"purge=1, purging...\")\n\t\tif err := ping(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpong = true\n\t}\n\n\tfor {\n\t\tarp, err := getArpTable()\n\n\t\tif log.IsDebugEnabled() {\n\t\t\tlog.Debug(\"here's the arp table:\")\n\n\t\t\tsort.Slice(arp, func(i, j int) bool {\n\t\t\t\treturn arp[i].mac > arp[j].mac\n\t\t\t})\n\n\t\t\tfor _, e := range arp {\n\t\t\t\tlog.Debug(\"IP: %s, MAC: %s\", e.ip, e.mac)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tfor i := len(arp) - 1; i >= 0; i-- {\n\t\t\ta := arp[i]\n\t\t\tif a.mac == mac {\n\t\t\t\treturn a.ip, nil\n\t\t\t}\n\t\t}\n\n\t\tif pong {\n\t\t\tbreak\n\t\t}\n\n\t\tif err := ping(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpong = true\n\t}\n\n\treturn \"\", fmt.Errorf(\"Cannot find ip for %s\\nUse the command 'vermin ip -p %s' to purge cache\", vmName, vmName)\n}", "func main() {\n\t// variables\n\tvar userInput string\n\n\t// Get the input\n\tfmt.Printf(\"Enter the findian string to match : \")\n\t_, err := fmt.Scan(&userInput)\n\n\t// Validate the input\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tuserInputs := strings.ToLower(userInput)\n\tif strings.HasPrefix(userInputs, \"i\") &&\n\t\tstrings.HasSuffix(userInputs, \"n\") &&\n\t\tstrings.Index(userInputs, \"a\") != -1 {\n\n\t\tfmt.Println(\"Found!\")\n\n\t} else {\n\t\tfmt.Println(\"Not Found!\")\n\t}\n\n}", "func Lookup(v interface{}) (string, error) {\n\tvar mac net.HardwareAddr\n\tswitch v.(type) {\n\tcase string:\n\t\tvar err error\n\t\tmac, err = net.ParseMAC(v.(string))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\tcase net.HardwareAddr:\n\t\tmac = v.(net.HardwareAddr)\n\tdefault:\n\t\treturn \"\", errCannotResolveType\n\t}\n\n\tprefix := mac[:3].String()\n\tif val, ok := mapping[strings.ToLower(prefix)]; ok {\n\t\treturn val, nil\n\t}\n\n\treturn \"\", nil\n}", "func Search(query string) ([]http.Header, error) {\n\tconn, err := net.ListenUDP(\"udp\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\treq := strings.Join([]string{\n\t\t\"M-SEARCH * HTTP/1.1\",\n\t\t\"HOST: 239.255.255.250:1900\",\n\t\t\"MAN: \\\"ssdp:discover\\\"\",\n\t\t\"ST: \" + query,\n\t\t\"MX: 1\",\n\t}, \"\\r\\n\")\n\n\taddr, err := net.ResolveUDPAddr(\"udp\", \"239.255.255.250:1900\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = conn.WriteTo([]byte(req), addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn.SetDeadline(time.Now().Add(2 * time.Second))\n\n\tvar devices []http.Header\n\tfor {\n\t\tbuf := make([]byte, 65536)\n\n\t\tn, _, err := conn.ReadFrom(buf)\n\t\tif err, ok := err.(net.Error); ok && err.Timeout() {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Printf(\"ReadFrom error: %s\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tr := bufio.NewReader(bytes.NewReader(buf[:n]))\n\n\t\tresp, err := http.ReadResponse(r, &http.Request{})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ReadResponse error: %s\", err)\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tfor _, head := range resp.Header[\"St\"] {\n\t\t\tif head == query {\n\t\t\t\tdevices = append(devices, resp.Header)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn devices, nil\n}", "func Search(query string) ([]http.Header, error) {\n\tconn, err := net.ListenUDP(\"udp\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\treq := strings.Join([]string{\n\t\t\"M-SEARCH * HTTP/1.1\",\n\t\t\"HOST: 239.255.255.250:1900\",\n\t\t\"MAN: \\\"ssdp:discover\\\"\",\n\t\t\"ST: \" + query,\n\t\t\"MX: 1\",\n\t}, \"\\r\\n\")\n\n\taddr, err := net.ResolveUDPAddr(\"udp\", \"239.255.255.250:1900\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = conn.WriteTo([]byte(req), addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn.SetDeadline(time.Now().Add(2 * time.Second))\n\n\tvar devices []http.Header\n\tfor {\n\t\tbuf := make([]byte, 65536)\n\n\t\tn, _, err := conn.ReadFrom(buf)\n\t\tif err, ok := err.(net.Error); ok && err.Timeout() {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Printf(\"ReadFrom error: %s\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tr := bufio.NewReader(bytes.NewReader(buf[:n]))\n\n\t\tresp, err := http.ReadResponse(r, &http.Request{})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ReadResponse error: %s\", err)\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tfor _, head := range resp.Header[\"St\"] {\n\t\t\tif head == query {\n\t\t\t\tdevices = append(devices, resp.Header)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn devices, nil\n}", "func searchable(s string) string {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\twords := strings.Fields(s)\n\treturn strings.Join(words, \":* & \") + \":*\"\n}", "func MacAddress(opts ...options.OptionFunc) string {\n\treturn singleFakeData(MacAddressTag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\treturn i.macAddress()\n\t}, opts...).(string)\n}", "func (i Internet) MacAddress() string {\n\tvalues := []string{\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\"}\n\n\tmac := make([]string, 0, 6)\n\tfor j := 0; j < 6; j++ {\n\t\tm := i.Faker.RandomStringElement(values)\n\t\tm = m + i.Faker.RandomStringElement(values)\n\t\tmac = append(mac, m)\n\t}\n\n\treturn strings.Join(mac, \":\")\n}", "func FindHardware(searchString string) []Hardware {\n\tresult := []Hardware{}\n\t//TODO: Rewrite query with better security against sql injection\n\t//TODO: Check again if only active devices are shown (archive is shown as well imo)\n\t//TODO: Modifiy so that phones can be found as well (different db table)\n\t//statusid = '11F18C35-FAB2-5802-86CA-B9DF68C41B8F' means the device has the status 'aktiv'\n\terr := db.Select(&result, \"SELECT naam, hostnaam, ref_gebruiker, objecttype, specificatie, ref_lokatie, ipadres, macadres FROM hardware WHERE (naam Like '%\"+searchString+\"%' OR ref_gebruiker Like '%\"+searchString+\"%' OR ipadres Like '%\"+searchString+\"%' OR macadres Like '%\"+searchString+\"%' OR hostnaam Like '%\"+searchString+\"%') AND statusid = '11F18C35-FAB2-5802-86CA-B9DF68C41B8F' AND archiefredenid IS NULL\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn result\n}", "func getInterfaceMatch(ip string) (name string, address net.IP, err error) {\n\tnics, err := net.Interfaces()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, nic := range nics {\n\t\tvar addrs []net.Addr\n\t\taddrs, err = nic.Addrs()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tif addr, ok := addr.(*net.IPNet); ok {\n\t\t\t\tif addr.IP.String() == ip {\n\t\t\t\t\treturn nic.Name, addr.IP, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\terr = fmt.Errorf(\"no match found\")\n\treturn\n}", "func (d *Driver) trimMacAddress(rawUUID string) string {\n\tre := regexp.MustCompile(`[0]([A-Fa-f0-9][:])`)\n\tmac := re.ReplaceAllString(rawUUID, \"$1\")\n\n\treturn mac\n}", "func SearchUniqueNetwork(term string, service service.Network) (*upcloud.Network, error) {\n\tresult, err := SearchNetwork(term, service, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(result) > 1 {\n\t\treturn nil, fmt.Errorf(\"multiple networks matched to query %q, use UUID to specify\", term)\n\t}\n\treturn result[0], nil\n}", "func findInterface(ip string) (string, error) {\n\tiFaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, iFace := range iFaces {\n\t\taddrs, err := iFace.Addrs()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tlogrus.Debugf(\"evaluating if the interface: %s with addresses %v, contains ip: %s\", iFace.Name, addrs, ip)\n\t\tfor _, addr := range addrs {\n\t\t\tif strings.Contains(addr.String(), ip) {\n\t\t\t\treturn iFace.Name, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"no interface has the ip: %s\", ip)\n}", "func MacAddress() string {\n\tblocks := []string{}\n\tfor i := 0; i < 6; i++ {\n\t\tnumber := fmt.Sprintf(\"%02x\", seedAndReturnRandom(255))\n\t\tblocks = append(blocks, number)\n\t}\n\n\treturn strings.Join(blocks, \":\")\n}", "func FindMacs(macsToFind []string) bool {\n\n\tmacListRegex := \"\"\n\n\tfor i := 0; i < len(macsToFind); i++ {\n\t\tmacListRegex += macsToFind[i]\n\n\t\tif i < len(macsToFind)-1 {\n\t\t\tmacListRegex += \"|\"\n\t\t}\n\n\t}\n\n\tres, err := RunCommand(LibConfig.SysCommands[\"ARP\"] + \" -n | \" + LibConfig.SysCommands[\"GREP\"] + \" -iE '\" + macListRegex + \"'\")\n\n\tif err != nil {\n\t\tLogInfo(LibConfig.SysCommands[\"ARP\"] + \" command code: \" + err.Error())\n\t}\n\n\treturn (len(string(res)) > 0)\n\n}", "func dellMAC(u, p, ipmi string) (string, error) {\n\tconst cmd = \"delloem mac\"\n\trc, stdout, _, err := ipmicmd(ipmi, u, p, cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif rc != 0 {\n\t\treturn \"\", err\n\t}\n\tlines := strings.Split(stdout, \"\\n\")\n\tmacs := make([]string, 0, len(lines))\n\tre, err := regexp.Compile(\"^[0-9].*\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, line := range lines {\n\t\tif re.Match([]byte(line)) {\n\t\t\tf := strings.Fields(line)\n\t\t\tmacs = append(macs, f[1])\n\t\t}\n\t}\n\tif len(macs) > 0 {\n\t\tsort.Strings(macs)\n\t\treturn macs[0], nil\n\t}\n\treturn \"\", fmt.Errorf(\"no MAC found\")\n}", "func findAddress(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar incomingAddress string\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t fmt.Println(err)\n\t w.WriteHeader(http.StatusInternalServerError)\n\t return\n\t}\n\n\terr = json.Unmarshal(reqBody, &incomingAddress)\n\tif err != nil {\n\t fmt.Println(\"Err with unmarshalling request in findaddress method: %v \\n\", err)\n\t}\n\taddress := strings.Split(incomingAddress, \"@\")\n\t//searches through servers to find one that matches, returns both the MSA and MTA address ready for use by the MTA\n\tfor _, singleServer := range servers {\n\t\tif singleServer.Address == address[1] {\n\t\t\tjson.NewEncoder(w).Encode(singleServer.MsaAddress+\"|\"+singleServer.MtaAddress)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Printf(\"No server found in BBS - err: %v\", http.StatusNoContent)\n\tw.WriteHeader(http.StatusNoContent)\n\treturn\n}", "func ListenMac(filters ...func(iface net.Interface) bool) (net.HardwareAddr, error) {\n\treturn net_.ListenMac(filters...)\n}", "func SearchNetwork(term string, service service.Network, unique bool) ([]*upcloud.Network, error) {\n\tvar result []*upcloud.Network\n\n\tif len(cachedNetworks) == 0 {\n\t\tnetworks, err := service.GetNetworks()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcachedNetworks = networks.Networks\n\t}\n\n\tfor _, n := range cachedNetworks {\n\t\tnetwork := n\n\t\tif network.UUID == term || network.Name == term {\n\t\t\tresult = append(result, &network)\n\t\t}\n\t}\n\tif len(result) == 0 {\n\t\treturn nil, fmt.Errorf(\"no network was found with %s\", term)\n\t}\n\tif len(result) > 1 && unique {\n\t\treturn nil, fmt.Errorf(\"multiple networks matched to query %q, use UUID to specify\", term)\n\t}\n\n\treturn result, nil\n}", "func (me TxsdAddressSimpleContentExtensionCategory) IsMac() bool { return me.String() == \"mac\" }", "func findInterfaceReach(dest string) (string, error) {\n\tdestUdpAddress := fmt.Sprintf(\"[%s]:80\", dest)\n\tconn, err := net.Dial(\"udp4\", destUdpAddress)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer conn.Close()\n\n\tlocalAddress := conn.LocalAddr()\n\tif localAddress == nil {\n\t\treturn \"\", fmt.Errorf(\"no interface can route IP: %s\", dest)\n\t}\n\n\tfoundIf, err := findInterface(strings.Split(localAddress.String(), \":\")[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn foundIf, nil\n}", "func filterMibbit(v string) string {\n\tif !regMibbit.MatchString(v) {\n\t\treturn v\n\t}\n\n\tidx := strings.Index(v, \"@\")\n\tif idx == -1 {\n\t\treturn v\n\t}\n\n\taddr := strings.TrimSpace(v[:idx])\n\tif len(addr) != 8 {\n\t\treturn v\n\t}\n\n\ta, ea := strconv.ParseUint(addr[:2], 16, 8)\n\tb, eb := strconv.ParseUint(addr[2:4], 16, 8)\n\tc, ec := strconv.ParseUint(addr[4:6], 16, 8)\n\td, ed := strconv.ParseUint(addr[6:], 16, 8)\n\n\tif ea != nil || eb != nil || ec != nil || ed != nil {\n\t\treturn v\n\t}\n\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\", a, b, c, d)\n}", "func checkResults(max int, c chan string) {\n\tcurrent := 0\n\tfor {\n\t\tfmt.Print(<-c + \", \")\n\t\tcurrent++\n\t\tif current == max {\n\t\t\tfmt.Println(\"\\n\\nDone scanning, checking MACs...\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// execute arp -a and grap output of it\n\toutput, _ := exec.Command(\"arp\", \"-a\").Output()\n\tsplitted := strings.Split(string(output), \"\\n\")\n\n\t// get lines with cockpit/a4w MACs\n\tfmt.Println(\"IPs matching Cockpit/A4W MAC:\")\n\tfor _, v := range splitted {\n\t\tmatch := strings.TrimSpace(arpPattern.FindString(v))\n\t\tif len(match) > 5{\n\t\t\tfmt.Println(strings.TrimSpace(arpPattern.FindString(match)))\t\t\n\t\t}\n\t}\n}", "func IsMAC(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\t_, err := net.ParseMAC(s)\n\treturn err == nil\n}", "func IsMAC(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\t_, err := net.ParseMAC(s)\n\treturn err == nil\n}", "func getAddress(str []byte) (address string){\n\thash :=userlib.NewSHA256()\n\thash.Write(str)\n\taddress = hex.EncodeToString(hash.Sum(nil))\n\treturn\n}", "func (c *moovWatchmanClient) Search(ctx context.Context, name string, requestID string) (*watchman.OfacSdn, error) {\n\tindividualSearch, err := c.ofacSearch(ctx, name, \"individual\", requestID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tentitySearch, err := c.ofacSearch(ctx, name, \"entity\", requestID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearch := highestOfacSearchMatch(individualSearch, entitySearch)\n\n\tif search == nil || (len(search.SDNs) == 0 && len(search.AltNames) == 0) {\n\t\treturn nil, nil // Nothing found\n\t}\n\n\t// We prefer to return the SDN, but if there's an AltName with a higher match return that instead.\n\tif len(search.SDNs) > 0 && len(search.AltNames) == 0 {\n\t\treturn &search.SDNs[0], nil // return SDN as it was all we got\n\t}\n\t// Take an Alt and find the SDN for it if that was the highest match\n\tif len(search.SDNs) == 0 && len(search.AltNames) > 0 {\n\t\talt := search.AltNames[0]\n\t\tc.logger.Log(fmt.Sprintf(\"Found AltName=%s,SDN=%s with no higher matched SDNs\", alt.AlternateID, alt.EntityID))\n\t\treturn c.altToSDN(ctx, search.AltNames[0], requestID)\n\t}\n\t// AltName matched higher than SDN names, so return the SDN of the matched AltName\n\tif len(search.SDNs) > 0 && len(search.AltNames) > 0 && (search.AltNames[0].Match > 0.1) && search.AltNames[0].Match > search.SDNs[0].Match {\n\t\talt := search.AltNames[0]\n\t\tc.logger.Log(fmt.Sprintf(\"AltName=%s,SDN=%s had higher match than SDN=%s\", alt.AlternateID, alt.EntityID, search.SDNs[0].EntityID))\n\t\treturn c.altToSDN(ctx, alt, requestID)\n\t}\n\t// Return the SDN as Alts matched lower\n\tif len(search.SDNs) > 0 {\n\t\treturn &search.SDNs[0], nil\n\t}\n\n\treturn nil, nil // Nothing found\n}", "func TestSearch(t *testing.T) {\n\tp := playback{\n\t\tDevices: []Address{\n\t\t\t0x0000000000000000,\n\t\t\t0x0000000000000001,\n\t\t\t0x0010000000000000,\n\t\t\t0x0000100000000000,\n\t\t\t0xffffffffffffffff,\n\t\t\t0xfc0000013199a928,\n\t\t\t0xf100000131856328,\n\t\t},\n\t}\n\t// Fix-up the CRC byte for each device.\n\tvar buf [8]byte\n\tfor i := range p.Devices {\n\t\tbinary.LittleEndian.PutUint64(buf[:], uint64(p.Devices[i]))\n\t\tcrc := CalcCRC(buf[:7])\n\t\tp.Devices[i] = (Address(crc) << 56) | (p.Devices[i] & 0x00ffffffffffffff)\n\t}\n\n\t// We're doing one search operation per device, plus a last one.\n\tp.Ops = make([]IO, len(p.Devices)+1)\n\tfor i := 0; i < len(p.Ops); i++ {\n\t\tp.Ops[i] = IO{Write: []byte{0xf0}, Pull: WeakPullup}\n\t}\n\n\t// Start search.\n\tif err := p.Tx([]byte{0xf0}, nil, WeakPullup); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Perform search.\n\taddrs, err := p.Search(false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify we got all devices.\n\tif len(addrs) != len(p.Devices) {\n\t\tt.Fatalf(\"expected %d devices, got %d\", len(p.Devices), len(addrs))\n\t}\nmatch:\n\tfor _, ai := range p.Devices {\n\t\tfor _, aj := range addrs {\n\t\t\tif ai == aj {\n\t\t\t\tcontinue match\n\t\t\t}\n\t\t}\n\t\tt.Errorf(\"expected to find %#x but didn't\", ai)\n\t}\n\tif err := p.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (_class PIFClass) GetMAC(sessionID SessionRef, self PIFRef) (_retval string, _err error) {\n\t_method := \"PIF.get_MAC\"\n\t_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"session_id\"), sessionID)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_selfArg, _err := convertPIFRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"self\"), self)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_retval, _err = convertStringToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func (m MAC) String() string {\n\treturn net.HardwareAddr(m).String()\n}", "func vmIDtoMacAddr(vmID uint) string {\n\tvar addrParts []string\n\n\t// mac addresses have 6 hex components separate by \":\", i.e. \"11:22:33:44:55:66\"\n\tnumMacAddrComponents := uint(6)\n\n\tfor n := uint(0); n < numMacAddrComponents; n++ {\n\t\t// To isolate the value of the nth component, right bit shift the vmID by 8*n (there are 8 bits per component) and\n\t\t// mask out any upper bits leftover (bitwise AND with 255)\n\t\taddrComponent := (vmID >> (8 * n)) & 255\n\n\t\t// format the component as a two-digit hex string\n\t\taddrParts = append(addrParts, fmt.Sprintf(\"%02x\", addrComponent))\n\t}\n\n\treturn strings.Join(addrParts, \":\")\n}", "func registryLookupServiceOnInterface(address *net.TCPAddr, intf net.Interface, ch chan int) {\n\tresponse := LookupAddressResponse{*address}\n\tbuffer := make([]byte, PACKET_SIZE)\n\n\tconnection, err := net.ListenMulticastUDP(UDP_PROTOCOL, &intf, MULTICAT_ADDR)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer connection.Close()\n\n\tbytes, err := json.Marshal(response)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor {\n\t\t_, sender, err := connection.ReadFromUDP(buffer)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = connection.WriteToUDP(bytes, sender)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t\n\tch <- 0\n}", "func cleanMacAddress(macAddress string) string {\n\treg, err := regexp.Compile(\"[^A-Za-z0-9]+\")\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t}\n\n\tcleanedMacAddress := strings.ToLower(strings.TrimSpace(reg.ReplaceAllString(macAddress, \"\")))\n\n\tif len(cleanedMacAddress) > 12 {\n\t\tcleanedMacAddress = cleanedMacAddress[0:12]\n\t}\n\n\treturn cleanedMacAddress\n}", "func FindIPAddressType(ip string) string {\n\tif strings.Count(ip, \":\") >= 1 {\n\t\treturn IpTypeIpv6\n\t} else {\n\t\treturn IpTypeIpv4\n\t}\n}", "func searchAppSubstring(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {\n\tapp_str := r.FormValue(\"search\")\n\t// app_str2 := r.FormValue(\"test2\")\n\tfmt.Println(\"searching for substring in apps: \", app_str)\n\n\tc := db.C(\"machines\")\n\n\tcontext := make([]appResult, 0, 10)\n\tvar res *appResult\n\n\tp := \"^.*\" + app_str + \".*\"\n\n\tfmt.Println(\"query: \", p)\n\t// m := bson.M{} \n\tif len(app_str) == 0 {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\terr := c.Find(bson.M{\"apps._name\": &bson.RegEx{Pattern: p, Options: \"i\"}}).\n\t\tSelect(bson.M{\n\t\t\"hostname\": 1,\n\t\t\"apps\": 1,\n\t\t\"_id\": 1}).\n\t\tSort(\"hostname\").\n\t\tFor(&res, func() error {\n\t\tres.Apps = fuzzyFilter_apps(app_str, res.Apps)\n\t\tcontext = append(context, *res)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tset.ExecuteTemplate(w, \"searchresults\", context)\n}", "func getMacAddr() ([]string, error) {\n\tifas, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar as []string\n\tfor _, ifa := range ifas {\n\t\ta := ifa.HardwareAddr.String()\n\t\tif a != \"\" {\n\t\t\tas = append(as, a)\n\t\t}\n\t}\n\treturn as, nil\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetMacAddress() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.MacAddress\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetMacAddressOk() ([]string, bool) {\n\tif o == nil || o.MacAddress == nil {\n\t\treturn nil, false\n\t}\n\treturn o.MacAddress, true\n}", "func GetNicMAC() (mac string) {\n\tvar macs []string\n\t// get all the system's or local machine's network interfaces\n\tinterfaces, _ := net.Interfaces()\n\tvar err error\n\tfor _, interf := range interfaces {\n\t\t// Skip virtual interfaces.\n\t\tsymInterf := filepath.Join(\"/sys/class/net\", interf.Name)\n\t\tvar realInterf string\n\t\tif realInterf, err = filepath.EvalSymlinks(symInterf); err != nil {\n\t\t\tlog.Warnf(\"%v is broken, skip\", symInterf)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Index(realInterf, \"devices/virtual\") >= 0 {\n\t\t\tlog.Debugf(\"%v is virtual, skip\", symInterf)\n\t\t\tcontinue\n\t\t}\n\n\t\tif addrs, err := interf.Addrs(); err == nil {\n\t\t\tif len(interf.HardwareAddr) == 0 {\n\t\t\t\t// There's no MAC for tun interfaces.\n\t\t\t\tlog.Debugf(\"interface %v doesn't have hardware address, skip\", interf.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Nil slice: its len is zero, and it's fine to append.\n\t\t\tvar currentIP []string\n\t\t\tfor _, addr := range addrs {\n\t\t\t\t// check the address type and if it is not a loopback the display it\n\t\t\t\t// = GET LOCAL IP ADDRESS\n\t\t\t\tif ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\t\t\tcurrentIP = append(currentIP, ipnet.IP.String())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif currentIP == nil {\n\t\t\t\tlog.Debugf(\"interface %v doesn't have non-loopback IPv4 address, skip\", interf.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Debugf(\"interface %v, MAC %v, IP %v\", interf.Name, hex.EncodeToString(interf.HardwareAddr), currentIP)\n\t\t\tmacs = append(macs, hex.EncodeToString(interf.HardwareAddr))\n\t\t}\n\t}\n\tif len(macs) != 0 {\n\t\tsort.Strings(macs)\n\t\tmac = macs[0]\n\t}\n\treturn\n}", "func OperAddrToOtherAddr(operaddr string) [6]string {\n\n\thexOperaddr := RunFromBech32(operaddr)\n\tkeys := RunFromHex(hexOperaddr)\n\n\treturn keys\n}", "func DeviceMac(key Key, macaddr string, endtime time.Time, limit int64) (APIDeviceMacResponse, error) {\n\tvar ar APIDeviceMacResponse\n\tapiurl := APIEP + \"/devices/\" + macaddr + \"?endDate=\" + url.QueryEscape(endtime.Format(time.RFC3339)) +\n\t\t\"&limit=\" + fmt.Sprintf(\"%d\", limit) + \"&applicationKey=\" + key.applicationKey +\n\t\t\"&apiKey=\" + key.apiKey\n\tstartTime := time.Now()\n\tresp, err := httpGet(apiurl)\n\tar.ResponseTime = time.Since(startTime)\n\tif err != nil {\n\t\treturn ar, err\n\t}\n\tar.HTTPResponseCode = resp.StatusCode\n\tar.JSONResponse, err = io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn ar, err\n\t}\n\tswitch resp.StatusCode {\n\tcase 200:\n\tcase 429, 502, 503:\n\t\t{\n\t\t\tif resp.StatusCode >= 500 {\n\t\t\t\tif resp.StatusCode >= 500 {\n\t\t\t\t\tar.JSONResponse, _ = json.Marshal(\n\t\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\t\"{\\\"errormessage\\\": \\\"HTTP Error Code: %d\\\"}\", resp.StatusCode,\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\treturn ar, nil\n\t\t}\n\tdefault:\n\t\t{\n\t\t\t_, err := fmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"ambient.DeviceMac: HTTPResponseCode=%d\\n\"+\n\t\t\t\t\t\"Full Response:\\n%+v\",\n\t\t\t\tresp.StatusCode, resp,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn APIDeviceMacResponse{}, err\n\t\t\t}\n\t\t\treturn ar, errors.New(\"bad non-200/429/502/503 Response Code\")\n\t\t}\n\t}\n\terr = json.Unmarshal(ar.JSONResponse, &ar.Record)\n\tif err != nil {\n\t\treturn ar, err\n\t}\n\tvar DeviceInterface interface{}\n\terr = json.Unmarshal(ar.JSONResponse, &DeviceInterface)\n\tif err != nil {\n\t\treturn ar, err\n\t}\n\tDeviceMap := DeviceInterface.([]interface{})\n\tRDF := make([]map[string]interface{}, len(DeviceMap))\n\tfor key, value := range DeviceMap {\n\t\tRDF[key] = make(map[string]interface{})\n\t\tswitch value2 := value.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tfor k2, v2 := range value2 {\n\t\t\t\tRDF[key][k2] = v2\n\t\t\t}\n\t\t}\n\t}\n\tar.RecordFields = RDF\n\treturn ar, nil\n}", "func TestNewTenantHardwareAddr(t *testing.T) {\n\tip := net.ParseIP(\"172.16.0.2\")\n\texpectedMAC := \"02:00:ac:10:00:02\"\n\thw := newTenantHardwareAddr(ip)\n\tif hw.String() != expectedMAC {\n\t\tt.Error(\"Expected: \", expectedMAC, \" Received: \", hw.String())\n\t}\n}", "func interfaceByIP(ip string) (string, int, error) {\n\tifaces, err := netInterfaces()\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\tfor _, iface := range ifaces {\n\t\tifaceIP, mask, err := ipByInterface(iface.Name)\n\t\tif err == nil && ip == ifaceIP {\n\t\t\treturn iface.Name, mask, nil\n\t\t}\n\t}\n\n\treturn \"\", 0, fmt.Errorf(\"no matching interface found for IP %s\", ip)\n}", "func (s *Server) handleMacLookup(vpcID uint32, mac net.HardwareAddr) {\n\tgw, err := s.sdn.LookupMac(vpcID, mac)\n\tif err != nil || gw == nil {\n\t\tlog.Printf(\"Failed to find VTEP for %s\", mac)\n\t\treturn\n\t}\n\n\ts.transport.AddForwardEntry(vpcID, mac, gw)\n}", "func Find(vmName string, purge bool) (string, error) {\n\n\tmac, err := getMACAddr(vmName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar pong bool\n\n\tif purge {\n\t\tping()\n\t\tpong = true\n\t}\n\n\tfor {\n\t\tarp, err := getArpTable()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tfor i := len(arp) - 1; i >= 0; i-- {\n\t\t\ta := arp[i]\n\t\t\tif a.mac == mac {\n\t\t\t\treturn a.ip, nil\n\t\t\t}\n\t\t}\n\n\t\tif pong {\n\t\t\tbreak\n\t\t}\n\n\t\tping()\n\t\tpong = true\n\t}\n\n\treturn \"\", fmt.Errorf(\"Cannot find ip for %s\\nUse the command 'vermin ip -p %s' to purge cache\", vmName, vmName)\n}", "func GetAddress(ifname string, query IPTypeQuery) ([]string, error) {\n\ti, err := net.InterfaceByName(ifname)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get interface %s: %s\", ifname, err)\n\t}\n\taddrs, err := i.Addrs()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get address for %s: %s\", ifname, err)\n\t}\n\tlist := []string{}\n\tfor _, a := range addrs {\n\t\tipnet := a.(*net.IPNet)\n\t\tip := ipnet.IP\n\t\tif ip.IsLoopback() && !query.IsLoopback {\n\t\t\tcontinue\n\t\t}\n\t\tif ip.IsLinkLocalUnicast() && !query.IsLinklocal {\n\t\t\tcontinue\n\t\t}\n\t\tif ip.IsLinkLocalMulticast() && !query.IsLinklocal {\n\t\t\tcontinue\n\t\t}\n\t\tif ip.IsMulticast() && !query.IsMulticast {\n\t\t\tcontinue\n\t\t}\n\t\tif ip.To4() != nil && !query.IsIPv4 {\n\t\t\tcontinue\n\t\t}\n\t\tif ip.To4() == nil && !query.IsIPv6 {\n\t\t\tcontinue\n\t\t}\n\t\tlist = append(list, ip.String())\n\t}\n\treturn list, nil\n}", "func getAddr(ifname string) string {\n\tiface, err := net.InterfaceByName(ifname)\n\tif err != nil {\n\t\tlog.Printf(\"error obtaining interface %v\\n\", ifname)\n\t\tpanic(err)\n\t}\n\taddrs, err := iface.Addrs()\n\tif err != nil {\n\t\tlog.Printf(\"error obtaining address for interface %v\\n\", ifname)\n\t\tpanic(err)\n\t}\n\tfor _, a := range addrs {\n\t\t// skip IPv6 addresses\n\t\tif !strings.Contains(a.String(), \":\") {\n\t\t\tip, _, err := net.ParseCIDR(a.String())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn ip.String()\n\t\t}\n\t}\n\treturn \"\"\n}", "func (ns *NetworkServer) matchDevice(ctx context.Context, up *ttnpb.UplinkMessage) (*matchedDevice, error) {\n\tif len(up.RawPayload) < 4 {\n\t\treturn nil, errRawPayloadTooShort\n\t}\n\tmacPayloadBytes := up.RawPayload[:len(up.RawPayload)-4]\n\n\tpld := up.Payload.GetMACPayload()\n\n\tlogger := log.FromContext(ctx).WithFields(log.Fields(\n\t\t\"dev_addr\", pld.DevAddr,\n\t\t\"uplink_f_cnt\", pld.FCnt,\n\t\t\"payload_length\", len(macPayloadBytes),\n\t))\n\n\tvar addrMatches []matchedDevice\n\tif err := ns.devices.RangeByAddr(ctx, pld.DevAddr,\n\t\t[]string{\n\t\t\t\"frequency_plan_id\",\n\t\t\t\"lorawan_phy_version\",\n\t\t\t\"mac_settings.resets_f_cnt\",\n\t\t\t\"mac_settings.supports_32_bit_f_cnt\",\n\t\t\t\"mac_state\",\n\t\t\t\"multicast\",\n\t\t\t\"pending_mac_state\",\n\t\t\t\"pending_session\",\n\t\t\t\"recent_downlinks\",\n\t\t\t\"recent_uplinks\",\n\t\t\t\"session\",\n\t\t},\n\t\tfunc(dev *ttnpb.EndDevice) bool {\n\t\t\tif dev.Multicast {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif dev.Session != nil && dev.MACState != nil && dev.Session.DevAddr == pld.DevAddr {\n\t\t\t\taddrMatches = append(addrMatches, matchedDevice{\n\t\t\t\t\tDevice: dev,\n\t\t\t\t\tSession: dev.Session,\n\t\t\t\t\tMACState: dev.MACState,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif dev.PendingSession != nil && dev.PendingMACState != nil && dev.PendingSession.DevAddr == pld.DevAddr {\n\t\t\t\tif dev.Session != nil && dev.MACState != nil && dev.Session.DevAddr == pld.DevAddr {\n\t\t\t\t\tlogger.Warn(\"Same DevAddr was assigned to a device in two consecutive sessions\")\n\t\t\t\t}\n\t\t\t\taddrMatches = append(addrMatches, matchedDevice{\n\t\t\t\t\tDevice: dev,\n\t\t\t\t\tSession: dev.PendingSession,\n\t\t\t\t\tMACState: dev.PendingMACState,\n\t\t\t\t\tPending: true,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn true\n\n\t\t}); err != nil {\n\t\tlogger.WithError(err).Warn(\"Failed to find devices in registry by DevAddr\")\n\t\treturn nil, err\n\t}\n\tif len(addrMatches) == 0 {\n\t\tlogger.Debug(\"No device matched DevAddr\")\n\t\treturn nil, errDeviceNotFound\n\t}\n\n\ttype device struct {\n\t\tmatchedDevice\n\t\tgap uint32\n\t\tfCntReset bool\n\t}\n\tmatched := make([]device, 0, len(addrMatches))\n\n\tfor _, match := range addrMatches {\n\t\tsupports32BitFCnt := true\n\t\tif match.Device.GetMACSettings().GetSupports32BitFCnt() != nil {\n\t\t\tsupports32BitFCnt = match.Device.MACSettings.Supports32BitFCnt.Value\n\t\t} else if ns.defaultMACSettings.GetSupports32BitFCnt() != nil {\n\t\t\tsupports32BitFCnt = ns.defaultMACSettings.Supports32BitFCnt.Value\n\t\t}\n\n\t\tfCnt := pld.FCnt\n\t\tswitch {\n\t\tcase !supports32BitFCnt, fCnt >= match.Session.LastFCntUp, fCnt == 0:\n\t\tcase fCnt > match.Session.LastFCntUp&0xffff:\n\t\t\tfCnt |= match.Session.LastFCntUp &^ 0xffff\n\t\tcase match.Session.LastFCntUp < 0xffff0000:\n\t\t\tfCnt |= (match.Session.LastFCntUp + 0x10000) &^ 0xffff\n\t\t}\n\n\t\tmaxNbTrans := maxTransmissionNumber(match.MACState.LoRaWANVersion, up.Payload.MType == ttnpb.MType_CONFIRMED_UP, match.MACState.CurrentParameters.ADRNbTrans)\n\t\tlogger := logger.WithFields(log.Fields(\n\t\t\t\"device_uid\", unique.ID(ctx, match.Device.EndDeviceIdentifiers),\n\t\t\t\"last_f_cnt_up\", match.Session.LastFCntUp,\n\t\t\t\"mac_version\", match.MACState.LoRaWANVersion,\n\t\t\t\"max_transmissions\", maxNbTrans,\n\t\t\t\"pending_session\", match.Pending,\n\t\t))\n\n\t\tswitch {\n\t\tcase fCnt == match.Session.LastFCntUp:\n\t\t\tnbTrans, lastAt := transmissionNumber(macPayloadBytes, match.Device.RecentUplinks...)\n\t\t\tlogger = logger.WithFields(log.Fields(\n\t\t\t\t\"f_cnt_gap\", 0,\n\t\t\t\t\"full_f_cnt_up\", match.Session.LastFCntUp,\n\t\t\t\t\"transmission\", nbTrans,\n\t\t\t))\n\t\t\tif !lastAt.IsZero() {\n\t\t\t\tmaxDelay := maxRetransmissionDelay(match.MACState.CurrentParameters.Rx1Delay)\n\t\t\t\tdelay := up.ReceivedAt.Sub(lastAt)\n\n\t\t\t\tlogger = logger.WithFields(log.Fields(\n\t\t\t\t\t\"last_transmission_at\", lastAt,\n\t\t\t\t\t\"max_retransmission_delay\", maxDelay,\n\t\t\t\t\t\"retransmission_delay\", delay,\n\t\t\t\t))\n\n\t\t\t\tif delay > maxDelay {\n\t\t\t\t\tlogger.Error(\"Retransmission delay exceeds maximum, skip\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nbTrans > maxNbTrans {\n\t\t\t\tlogger.Error(\"Transmission number exceeds maximum, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmatch.FCnt = match.Session.LastFCntUp\n\t\t\tmatch.NbTrans = nbTrans\n\t\t\tmatch.logger = logger\n\t\t\tmatched = append(matched, device{\n\t\t\t\tmatchedDevice: match,\n\t\t\t})\n\n\t\tcase fCnt < match.Session.LastFCntUp:\n\t\t\tlogger = logger.WithFields(log.Fields(\n\t\t\t\t\"full_f_cnt_up\", pld.FCnt,\n\t\t\t\t\"transmission\", 1,\n\t\t\t))\n\n\t\t\tif !resetsFCnt(match.Device, ns.defaultMACSettings) {\n\t\t\t\tlogger.Debug(\"FCnt too low, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, phy, err := getDeviceBandVersion(match.Device, ns.FrequencyPlans)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Warn(\"Failed to get device's versioned band, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif match.MACState.LoRaWANVersion.HasMaxFCntGap() && uint(pld.FCnt) > phy.MaxFCntGap {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar gap uint32\n\t\t\tif math.MaxUint32-match.Session.LastFCntUp < pld.FCnt {\n\t\t\t\tgap = match.Session.LastFCntUp + pld.FCnt\n\t\t\t} else {\n\t\t\t\tgap = math.MaxUint32\n\t\t\t}\n\t\t\tmatch.FCnt = pld.FCnt\n\t\t\tmatch.NbTrans = 1\n\t\t\tmatch.logger = logger.WithField(\"f_cnt_gap\", gap)\n\t\t\tmatched = append(matched, device{\n\t\t\t\tmatchedDevice: match,\n\t\t\t\tfCntReset: true,\n\t\t\t\tgap: gap,\n\t\t\t})\n\n\t\tdefault:\n\t\t\tlogger = logger.WithField(\"transmission\", 1)\n\n\t\t\t_, phy, err := getDeviceBandVersion(match.Device, ns.FrequencyPlans)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithField(\"full_f_cnt_up\", fCnt).WithError(err).Warn(\"Failed to get device's versioned band, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fCnt != pld.FCnt &&\n\t\t\t\tresetsFCnt(match.Device, ns.defaultMACSettings) &&\n\t\t\t\t(!match.MACState.LoRaWANVersion.HasMaxFCntGap() || uint(pld.FCnt) <= phy.MaxFCntGap) {\n\n\t\t\t\tvar gap uint32\n\t\t\t\tif math.MaxUint32-match.Session.LastFCntUp < pld.FCnt {\n\t\t\t\t\tgap = match.Session.LastFCntUp + pld.FCnt\n\t\t\t\t} else {\n\t\t\t\t\tgap = math.MaxUint32\n\t\t\t\t}\n\t\t\t\tmatch.FCnt = pld.FCnt\n\t\t\t\tmatch.NbTrans = 1\n\t\t\t\tmatch.logger = logger.WithFields(log.Fields(\n\t\t\t\t\t\"f_cnt_gap\", gap,\n\t\t\t\t\t\"full_f_cnt_up\", pld.FCnt,\n\t\t\t\t))\n\t\t\t\tmatched = append(matched, device{\n\t\t\t\t\tmatchedDevice: match,\n\t\t\t\t\tfCntReset: true,\n\t\t\t\t\tgap: gap,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tgap := fCnt - match.Session.LastFCntUp\n\t\t\tlogger = logger.WithFields(log.Fields(\n\t\t\t\t\"f_cnt_gap\", gap,\n\t\t\t\t\"full_f_cnt_up\", fCnt,\n\t\t\t))\n\t\t\tif match.MACState.LoRaWANVersion.HasMaxFCntGap() && uint(gap) > phy.MaxFCntGap {\n\t\t\t\tlogger.Debug(\"FCnt gap too high, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmatch.FCnt = fCnt\n\t\t\tmatch.NbTrans = 1\n\t\t\tmatch.logger = logger\n\t\t\tmatched = append(matched, device{\n\t\t\t\tmatchedDevice: match,\n\t\t\t\tgap: gap,\n\t\t\t})\n\t\t}\n\t}\n\tsort.Slice(matched, func(i, j int) bool {\n\t\tif matched[i].gap != matched[j].gap {\n\t\t\treturn matched[i].gap < matched[j].gap\n\t\t}\n\t\tif matched[i].fCntReset != matched[j].fCntReset {\n\t\t\treturn matched[j].fCntReset\n\t\t}\n\t\treturn matched[i].Session.LastFCntUp < matched[j].Session.LastFCntUp\n\t})\n\n\tlogger.WithField(\"device_count\", len(matched)).Debug(\"Perform MIC checks on devices with matching frame counters\")\n\tfor i, match := range matched {\n\t\tlogger := match.logger.WithField(\"match_attempt\", i)\n\n\t\tif pld.Ack {\n\t\t\tif len(match.Device.RecentDownlinks) == 0 {\n\t\t\t\t// Uplink acknowledges a downlink, but no downlink was sent to the device,\n\t\t\t\t// hence it must be the wrong device.\n\t\t\t\tlogger.Debug(\"Uplink contains ACK, but no downlink was sent to device, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif match.Session.FNwkSIntKey == nil || len(match.Session.FNwkSIntKey.Key) == 0 {\n\t\t\tlogger.Warn(\"Device missing FNwkSIntKey in registry, skip\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfNwkSIntKey, err := cryptoutil.UnwrapAES128Key(*match.Session.FNwkSIntKey, ns.KeyVault)\n\t\tif err != nil {\n\t\t\tlogger.WithField(\"kek_label\", match.Session.FNwkSIntKey.KEKLabel).WithError(err).Warn(\"Failed to unwrap FNwkSIntKey, skip\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif match.fCntReset {\n\t\t\t// TODO: Handle MAC state reset(https://github.com/TheThingsNetwork/lorawan-stack/issues/505)\n\t\t}\n\n\t\tvar computedMIC [4]byte\n\t\tif match.MACState.LoRaWANVersion.Compare(ttnpb.MAC_V1_1) < 0 {\n\t\t\tcomputedMIC, err = crypto.ComputeLegacyUplinkMIC(\n\t\t\t\tfNwkSIntKey,\n\t\t\t\tpld.DevAddr,\n\t\t\t\tmatch.FCnt,\n\t\t\t\tmacPayloadBytes,\n\t\t\t)\n\t\t} else {\n\t\t\tif match.Session.SNwkSIntKey == nil || len(match.Session.SNwkSIntKey.Key) == 0 {\n\t\t\t\tlogger.Warn(\"Device missing SNwkSIntKey in registry, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdrIdx, err := searchDataRate(up.Settings.DataRate, match.Device, ns.FrequencyPlans)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Debug(\"Failed to determine data rate index of uplink\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchIdx, err := searchUplinkChannel(up.Settings.Frequency, match.MACState)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Debug(\"Failed to determine channel index of uplink\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsNwkSIntKey, err := cryptoutil.UnwrapAES128Key(*match.Session.SNwkSIntKey, ns.KeyVault)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithField(\"kek_label\", match.Session.SNwkSIntKey.KEKLabel).WithError(err).Warn(\"Failed to unwrap SNwkSIntKey, skip\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar confFCnt uint32\n\t\t\tif pld.Ack {\n\t\t\t\tconfFCnt = match.Session.LastConfFCntDown\n\t\t\t}\n\t\t\tcomputedMIC, err = crypto.ComputeUplinkMIC(\n\t\t\t\tsNwkSIntKey,\n\t\t\t\tfNwkSIntKey,\n\t\t\t\tconfFCnt,\n\t\t\t\tuint8(drIdx),\n\t\t\t\tchIdx,\n\t\t\t\tpld.DevAddr,\n\t\t\t\tmatch.FCnt,\n\t\t\t\tmacPayloadBytes,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"Failed to compute MIC\")\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(up.Payload.MIC, computedMIC[:]) {\n\t\t\tlogger.Debug(\"MIC mismatch\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif match.FCnt == math.MaxUint32 {\n\t\t\treturn nil, errFCntTooHigh\n\t\t}\n\t\treturn &match.matchedDevice, nil\n\t}\n\treturn nil, errDeviceNotFound\n}", "func ipFind(ip string) string {\n\tr := regexp.MustCompile(`\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b`)\n\treturn r.FindString(ip)\n}", "func searchExact(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {\n\tkey := r.FormValue(\"key\")\n\tval := r.FormValue(\"val\")\n\n\tcontext := make([]appResult, 0, 10)\n\tvar res *appResult\n\n\tc := db.C(\"machines\")\n\tvar usePath bool\n\tif key == \"apps.path\" {\n\t\tusePath = true\n\t}\n\n\terr := c.Find(bson.M{key: val}).\n\t\tSelect(bson.M{\n\t\t\"hostname\": 1,\n\t\t\"apps\": 1,\n\t\t\"_id\": 1}).\n\t\tSort(\"hostname\").\n\t\tFor(&res, func() error {\n\t\tres.Apps = filter_apps(val, res.Apps, usePath)\n\t\tcontext = append(context, *res)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tset.ExecuteTemplate(w, \"searchresults\", context)\n}", "func listenAddr(interfaces []net.Interface, filter func(iface net.Interface) bool) (net.HardwareAddr, net.IP, error) {\n\tif filter == nil {\n\t\tfilter = func(iface net.Interface) bool { return true }\n\t}\n\tbestScore := -1\n\tvar bestIP net.IP\n\tvar bestMac net.HardwareAddr\n\t// Select the highest scoring IP as the best IP.\n\tfor _, iface := range interfaces {\n\t\tif !filter(iface) {\n\t\t\tcontinue\n\t\t}\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\t// Skip this interface if there is an error.\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tscore, ip := ScoreAddr(iface, addr)\n\t\t\tif score > bestScore {\n\t\t\t\tbestScore = score\n\t\t\t\tbestIP = ip\n\t\t\t\tbestMac = iface.HardwareAddr\n\t\t\t}\n\t\t}\n\t}\n\n\tif bestScore == -1 {\n\t\treturn nil, nil, errors.New(\"no addresses to listen on\")\n\t}\n\n\treturn bestMac, bestIP, nil\n}", "func FindHostDevice(pciAddress, name string, namespaces ...netns.NsHandle) (Link, error) {\n\t// TODO: add support for shared l interfaces (like Mellanox NICs)\n\tattempts := []func(netns.NsHandle, string, string) (netlink.Link, error){\n\t\tsearchByPCIAddress,\n\t\tsearchByName,\n\t}\n\n\t// search for link with a matching name or PCI address in the provided namespaces\n\tfor _, ns := range namespaces {\n\t\tfor _, search := range attempts {\n\t\t\tfound, err := search(ns, name, pciAddress)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif found != nil {\n\t\t\t\treturn &link{\n\t\t\t\t\tlink: found,\n\t\t\t\t\tnetns: ns,\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.Errorf(\"failed to obtain netlink link matching criteria: name=%s or pciAddress=%s\", name, pciAddress)\n}", "func extractAddress(str string) string {\n\tvar addr string\n\n\tswitch {\n\tcase strings.Contains(str, `]`):\n\t\t// IPv6 address [2001:db8::1%lo0]:48467\n\t\taddr = strings.Split(str, `]`)[0]\n\t\taddr = strings.Split(addr, `%`)[0]\n\t\taddr = strings.TrimLeft(addr, `[`)\n\tdefault:\n\t\t// IPv4 address 192.0.2.1:48467\n\t\taddr = strings.Split(str, `:`)[0]\n\t}\n\treturn addr\n}", "func extractAddress(str string) string {\n\tvar addr string\n\n\tswitch {\n\tcase strings.Contains(str, `]`):\n\t\t// IPv6 address [2001:db8::1%lo0]:48467\n\t\taddr = strings.Split(str, `]`)[0]\n\t\taddr = strings.Split(addr, `%`)[0]\n\t\taddr = strings.TrimLeft(addr, `[`)\n\tdefault:\n\t\t// IPv4 address 192.0.2.1:48467\n\t\taddr = strings.Split(str, `:`)[0]\n\t}\n\treturn addr\n}", "func (h *HaproxyInstace) q(query string) (string, error) {\n\tc, err := net.Dial(h.Network, h.Address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer c.Close()\n\n\tc.Write([]byte(query + \"\\n\"))\n\n\tvar buf bytes.Buffer\n\tio.Copy(&buf, c)\n\n\treturn strings.TrimSpace(buf.String()), nil\n}", "func (client *SdnClient) GetEveIfMAC(eveIfName string) (mac string, err error) {\n\tnetModel, err := client.GetNetworkModel()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to get network model: %v\", err)\n\t\treturn\n\t}\n\tvar eveIfIndex int\n\teveIfIndex, err = client.getEveIfIndex(eveIfName)\n\tif err != nil {\n\t\treturn\n\t}\n\tif eveIfIndex < 0 || eveIfIndex >= len(netModel.Ports) {\n\t\terr = fmt.Errorf(\"EVE interface index is out-of-range: %d <%d-%d)\",\n\t\t\teveIfIndex, 0, len(netModel.Ports))\n\t\treturn\n\t}\n\treturn netModel.Ports[eveIfIndex].EVEConnect.MAC, nil\n}", "func (b *Blueprint) MacAddress(column string) *ColumnDefinition {\n\treturn b.addColumn(\"macAddress\", column, nil)\n}", "func search(client pb.TwitterClient, query string) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\treq := &pb.Search{Token: getToken(), Text: query}\n\tstream, err := client.Filter(ctx, req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\tres, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tfmt.Println(\"Search ended :O\")\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"%v : %s \\n\", res.User.ScreenName, res.Text)\n\t}\n}", "func (h *Hostman) Search(query string) Entries {\n\tvar matches Entries\n\n\tentries := h.Entries()\n\n\tfor _, entry := range entries {\n\t\tif strings.Contains(entry.Raw, query) {\n\t\t\tmatches = append(matches, entry)\n\t\t}\n\t}\n\n\treturn matches\n}", "func (vm *FstVM) Search(input string) []string {\n\ttape, snap, acc := vm.run(input)\n\tif !acc || len(snap) == 0 {\n\t\treturn 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 []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 outs\n}", "func (m *WindowsInformationProtectionDeviceRegistration) GetDeviceMacAddress()(*string) {\n val, err := m.GetBackingStore().Get(\"deviceMacAddress\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func Search(host string) (*Fqdn, error) {\n\thost = url.PathEscape(host)\n\tres, err := http.Get(fmt.Sprintf(\"https://registro.br/v2/ajax/avail/raw/%s\", host))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"Ooops, request error with status %d\", res.StatusCode)\n\t}\n\n\tvar fqdn *Fqdn\n\tjson.NewDecoder(res.Body).Decode(&fqdn)\n\n\tif len(fqdn.Reasons) > 0 {\n\t\treturn nil, &fqdnError{\n\t\t\tfqdn: fqdn.Fqdn,\n\t\t\terrorReasons: fqdn.Reasons,\n\t\t}\n\t}\n\n\treturn fqdn, nil\n}", "func dockStationMACs(ctx context.Context) ([]string, error) {\n\tmanager, err := shill.NewManager(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create shill manager proxy\")\n\t}\n\n\t_, props, err := manager.DevicesByTechnology(ctx, shill.TechnologyEthernet)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get ethernet devices\")\n\t}\n\n\tvar macs []string\n\n\tfor _, deviceProps := range props {\n\t\tif !deviceProps.Has(shillconst.DevicePropertyEthernetBusType) {\n\t\t\tcontinue\n\t\t}\n\t\tbusType, err := deviceProps.GetString(shillconst.DevicePropertyEthernetBusType)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get device bus type\")\n\t\t}\n\n\t\tiface, err := deviceProps.GetString(shillconst.DevicePropertyInterface)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get interface name\")\n\t\t}\n\n\t\tif busType != \"usb\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tifi, err := net.InterfaceByName(iface)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get interface by %q name\", iface)\n\t\t}\n\t\tif ifi.HardwareAddr == nil {\n\t\t\treturn nil, errors.New(\"interface MAC address is nil\")\n\t\t}\n\t\tmacs = append(macs, strings.ToLower(ifi.HardwareAddr.String()))\n\t}\n\n\tif len(macs) == 0 {\n\t\treturn nil, errors.New(\"not found USB Ethernet adapter connected to the DUT\")\n\t}\n\n\treturn macs, nil\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 (self *Device) selectAvailableInterfaceForAddr(fromAddr string) (string, error) {\n\tifi, err := util.GetAvailableInterfaceForAddr(fromAddr)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tifAddr, err := util.GetInterfaceAddress(ifi)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn ifAddr, err\n}", "func (s *Service) Search(c context.Context, mid, zoneid int64, mobiApp, device, platform, buvid, keyword, duration, order, filtered, lang, fromSource, recommend, parent string, plat int8, rid, highlight, build, pn, ps, isQuery int, old bool, now time.Time) (res *search.Result, err error) {\n\tconst (\n\t\t_newIPhonePGC = 6500\n\t\t_newAndroidPGC = 519010\n\t\t_newIPhoneSearch = 6500\n\t\t_newAndroidSearch = 5215000\n\t\t_newAndroidBSearch = 591200\n\t)\n\tvar (\n\t\tnewPGC, flow, isNewTwitter bool\n\t\tavids []int64\n\t\tavm map[int64]*api.Arc\n\t\towners []int64\n\t\tfollows map[int64]bool\n\t\troomIDs []int64\n\t\tlm map[int64]*live.RoomInfo\n\t\tseasonIDs []int64\n\t\tbangumis map[string]*bangumi.Card\n\t\t//tagSeasonIDs []int32\n\t\ttagBangumis map[int32]*seasongrpc.CardInfoProto\n\t\ttags []int64\n\t\ttagMyInfos []*tagmdl.Tag\n\t\tdynamicIDs []int64\n\t\tdynamicDetails map[int64]*bplus.Detail\n\t\taccInfos map[int64]*account.Info\n\t\tcooperation bool\n\t)\n\t// android 概念版 591205\n\tif (plat == model.PlatAndroid && build >= _newAndroidPGC && build != 591205) || (plat == model.PlatIPhone && build >= _newIPhonePGC && build != 7140) || (plat == model.PlatAndroidB && build >= _newAndroidBSearch) || (plat == model.PlatIPad && build >= search.SearchNewIPad) || (plat == model.PlatIpadHD && build >= search.SearchNewIPadHD) || model.IsIPhoneB(plat) {\n\t\tnewPGC = true\n\t}\n\t// 处理一个ios概念版是 7140,是否需要过滤\n\tif (plat == model.PlatAndroid && build >= _newAndroidSearch) || (plat == model.PlatIPhone && build >= _newIPhoneSearch && build != 7140) || (plat == model.PlatAndroidB && build >= _newAndroidBSearch) || model.IsIPhoneB(plat) {\n\t\tflow = true\n\t}\n\tvar (\n\t\tseasonNum int\n\t\tmovieNum int\n\t)\n\tif (plat == model.PlatIPad && build >= search.SearchNewIPad) || (plat == model.PlatIpadHD && build >= search.SearchNewIPadHD) {\n\t\tseasonNum = s.iPadSearchBangumi\n\t\tmovieNum = s.iPadSearchFt\n\t} else {\n\t\tseasonNum = s.seasonNum\n\t\tmovieNum = s.movieNum\n\t}\n\tall, code, err := s.srchDao.Search(c, mid, zoneid, mobiApp, device, platform, buvid, keyword, duration, order, filtered, fromSource, recommend, parent, plat, seasonNum, movieNum, s.upUserNum, s.uvLimit, s.userNum, s.userVideoLimit, s.biliUserNum, s.biliUserVideoLimit, rid, highlight, build, pn, ps, isQuery, old, now, newPGC, flow)\n\tif err != nil {\n\t\tlog.Error(\"%+v\", err)\n\t\treturn\n\t}\n\tif (model.IsAndroid(plat) && build > s.c.SearchBuildLimit.NewTwitterAndroid) || (model.IsIPhone(plat) && build > s.c.SearchBuildLimit.NewTwitterIOS) {\n\t\tisNewTwitter = true\n\t}\n\tif code == model.ForbidCode || code == model.NoResultCode {\n\t\tres = _emptyResult\n\t\terr = nil\n\t\treturn\n\t}\n\tres = &search.Result{}\n\tres.Trackid = all.Trackid\n\tres.Page = all.Page\n\tres.Array = all.FlowPlaceholder\n\tres.Attribute = all.Attribute\n\tres.NavInfo = s.convertNav(all, plat, build, lang, old, newPGC)\n\tif len(all.FlowResult) != 0 {\n\t\tvar item []*search.Item\n\t\tfor _, v := range all.FlowResult {\n\t\t\tswitch v.Type {\n\t\t\tcase search.TypeUser, search.TypeBiliUser:\n\t\t\t\towners = append(owners, v.User.Mid)\n\t\t\t\tfor _, vr := range v.User.Res {\n\t\t\t\t\tavids = append(avids, vr.Aid)\n\t\t\t\t}\n\t\t\t\troomIDs = append(roomIDs, v.User.RoomID)\n\t\t\tcase search.TypeVideo:\n\t\t\t\tavids = append(avids, v.Video.ID)\n\t\t\tcase search.TypeLive:\n\t\t\t\troomIDs = append(roomIDs, v.Live.RoomID)\n\t\t\tcase search.TypeMediaBangumi, search.TypeMediaFt:\n\t\t\t\tseasonIDs = append(seasonIDs, v.Media.SeasonID)\n\t\t\tcase search.TypeStar:\n\t\t\t\tif v.Star.MID != 0 {\n\t\t\t\t\towners = append(owners, v.Star.MID)\n\t\t\t\t}\n\t\t\t\tif v.Star.TagID != 0 {\n\t\t\t\t\ttags = append(tags, v.Star.TagID)\n\t\t\t\t}\n\t\t\tcase search.TypeArticle:\n\t\t\t\towners = append(owners, v.Article.Mid)\n\t\t\tcase search.TypeChannel:\n\t\t\t\ttags = append(tags, v.Channel.TagID)\n\t\t\t\tif len(v.Channel.Values) > 0 {\n\t\t\t\t\tfor _, vc := range v.Channel.Values {\n\t\t\t\t\t\tswitch vc.Type {\n\t\t\t\t\t\tcase search.TypeVideo:\n\t\t\t\t\t\t\tif vc.Video != nil {\n\t\t\t\t\t\t\t\tavids = append(avids, vc.Video.ID)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//case search.TypeLive:\n\t\t\t\t\t\t\t//\tif vc.Live != nil {\n\t\t\t\t\t\t\t//\t\troomIDs = append(roomIDs, vc.Live.RoomID)\n\t\t\t\t\t\t\t//\t}\n\t\t\t\t\t\t\t//case search.TypeMediaBangumi, search.TypeMediaFt:\n\t\t\t\t\t\t\t//\tif vc.Media != nil {\n\t\t\t\t\t\t\t//\t\ttagSeasonIDs = append(tagSeasonIDs, int32(vc.Media.SeasonID))\n\t\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\tcase search.TypeTwitter:\n\t\t\t\tdynamicIDs = append(dynamicIDs, v.Twitter.ID)\n\t\t\t}\n\t\t}\n\t\tg, ctx := errgroup.WithContext(c)\n\t\tif len(owners) != 0 {\n\t\t\tif mid > 0 {\n\t\t\t\tg.Go(func() error {\n\t\t\t\t\tfollows = s.accDao.Relations3(ctx, owners, mid)\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif accInfos, err = s.accDao.Infos3(ctx, owners); err != nil {\n\t\t\t\t\tlog.Error(\"%v\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\tif len(avids) != 0 {\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif avm, err = s.arcDao.Archives2(ctx, avids); err != nil {\n\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\tif len(roomIDs) != 0 {\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif lm, err = s.liveDao.LiveByRIDs(ctx, roomIDs); err != nil {\n\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\tif len(seasonIDs) != 0 {\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif bangumis, err = s.bangumiDao.Card(ctx, mid, seasonIDs); err != nil {\n\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\t//if len(tagSeasonIDs) != 0 {\n\t\t//\tg.Go(func() (err error) {\n\t\t//\t\tif tagBangumis, err = s.bangumiDao.Cards(ctx, tagSeasonIDs); err != nil {\n\t\t//\t\t\tlog.Error(\"%+v\", err)\n\t\t//\t\t\terr = nil\n\t\t//\t\t}\n\t\t//\t\treturn\n\t\t//\t})\n\t\t//}\n\t\tif len(tags) != 0 {\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif tagMyInfos, err = s.tagDao.TagInfos(ctx, tags, mid); err != nil {\n\t\t\t\t\tlog.Error(\"%v \\n\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\tif len(dynamicIDs) != 0 {\n\t\t\tg.Go(func() (err error) {\n\t\t\t\tif dynamicDetails, err = s.bplusDao.DynamicDetails(ctx, dynamicIDs, \"search\"); err != nil {\n\t\t\t\t\tlog.Error(\"%v \\n\", err)\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t})\n\t\t}\n\t\tif err = g.Wait(); err != nil {\n\t\t\tlog.Error(\"%+v\", err)\n\t\t\treturn\n\t\t}\n\t\tif all.SuggestKeyword != \"\" && pn == 1 {\n\t\t\ti := &search.Item{Title: all.SuggestKeyword, Goto: model.GotoSuggestKeyWord, SugKeyWordType: 1}\n\t\t\titem = append(item, i)\n\t\t} else if all.CrrQuery != \"\" && pn == 1 {\n\t\t\tif (model.IsAndroid(plat) && build > s.c.SearchBuildLimit.QueryCorAndroid) || (model.IsIPhone(plat) && build > s.c.SearchBuildLimit.QueryCorIOS) {\n\t\t\t\ti := &search.Item{Title: fmt.Sprintf(\"已匹配%q的搜索结果\", all.CrrQuery), Goto: model.GotoSuggestKeyWord, SugKeyWordType: 2}\n\t\t\t\titem = append(item, i)\n\t\t\t}\n\t\t}\n\t\tfor _, v := range all.FlowResult {\n\t\t\ti := &search.Item{TrackID: v.TrackID, LinkType: v.LinkType, Position: v.Position}\n\t\t\tswitch v.Type {\n\t\t\tcase search.TypeVideo:\n\t\t\t\tif (model.IsAndroid(plat) && build > s.c.SearchBuildLimit.CooperationAndroid) || (model.IsIPhone(plat) && build > s.c.SearchBuildLimit.CooperationIOS) {\n\t\t\t\t\tcooperation = true\n\t\t\t\t}\n\t\t\t\ti.FromVideo(v.Video, avm[v.Video.ID], cooperation)\n\t\t\tcase search.TypeLive:\n\t\t\t\ti.FromLive(v.Live, lm[v.Live.RoomID])\n\t\t\tcase search.TypeMediaBangumi:\n\t\t\t\ti.FromMedia(v.Media, \"\", model.GotoBangumi, bangumis)\n\t\t\tcase search.TypeMediaFt:\n\t\t\t\ti.FromMedia(v.Media, \"\", model.GotoMovie, bangumis)\n\t\t\tcase search.TypeArticle:\n\t\t\t\ti.FromArticle(v.Article, accInfos[v.Article.Mid])\n\t\t\tcase search.TypeSpecial:\n\t\t\t\ti.FromOperate(v.Operate, model.GotoSpecial)\n\t\t\tcase search.TypeBanner:\n\t\t\t\ti.FromOperate(v.Operate, model.GotoBanner)\n\t\t\tcase search.TypeUser:\n\t\t\t\tif follows[v.User.Mid] {\n\t\t\t\t\ti.Attentions = 1\n\t\t\t\t}\n\t\t\t\ti.FromUser(v.User, avm, lm[v.User.RoomID])\n\t\t\tcase search.TypeBiliUser:\n\t\t\t\tif follows[v.User.Mid] {\n\t\t\t\t\ti.Attentions = 1\n\t\t\t\t}\n\t\t\t\ti.FromUpUser(v.User, avm, lm[v.User.RoomID])\n\t\t\tcase search.TypeSpecialS:\n\t\t\t\ti.FromOperate(v.Operate, model.GotoSpecialS)\n\t\t\tcase search.TypeGame:\n\t\t\t\ti.FromGame(v.Game)\n\t\t\tcase search.TypeQuery:\n\t\t\t\ti.Title = v.TypeName\n\t\t\t\ti.FromQuery(v.Query)\n\t\t\tcase search.TypeComic:\n\t\t\t\ti.FromComic(v.Comic)\n\t\t\tcase search.TypeConverge:\n\t\t\t\tvar (\n\t\t\t\t\taids, rids, artids []int64\n\t\t\t\t\tam map[int64]*api.Arc\n\t\t\t\t\trm map[int64]*live.Room\n\t\t\t\t\tartm map[int64]*article.Meta\n\t\t\t\t)\n\t\t\t\tfor _, c := range v.Operate.ContentList {\n\t\t\t\t\tswitch c.Type {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\taids = append(aids, c.ID)\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\trids = append(rids, c.ID)\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tartids = append(artids, c.ID)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tg, ctx := errgroup.WithContext(c)\n\t\t\t\tif len(aids) != 0 {\n\t\t\t\t\tg.Go(func() (err error) {\n\t\t\t\t\t\tif am, err = s.arcDao.Archives2(ctx, aids); err != nil {\n\t\t\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\t\t\terr = nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif len(rids) != 0 {\n\t\t\t\t\tg.Go(func() (err error) {\n\t\t\t\t\t\tif rm, err = s.liveDao.AppMRoom(ctx, rids); err != nil {\n\t\t\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\t\t\terr = nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif len(artids) != 0 {\n\t\t\t\t\tg.Go(func() (err error) {\n\t\t\t\t\t\tif artm, err = s.artDao.Articles(ctx, artids); err != nil {\n\t\t\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\t\t\terr = nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif err = g.Wait(); err != nil {\n\t\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ti.FromConverge(v.Operate, am, rm, artm)\n\t\t\tcase search.TypeTwitter:\n\t\t\t\ti.FromTwitter(v.Twitter, dynamicDetails, s.c.SearchDynamicSwitch.IsUP, s.c.SearchDynamicSwitch.IsCount, isNewTwitter)\n\t\t\tcase search.TypeStar:\n\t\t\t\tif v.Star.TagID != 0 {\n\t\t\t\t\ti.URIType = search.StarChannel\n\t\t\t\t\tfor _, myInfo := range tagMyInfos {\n\t\t\t\t\t\tif myInfo != nil && myInfo.TagID == v.Star.TagID {\n\t\t\t\t\t\t\ti.IsAttention = myInfo.IsAtten\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if v.Star.MID != 0 {\n\t\t\t\t\ti.URIType = search.StarSpace\n\t\t\t\t\tif follows[v.Star.MID] {\n\t\t\t\t\t\ti.IsAttention = 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti.FromStar(v.Star)\n\t\t\tcase search.TypeTicket:\n\t\t\t\ti.FromTicket(v.Ticket)\n\t\t\tcase search.TypeProduct:\n\t\t\t\ti.FromProduct(v.Product)\n\t\t\tcase search.TypeSpecialerGuide:\n\t\t\t\ti.FromSpecialerGuide(v.SpecialerGuide)\n\t\t\tcase search.TypeChannel:\n\t\t\t\ti.FromChannel(v.Channel, avm, tagBangumis, lm, tagMyInfos)\n\t\t\t}\n\t\t\tif i.Goto != \"\" {\n\t\t\t\titem = append(item, i)\n\t\t\t}\n\t\t}\n\t\tres.Item = item\n\t\tif plat == model.PlatAndroid && build < search.SearchEggInfoAndroid {\n\t\t\treturn\n\t\t}\n\t\tif all.EggInfo != nil {\n\t\t\tres.EasterEgg = &search.EasterEgg{ID: all.EggInfo.Source, ShowCount: all.EggInfo.ShowCount}\n\t\t}\n\t\treturn\n\t}\n\tvar items []*search.Item\n\tif all.SuggestKeyword != \"\" && pn == 1 {\n\t\tres.Items.SuggestKeyWord = &search.Item{Title: all.SuggestKeyword, Goto: model.GotoSuggestKeyWord}\n\t}\n\t// archive\n\tfor _, v := range all.Result.Video {\n\t\tavids = append(avids, v.ID)\n\t}\n\tif duration == \"0\" && order == \"totalrank\" && rid == 0 {\n\t\tfor _, v := range all.Result.Movie {\n\t\t\tif v.Type == \"movie\" {\n\t\t\t\tavids = append(avids, v.Aid)\n\t\t\t}\n\t\t}\n\t}\n\tif pn == 1 {\n\t\tfor _, v := range all.Result.User {\n\t\t\tfor _, vr := range v.Res {\n\t\t\t\tavids = append(avids, vr.Aid)\n\t\t\t}\n\t\t}\n\t\tif old {\n\t\t\tfor _, v := range all.Result.UpUser {\n\t\t\t\tfor _, vr := range v.Res {\n\t\t\t\t\tavids = append(avids, vr.Aid)\n\t\t\t\t}\n\t\t\t\towners = append(owners, v.Mid)\n\t\t\t\troomIDs = append(roomIDs, v.RoomID)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, v := range all.Result.BiliUser {\n\t\t\t\tfor _, vr := range v.Res {\n\t\t\t\t\tavids = append(avids, vr.Aid)\n\t\t\t\t}\n\t\t\t\towners = append(owners, v.Mid)\n\t\t\t\troomIDs = append(roomIDs, v.RoomID)\n\t\t\t}\n\t\t}\n\t}\n\tif model.IsOverseas(plat) {\n\t\tfor _, v := range all.Result.LiveRoom {\n\t\t\troomIDs = append(roomIDs, v.RoomID)\n\t\t}\n\t\tfor _, v := range all.Result.LiveUser {\n\t\t\troomIDs = append(roomIDs, v.RoomID)\n\t\t}\n\t}\n\tg, ctx := errgroup.WithContext(c)\n\tif len(owners) != 0 {\n\t\tif mid > 0 {\n\t\t\tg.Go(func() error {\n\t\t\t\tfollows = s.accDao.Relations3(ctx, owners, mid)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\tif len(avids) != 0 {\n\t\tg.Go(func() (err error) {\n\t\t\tif avm, err = s.arcDao.Archives2(ctx, avids); err != nil {\n\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n\tif len(roomIDs) != 0 {\n\t\tg.Go(func() (err error) {\n\t\t\tif lm, err = s.liveDao.LiveByRIDs(ctx, roomIDs); err != nil {\n\t\t\t\tlog.Error(\"%+v\", err)\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t}\n\tif err = g.Wait(); err != nil {\n\t\tlog.Error(\"%+v\", err)\n\t\treturn\n\t}\n\tif duration == \"0\" && order == \"totalrank\" && rid == 0 {\n\t\tvar promptBangumi, promptFt string\n\t\t// season\n\t\tbangumi := all.Result.Bangumi\n\t\titems = make([]*search.Item, 0, len(bangumi))\n\t\tfor _, v := range bangumi {\n\t\t\tsi := &search.Item{}\n\t\t\tif (model.IsAndroid(plat) && build <= _oldAndroid) || (model.IsIPhone(plat) && build <= _oldIOS) {\n\t\t\t\tsi.FromSeason(v, model.GotoBangumi)\n\t\t\t} else {\n\t\t\t\tsi.FromSeason(v, model.GotoBangumiWeb)\n\t\t\t}\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.Season = items\n\t\t// movie\n\t\tmovie := all.Result.Movie\n\t\titems = make([]*search.Item, 0, len(movie))\n\t\tfor _, v := range movie {\n\t\t\tsi := &search.Item{}\n\t\t\tsi.FromMovie(v, avm)\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.Movie = items\n\t\t// season2\n\t\tmb := all.Result.MediaBangumi\n\t\titems = make([]*search.Item, 0, len(mb))\n\t\tfor k, v := range mb {\n\t\t\tsi := &search.Item{}\n\t\t\tif ((plat == model.PlatIPad && build >= search.SearchNewIPad) || (plat == model.PlatIpadHD && build >= search.SearchNewIPadHD)) && (k == len(mb)-1) && all.PageInfo.MediaBangumi.NumResults > s.iPadSearchBangumi {\n\t\t\t\tpromptBangumi = fmt.Sprintf(\"查看全部番剧 ( %d ) >\", all.PageInfo.MediaBangumi.NumResults)\n\t\t\t}\n\t\t\tsi.FromMedia(v, promptBangumi, model.GotoBangumi, nil)\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.Season2 = items\n\t\t// movie2\n\t\tmf := all.Result.MediaFt\n\t\titems = make([]*search.Item, 0, len(mf))\n\t\tfor k, v := range mf {\n\t\t\tsi := &search.Item{}\n\t\t\tif ((plat == model.PlatIPad && build >= search.SearchNewIPad) || (plat == model.PlatIpadHD && build >= search.SearchNewIPadHD)) && (k == len(mf)-1) && all.PageInfo.MediaFt.NumResults > s.iPadSearchFt {\n\t\t\t\tpromptFt = fmt.Sprintf(\"查看全部影视 ( %d ) >\", all.PageInfo.MediaFt.NumResults)\n\t\t\t}\n\t\t\tsi.FromMedia(v, promptFt, model.GotoMovie, nil)\n\t\t\tsi.Goto = model.GotoAv\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.Movie2 = items\n\t}\n\tif pn == 1 {\n\t\t// upper + user\n\t\tvar tmp []*search.User\n\t\tif old {\n\t\t\ttmp = all.Result.UpUser\n\t\t} else {\n\t\t\ttmp = all.Result.BiliUser\n\t\t}\n\t\titems = make([]*search.Item, 0, len(tmp)+len(all.Result.User))\n\t\tfor _, v := range all.Result.User {\n\t\t\tsi := &search.Item{}\n\t\t\tsi.FromUser(v, avm, lm[v.RoomID])\n\t\t\tif follows[v.Mid] {\n\t\t\t\tsi.Attentions = 1\n\t\t\t}\n\t\t\titems = append(items, si)\n\t\t}\n\t\tif len(items) == 0 {\n\t\t\tfor _, v := range tmp {\n\t\t\t\tsi := &search.Item{}\n\t\t\t\tsi.FromUpUser(v, avm, lm[v.RoomID])\n\t\t\t\tif follows[v.Mid] {\n\t\t\t\t\tsi.Attentions = 1\n\t\t\t\t}\n\t\t\t\tif old {\n\t\t\t\t\tsi.IsUp = true\n\t\t\t\t}\n\t\t\t\titems = append(items, si)\n\t\t\t}\n\t\t}\n\t\tres.Items.Upper = items\n\t}\n\titems = make([]*search.Item, 0, len(all.Result.Video))\n\tfor _, v := range all.Result.Video {\n\t\tsi := &search.Item{}\n\t\tsi.FromVideo(v, avm[v.ID], cooperation)\n\t\titems = append(items, si)\n\t}\n\tres.Items.Archive = items\n\t// live room\n\tif model.IsOverseas(plat) {\n\t\titems = make([]*search.Item, 0, len(all.Result.LiveRoom))\n\t\tfor _, v := range all.Result.LiveRoom {\n\t\t\tsi := &search.Item{}\n\t\t\tsi.FromLive(v, lm[v.RoomID])\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.LiveRoom = items\n\t\t// live user\n\t\titems = make([]*search.Item, 0, len(all.Result.LiveUser))\n\t\tfor _, v := range all.Result.LiveUser {\n\t\t\tsi := &search.Item{}\n\t\t\tsi.FromLive(v, lm[v.RoomID])\n\t\t\titems = append(items, si)\n\t\t}\n\t\tres.Items.LiveUser = items\n\t}\n\treturn\n}", "func parseAddrMsg(msg *netlink.Message) (*AddrEntry, bool, error) {\n\tvar ifamsg iproute2.IfAddrMsg\n\tif err := ifamsg.UnmarshalBinary(msg.Data); err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tvar e AddrEntry\n\te.init()\n\te.Family = int(ifamsg.Family)\n\te.PrefixLen = int(ifamsg.Prefixlen)\n\te.Flags = AddrFlag(ifamsg.Flags)\n\te.Scope = AddrScope(ifamsg.Scope)\n\te.Ifindex = int(ifamsg.Index)\n\n\tad, err := netlink.NewAttributeDecoder(msg.Data[iproute2.SizeofIfAddrMsg:])\n\tif err != nil {\n\t\treturn &e, false, err\n\t}\n\n\tfor ad.Next() {\n\t\tswitch ad.Type() {\n\t\tcase unix.IFA_ADDRESS:\n\t\t\te.InterfaceAddr = net.IP(ad.Bytes())\n\t\tcase unix.IFA_LOCAL:\n\t\t\te.LocalAddr = net.IP(ad.Bytes())\n\t\tcase unix.IFA_LABEL:\n\t\t\te.Label = ad.String()\n\t\tcase unix.IFA_BROADCAST:\n\t\t\te.BroadcastAddr = net.IP(ad.Bytes())\n\t\tcase unix.IFA_ANYCAST:\n\t\t\te.AnycastAddr = net.IP(ad.Bytes())\n\t\tcase unix.IFA_CACHEINFO:\n\t\t\te.AddrInfo = new(iproute2.IfaCacheinfo)\n\t\t\t_ = e.AddrInfo.UnmarshalBinary(ad.Bytes())\n\t\tcase unix.IFA_MULTICAST:\n\t\t\te.MulticastAddr = net.IP(ad.Bytes())\n\t\tcase unix.IFA_FLAGS:\n\t\t\te.AddrFlags = AddrFlag(ad.Uint32())\n\t\t}\n\t}\n\terr = ad.Err()\n\treturn &e, err == nil, err\n}", "func findMDA(host string) (string, error) {\n\tresults, err := net.LookupMX(host)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(results) == 0 {\n\t\treturn \"\", errors.New(\"No MX records found\")\n\t}\n\n\t// todo: support for multiple MX records\n\th := results[0].Host\n\treturn h[:len(h)-1] + \":25\", nil\n}", "func (c *Eth) Show(name string) (Entry, error) {\n c.con.LogQuery(\"(show) ethernet interface %q\", name)\n return c.details(c.con.Show, name)\n}", "func ARP(node Node, ip net.IP) string {\n\tnetInterface := getNetworkInterfaceWithSameNetwork(node, ip)\n\tif netInterface != nil {\n\t\treturn ip.String()\n\t}\n\trouterIP := getRouterIP(node, ip)\n\tif routerIP == nil {\n\t\treturn \"\"\n\t}\n\tnetInterface = getNetworkInterfaceWithSameNetwork(node, routerIP)\n\tif netInterface != nil {\n\t\treturn routerIP.String()\n\t}\n\treturn \"\"\n}", "func UsernameAndMintHostFromAddress(\n\tctx context.Context,\n\taddress string,\n) (string, string, error) {\n\tm := AddressRegexp.FindStringSubmatch(address)\n\tif len(m) == 0 {\n\t\treturn \"\", \"\", errors.Trace(errors.Newf(\n\t\t\t\"Invalid address: %s\", address))\n\t}\n\n\treturn m[1], m[3], nil\n}", "func FindAtom(lpString string) ATOM {\n\tlpStringStr := unicode16FromString(lpString)\n\tret1 := syscall3(findAtom, 1,\n\t\tuintptr(unsafe.Pointer(&lpStringStr[0])),\n\t\t0,\n\t\t0)\n\treturn ATOM(ret1)\n}", "func findAManagementIP() string {\n\tvar addrs []net.Addr\n\teth0, err := net.InterfaceByName(\"eth0\")\n\tif err == nil {\n\t\taddrs, err = eth0.Addrs()\n\t}\n\tif err != nil {\n\t\tglog.Errorf(\"Could not read eth0 info; err=%v\", err)\n\t\treturn \"\"\n\t}\n\n\tfor _, addr := range addrs {\n\t\tip, _, err := net.ParseCIDR(addr.String())\n\t\tif err == nil && ip.To4() != nil {\n\t\t\treturn ip.String()\n\t\t}\n\t}\n\n\tglog.Errorf(\"Could not find a management address!!\")\n\treturn \"\"\n}", "func TestMacAddress(t *testing.T) {\n\tb := getMACAddr()\n\tzeroBytes := make([]byte, len(b))\n\tassert.NotEqual(t, b, zeroBytes, \"Random bytes all zero\")\n}", "func likelyHomeRouterIPWindows() (ret netaddr.IP, ok bool) {\n\tcmd := exec.Command(\"route\", \"print\", \"-4\")\n\tcmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn\n\t}\n\tdefer cmd.Wait()\n\n\tvar f []mem.RO\n\tlineread.Reader(stdout, func(lineb []byte) error {\n\t\tline := mem.B(lineb)\n\t\tif !mem.Contains(line, mem.S(\"0.0.0.0\")) {\n\t\t\treturn nil\n\t\t}\n\t\tf = mem.AppendFields(f[:0], line)\n\t\tif len(f) < 3 || !f[0].EqualString(\"0.0.0.0\") || !f[1].EqualString(\"0.0.0.0\") {\n\t\t\treturn nil\n\t\t}\n\t\tipm := f[2]\n\t\tip, err := netaddr.ParseIP(string(mem.Append(nil, ipm)))\n\t\tif err == nil && isPrivateIP(ip) {\n\t\t\tret = ip\n\t\t}\n\t\treturn nil\n\t})\n\treturn ret, !ret.IsZero()\n}", "func findBridge(device string) (*Bridge, error) {\n\n\tcmd := exec.Command(\"ifconfig\", device)\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbridge := parseIfconfig(string(out))\n\tbridge.Device = device\n\n\treturn bridge, nil\n}", "func MACMustParse(s string) net.HardwareAddr {\n\thwAddr, err := net.ParseMAC(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn hwAddr\n}", "func conjureMac(macPrefix string, ip net.IP) string {\n\tif ip4 := ip.To4(); ip4 != nil {\n\t\ta, b, c, d := ip4[0], ip4[1], ip4[2], ip4[3]\n\t\treturn fmt.Sprintf(\"%v-%02x-%02x-%02x-%02x\", macPrefix, a, b, c, d)\n\t} else if ip6 := ip.To16(); ip6 != nil {\n\t\ta, b, c, d := ip6[15], ip6[14], ip6[13], ip6[12]\n\t\treturn fmt.Sprintf(\"%v-%02x-%02x-%02x-%02x\", macPrefix, a, b, c, d)\n\t}\n\treturn \"02-11-22-33-44-55\"\n}", "func icao2reg(icao_addr uint32) (string, bool) {\n\t// Initialize local variables\n\tbase34alphabet := string(\"ABCDEFGHJKLMNPQRSTUVWXYZ0123456789\")\n\tnationalOffset := uint32(0xA00001) // default is US\n\ttail := \"\"\n\tnation := \"\"\n\n\t// Determine nationality\n\tif (icao_addr >= 0xA00001) && (icao_addr <= 0xAFFFFF) {\n\t\tnation = \"US\"\n\t} else if (icao_addr >= 0xC00001) && (icao_addr <= 0xC3FFFF) {\n\t\tnation = \"CA\"\n\t} else if (icao_addr >= 0x7C0000) && (icao_addr <= 0x7FFFFF) {\n\t\tnation = \"AU\"\n\t} else {\n\t\t//TODO: future national decoding.\n\t\treturn \"OTHER\", false\n\t}\n\n\tif nation == \"CA\" { // Canada decoding\n\t\t// First, discard addresses that are not assigned to aircraft on the civil registry\n\t\tif icao_addr > 0xC0CDF8 {\n\t\t\t//fmt.Printf(\"%X is a Canada aircraft, but not a CF-, CG-, or CI- registration.\\n\", icao_addr)\n\t\t\treturn \"CA-MIL\", false\n\t\t}\n\n\t\tnationalOffset := uint32(0xC00001)\n\t\tserial := int32(icao_addr - nationalOffset)\n\n\t\t// Fifth letter\n\t\te := serial % 26\n\n\t\t// Fourth letter\n\t\td := (serial / 26) % 26\n\n\t\t// Third letter\n\t\tc := (serial / 676) % 26 // 676 == 26*26\n\n\t\t// Second letter\n\t\tb := (serial / 17576) % 26 // 17576 == 26*26*26\n\n\t\tb_str := \"FGI\"\n\n\t\t//fmt.Printf(\"B = %d, C = %d, D = %d, E = %d\\n\",b,c,d,e)\n\t\ttail = fmt.Sprintf(\"C-%c%c%c%c\", b_str[b], c+65, d+65, e+65)\n\t}\n\n\tif nation == \"AU\" { // Australia decoding\n\n\t\tnationalOffset := uint32(0x7C0000)\n\t\toffset := (icao_addr - nationalOffset)\n\t\ti1 := offset / 1296\n\t\toffset2 := offset % 1296\n\t\ti2 := offset2 / 36\n\t\toffset3 := offset2 % 36\n\t\ti3 := offset3\n\n\t\tvar a_char, b_char, c_char string\n\n\t\ta_char = fmt.Sprintf(\"%c\", i1+65)\n\t\tb_char = fmt.Sprintf(\"%c\", i2+65)\n\t\tc_char = fmt.Sprintf(\"%c\", i3+65)\n\n\t\tif i1 < 0 || i1 > 25 || i2 < 0 || i2 > 25 || i3 < 0 || i3 > 25 {\n\t\t\treturn \"OTHER\", false\n\t\t}\n\n\t\ttail = \"VH-\" + a_char + b_char + c_char\n\t}\n\n\tif nation == \"US\" { // FAA decoding\n\t\t// First, discard addresses that are not assigned to aircraft on the civil registry\n\t\tif icao_addr > 0xADF7C7 {\n\t\t\t//fmt.Printf(\"%X is a US aircraft, but not on the civil registry.\\n\", icao_addr)\n\t\t\treturn \"US-MIL\", false\n\t\t}\n\n\t\tserial := int32(icao_addr - nationalOffset)\n\t\t// First digit\n\t\ta := (serial / 101711) + 1\n\n\t\t// Second digit\n\t\ta_remainder := serial % 101711\n\t\tb := ((a_remainder + 9510) / 10111) - 1\n\n\t\t// Third digit\n\t\tb_remainder := (a_remainder + 9510) % 10111\n\t\tc := ((b_remainder + 350) / 951) - 1\n\n\t\t// This next bit is more convoluted. First, figure out if we're using the \"short\" method of\n\t\t// decoding the last two digits (two letters, one letter and one blank, or two blanks).\n\t\t// This will be the case if digit \"B\" or \"C\" are calculated as negative, or if c_remainder\n\t\t// is less than 601.\n\n\t\tc_remainder := (b_remainder + 350) % 951\n\t\tvar d, e int32\n\n\t\tif (b >= 0) && (c >= 0) && (c_remainder > 600) { // alphanumeric decoding method\n\t\t\td = 24 + (c_remainder-601)/35\n\t\t\te = (c_remainder - 601) % 35\n\n\t\t} else { // two-letter decoding method\n\t\t\tif (b < 0) || (c < 0) {\n\t\t\t\tc_remainder -= 350 // otherwise \" \" == 350, \"A \" == 351, \"AA\" == 352, etc.\n\t\t\t}\n\n\t\t\td = (c_remainder - 1) / 25\n\t\t\te = (c_remainder - 1) % 25\n\n\t\t\tif e < 0 {\n\t\t\t\td -= 1\n\t\t\t\te += 25\n\t\t\t}\n\t\t}\n\n\t\ta_char := fmt.Sprintf(\"%d\", a)\n\t\tvar b_char, c_char, d_char, e_char string\n\n\t\tif b >= 0 {\n\t\t\tb_char = fmt.Sprintf(\"%d\", b)\n\t\t}\n\n\t\tif b >= 0 && c >= 0 {\n\t\t\tc_char = fmt.Sprintf(\"%d\", c)\n\t\t}\n\n\t\tif d > -1 {\n\t\t\td_char = string(base34alphabet[d])\n\t\t\tif e > 0 {\n\t\t\t\te_char = string(base34alphabet[e-1])\n\t\t\t}\n\t\t}\n\n\t\ttail = \"N\" + a_char + b_char + c_char + d_char + e_char\n\n\t}\n\n\treturn tail, true\n}", "func ParseMAC(s string) (m MAC, err error) {\n\tif len(s) == 12 {\n\t\ts = fmt.Sprintf(\"%s.%s.%s\", s[0:4], s[4:8], s[8:12])\n\t}\n\thw, err := net.ParseMAC(s)\n\tif len(hw) == 8 {\n\t\treturn nil, &net.AddrError{Err: \"EUI-64 not suported\", Addr: s}\n\t}\n\treturn MAC(hw), err\n}", "func (c *Client) Hmac(msg string) string {\n\tmac := hmac.New(sha512.New, []byte(c.apiKey))\n\tmac.Write([]byte(msg))\n\tout := mac.Sum(nil)\n\treturn hex.EncodeToString(out)\n}", "func createBitcoinAddress(secret string) map[string]string {\n\tcmd := exec.Command(\"bu\", \"-a\", secret)\n\t//cmd.Stdin = strings.NewReader(\"some input\")\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tm := make(map[string]string)\n\tdata := strings.Split(out.String(), \"\\n\")\n\tm[\"wif-compressed\"] = strings.TrimSpace(strings.Split(data[2], \":\")[1])\n\tm[\"wif-uncompressed\"] = strings.TrimSpace(strings.Split(data[3], \":\")[1])\n\tm[\"hash160-compressed\"] = strings.TrimSpace(strings.Split(data[12], \":\")[1])\n\tm[\"hash160-uncompressed\"] = strings.TrimSpace(strings.Split(data[13], \":\")[1])\n\tm[\"bitcoinaddress-compressed\"] = strings.TrimSpace(strings.Split(data[14], \":\")[1])\n\tm[\"bitcoinaddress-uncompressed\"] = strings.TrimSpace(strings.Split(data[15], \":\")[1])\n\treturn m\n}", "func Search(param string) {\n\tfmt.Printf(\"Searching: %v...\\n\", param)\n\tpayload := domain.HttpRequestParam{\n\t\tMethod: \"GET\",\n\t\tURL: domain.BaseRoute + fmt.Sprintf(\"/REST/rxcui.json?name=%s&search=1\", url.QueryEscape(param)),\n\t\tHeaders: map[string]string{\n\t\t\t\"Authorization\": \"Bearer \",\n\t\t},\n\t}\n\n\tresp, err := MakeHttpRequest(payload)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\\n\", err.Error())\n\t}\n\tdata := make(map[string]interface{})\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\\n\", err.Error())\n\t}\n\n\t//pretty print data\n\tm, err := json.MarshalIndent(data, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\\n\", err.Error())\n\t}\n\tfmt.Printf(\"%v\\n\", string(m))\n}", "func searchAll(searchItem string) {\n\tstrippedItem := common.ConvertSpacesToNbsp(searchItem)\n\tfmt.Println(\"my strippedItem, \", strippedItem)\n\n}", "func lookupProbe() (string, error) {\n\tserverAddr, err := net.ResolveUDPAddr(\"udp4\", \"239.1.9.14:8890\")\n\tcheckErr(err, \"Error retrieving multicast address\")\n\n\tserverConn, err := net.ListenMulticastUDP(\"udp\", nil, serverAddr)\n\tcheckErr(err, \"Error listening for probe\")\n\n\tserverConn.SetReadBuffer(4)\n\n\tfmt.Println(\"Looking for probe...\")\n\n\tfor {\n\t\tbuf := make([]byte, 4)\n\t\t_, addr, err := serverConn.ReadFromUDP(buf)\n\t\tcheckErr(err, \"Error getting probe\")\n\n\t\tif string(buf) == \"BBA\\001\" {\n\t\t\treturn addr.String(), nil\n\t\t}\n\t}\n}" ]
[ "0.66006845", "0.6512171", "0.6030407", "0.572997", "0.5663973", "0.5466286", "0.54406816", "0.5429834", "0.5425368", "0.5382587", "0.53788114", "0.5336779", "0.5320087", "0.53059417", "0.5297832", "0.52759004", "0.5225848", "0.5139628", "0.51170194", "0.50876766", "0.50876766", "0.50808376", "0.50650436", "0.50579315", "0.50290745", "0.5028352", "0.501654", "0.5010887", "0.50076157", "0.4985361", "0.49403894", "0.49386528", "0.49229342", "0.49083656", "0.48699582", "0.48382625", "0.48280916", "0.4822347", "0.48148522", "0.48140377", "0.48140377", "0.4789375", "0.47620443", "0.4757809", "0.47528926", "0.47260624", "0.47235292", "0.4721349", "0.47083622", "0.4707961", "0.46886805", "0.46704102", "0.4663158", "0.46612278", "0.46462405", "0.4630991", "0.46164927", "0.46098566", "0.46091607", "0.46090907", "0.4606507", "0.460068", "0.45988998", "0.4556819", "0.45533022", "0.45457566", "0.4545474", "0.45447996", "0.45226452", "0.45226452", "0.4513628", "0.4513105", "0.45054087", "0.4504665", "0.45005614", "0.44965115", "0.4494211", "0.44892597", "0.44832587", "0.44816026", "0.44768664", "0.44737014", "0.44708496", "0.44665796", "0.44561076", "0.44541907", "0.44430804", "0.44402394", "0.44395337", "0.44392303", "0.443172", "0.44314247", "0.44268045", "0.44241986", "0.44182414", "0.44167346", "0.4413189", "0.4398397", "0.43956807", "0.43895668", "0.43894857" ]
0.0
-1
GetVendor vendor company name only, in text format. return "" for any errors
func (c *Client) GetVendor(term string) string { c.Output = "vendor" result := "" httpResp, err := c.sendRequest("GET", term, nil) if err != nil { return result } if httpResp.StatusCode == http.StatusOK { defer httpResp.Body.Close() body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return result } result = string(body) } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d UserData) CommercialCompanyName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\"))\n\tif !d.Has(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (o *Wireless) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}", "func (o *NetworkLicenseFile) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}", "func (s UserSet) CommercialCompanyName() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\")).(string)\n\treturn res\n}", "func (o *Wireless) GetVendorOk() (string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Vendor, true\n}", "func (this *metaUsbSvc) VendorName(vid string) (string, error) {\n\tif vendor, err := this.GetVendor(vid); err != nil {\n\t\treturn ``, err\n\t} else {\n\t\treturn vendor.String(), nil\n\t}\n}", "func (o *NetworkElementSummaryAllOf) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}", "func (o *NetworkLicenseFile) GetVendorOk() (*string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Vendor, true\n}", "func (o *EquipmentIdentityAllOf) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}", "func (o *NetworkElementSummaryAllOf) GetVendorOk() (*string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Vendor, true\n}", "func (o LogzMonitorOutput) CompanyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *LogzMonitor) pulumi.StringPtrOutput { return v.CompanyName }).(pulumi.StringPtrOutput)\n}", "func (client *XenClient) SMGetVendor(self string) (result string, err error) {\n\tobj, err := client.APICall(\"SM.get_vendor\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}", "func (native *OpenGL) GetVendorName() string {\n\treturn gl.GoStr(gl.GetString(gl.VENDOR))\n}", "func (o *AdminInfo) GetVendorOk() (*Vendor, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Vendor, true\n}", "func (o *EquipmentIdentityAllOf) GetVendorOk() (*string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Vendor, true\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetVendorNameOk() (*string, bool) {\n\tif o == nil || o.VendorName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VendorName, true\n}", "func (a Annotations) Vendor() (string, bool) {\n\treturn a.Get(VendorAnnotation)\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetVendorName() string {\n\tif o == nil || o.VendorName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VendorName\n}", "func (d UserData) CompanyName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"CompanyName\", \"company_name\"))\n\tif !d.Has(models.NewFieldName(\"CompanyName\", \"company_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}", "func (s VulnerabilityVendor) String() string {\n\treturn awsutil.Prettify(s)\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 (x ApmDatabaseInstanceEntity) GetVendor() string {\n\treturn x.Vendor\n}", "func (o *InvoiceSeller) GetCompanyOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Company, true\n}", "func (op *OptVendorOpts) String() string {\n\treturn fmt.Sprintf(\"%s: {EnterpriseNumber=%v VendorOptions=%v}\", op.Code(), op.EnterpriseNumber, op.VendorOpts)\n}", "func (o *Invoice) GetCompanyOk() (*string, bool) {\n\tif o == nil || o.Company == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Company, true\n}", "func (m *User) GetCompanyName()(*string) {\n return m.companyName\n}", "func (c FieldsCollection) CommercialCompanyName() *models.Field {\n\treturn c.MustGet(\"CommercialCompanyName\")\n}", "func (s UserSet) CompanyName() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"CompanyName\", \"company_name\")).(string)\n\treturn res\n}", "func (m *AgedAccountsPayable) GetVendorId()(*string) {\n val, err := m.GetBackingStore().Get(\"vendorId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *IaasDeviceStatusAllOf) GetDeviceVendor() string {\n\tif o == nil || o.DeviceVendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DeviceVendor\n}", "func (o *AdminInfo) GetVendor() Vendor {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret Vendor\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}", "func Vendor() (string, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Find the directory that contains glide.yaml\n\tyamldir, err := GlideWD(cwd)\n\tif err != nil {\n\t\treturn cwd, err\n\t}\n\n\tgopath := filepath.Join(yamldir, VendorDir)\n\n\t// Resolve symlinks\n\tinfo, err := os.Lstat(gopath)\n\tif err != nil {\n\t\treturn gopath, nil\n\t}\n\tfor i := 0; IsLink(info) && i < 255; i++ {\n\t\tp, err := os.Readlink(gopath)\n\t\tif err != nil {\n\t\t\treturn gopath, nil\n\t\t}\n\n\t\tif filepath.IsAbs(p) {\n\t\t\tgopath = p\n\t\t} else {\n\t\t\tgopath = filepath.Join(filepath.Dir(gopath), p)\n\t\t}\n\n\t\tinfo, err = os.Lstat(gopath)\n\t\tif err != nil {\n\t\t\treturn gopath, nil\n\t\t}\n\t}\n\n\treturn gopath, nil\n}", "func (m *AgedAccountsPayable) GetVendorNumber()(*string) {\n val, err := m.GetBackingStore().Get(\"vendorNumber\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *InlineResponse200115Company) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (a *Client) GetVendorVerifyInfo(params *GetVendorVerifyInfoParams, authInfo runtime.ClientAuthInfoWriter) (*GetVendorVerifyInfoOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetVendorVerifyInfoParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetVendorVerifyInfo\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/app_vendors/app_vendor\",\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: &GetVendorVerifyInfoReader{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.(*GetVendorVerifyInfoOK), nil\n\n}", "func (o *ActivateTenantRequest) GetCompanyNameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.CompanyName, true\n}", "func (me TxsdCompanyID) String() string { return xsdt.String(me).String() }", "func (v VendorItem) String() string {\n\tjv, _ := json.Marshal(v)\n\treturn string(jv)\n}", "func (o *User) GetCompanyNameOk() (string, bool) {\n\tif o == nil || o.CompanyName == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.CompanyName, true\n}", "func getPCIVendor(vendorID string, deviceID string, sVendorID string, sDeviceID string) (string, string, string, error) {\n\tfn := \"/usr/share/hwdata/pci.ids\"\n\tif _, err := os.Stat(fn); os.IsNotExist(err) {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"file doesn't exist: %s\", fn)\n\t}\n\n\to, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\tvendor := \"\"\n\tdevice := \"\"\n\tsName := \"\"\n\tcols := 2\n\tfor _, line := range strings.Split(string(o), \"\\n\") {\n\t\tvals := strings.SplitN(line, \" \", cols)\n\t\tif len(vals) < 2 || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i := 0; i < cols; i++ {\n\t\t\tvals[i] = strings.Trim(vals[i], \" \\t\")\n\t\t}\n\n\t\tif strings.LastIndex(line, \"\\t\") == -1 && vals[0] == vendorID {\n\t\t\tvendor = vals[1]\n\t\t\tcontinue\n\t\t}\n\n\t\tif vendor != \"\" && strings.LastIndex(line, \"\\t\") == 0 && vals[0] == deviceID {\n\t\t\tdevice = vals[1]\n\t\t\tcols = 3\n\t\t\tcontinue\n\t\t}\n\n\t\tif vendor != \"\" && device != \"\" && strings.LastIndex(line, \"\\t\") == 1 && vals[0] == sVendorID && vals[1] == sDeviceID {\n\t\t\tsName = vals[2]\n\t\t\tbreak\n\t\t}\n\n\t\tif vendor != \"\" && strings.LastIndex(line, \"\\t\") == -1 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn vendor, device, sName, nil\n}", "func (x ApmDatabaseInstanceEntityOutline) GetVendor() string {\n\treturn x.Vendor\n}", "func TrimVendorPath(s string) string {\n\tif strings.Contains(s, \"/vendor/\") {\n\t\tif s[:1] == \"*\" {\n\t\t\treturn \"*\" + strings.Split(s, \"/vendor/\")[1]\n\t\t}\n\t\treturn strings.Split(s, \"/vendor/\")[1]\n\t}\n\treturn s\n}", "func getLicenceString() string {\n\tlicence :=\n\t\t\"\\nCopyright (c) 2015, Lindsay Bradford\\n\" +\n\t\t\t\"All rights reserved.\\n\\n\" +\n\t\t\t\"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\\n\\n\" +\n\t\t\t\"1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\\n\\n\" +\n\t\t\t\"2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\\n\\n\" +\n\t\t\t\"3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\\n\\n\" +\n\t\t\t\"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED \" +\n\t\t\t\"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \" +\n\t\t\t\"PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY \" +\n\t\t\t\"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \" +\n\t\t\t\"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \" +\n\t\t\t\"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \" +\n\t\t\t\"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\\n\"\n\n\treturn licence\n}", "func (o *Invoice) GetCompany() string {\n\tif o == nil || o.Company == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Company\n}", "func unvendor(importPath string) string {\n\tif vendorerAndVendoree := strings.SplitN(importPath, \"/vendor/\", 2); len(vendorerAndVendoree) == 2 {\n\t\treturn vendorerAndVendoree[1]\n\t}\n\treturn importPath\n}", "func Vendor() string {\n\tfp, err := gap.NewScope(gap.User, conf.GapUser).CacheDir()\n\tif err != nil {\n\t\th, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\tlog.Print(fmt.Errorf(\"vendorPath userhomedir: %w\", err))\n\t\t}\n\t\treturn path.Join(h, \".vendor/df2\")\n\t}\n\treturn fp\n}", "func (v VendorItems) String() string {\n\tjv, _ := json.Marshal(v)\n\treturn string(jv)\n}", "func (o *PartnerCustomerCreateRequest) GetCompanyNameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.CompanyName, true\n}", "func GetOrgName() string {\n\treturn myViper.GetString(\"client.sdk.org\")\n}", "func GetCompany(c *fiber.Ctx) error {\n\tcompanyCollection := config.MI.DB.Collection(\"company\")\n\t// get parameter value\n\tparamID := c.Params(\"id\")\n\t// convert parameterID to objectId\n\tid, err := primitive.ObjectIDFromHex(paramID)\n\n\t// if error while parsing paramID\n\tif err != nil {\n\t\treturn c.Status(fiber.StatusBadRequest).JSON(fiber.Map{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"Cannot parse Id\",\n\t\t\t\"error\": err,\n\t\t})\n\t}\n\n\t//find company\n\tdevice := &models.Device{}\n\tquery := bson.D{{Key: \"_id\", Value: id}}\n\terr = companyCollection.FindOne(c.Context(), query).Decode(device)\n\tif err != nil {\n\t\treturn c.Status(fiber.StatusNotFound).JSON(fiber.Map{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"Company Not found\",\n\t\t\t\"error\": err,\n\t\t})\n\t}\n\treturn c.Status(fiber.StatusOK).JSON(fiber.Map{\n\t\t\"success\": true,\n\t\t\"results\": device,\n\t})\n\n}", "func (o *Service) GetNewestMacVendorOk() (string, bool) {\n\tif o == nil || o.NewestMacVendor == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.NewestMacVendor, true\n}", "func (m *AgreementAcceptance) GetDeviceDisplayName()(*string) {\n return m.deviceDisplayName\n}", "func (this *metaUsbSvc) ProductName(vid, pid string) (string, error) {\n\tif vendor, err := this.GetVendor(vid); err != nil {\n\t\treturn ``, err\n\t} else if product, err := vendor.GetProduct(pid); err != nil {\n\t\treturn ``, err\n\t} else {\n\t\treturn product.String(), nil\n\t}\n}", "func (disturbia *Disturbia) GetProductName(doc *goquery.Document) (name string) {\n\tnameSelector := doc.Find(\"h1\")\n\tname = nameSelector.First().Text()\n\treturn\n}", "func (o *Service) GetNewestMacVendor() string {\n\tif o == nil || o.NewestMacVendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.NewestMacVendor\n}", "func (u *User) GetCompany() string {\n\tif u == nil || u.Company == nil {\n\t\treturn \"\"\n\t}\n\treturn *u.Company\n}", "func (o *ReservationModel) GetCompanyOk() (*EmbeddedCompanyModel, bool) {\n\tif o == nil || o.Company == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Company, true\n}", "func Vendor() error {\n\tmg.Deps(Deps)\n\tfmt.Println(\"vendoring deps ...\")\n\treturn mod(\"vendor\")\n}", "func (o *IaasDeviceStatusAllOf) GetDeviceVendorOk() (*string, bool) {\n\tif o == nil || o.DeviceVendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DeviceVendor, true\n}", "func GetDeviceManufacturerInfo(log *base.LogObject) (string, string, string, string, string) {\n\tpname, err := base.Exec(log, \"dmidecode\", \"-s\", \"system-product-name\").Output()\n\tif err != nil {\n\t\tlog.Errorf(\"GetDeviceManufacturerInfo system-product-name failed %s\\n\",\n\t\t\terr)\n\t\tpname = []byte{}\n\t}\n\tmanufacturer, err := base.Exec(log, \"dmidecode\", \"-s\", \"system-manufacturer\").Output()\n\tif err != nil {\n\t\tlog.Errorf(\"GetDeviceManufacturerInfo system-manufacturer failed %s\\n\",\n\t\t\terr)\n\t\tmanufacturer = []byte{}\n\t}\n\tversion, err := base.Exec(log, \"dmidecode\", \"-s\", \"system-version\").Output()\n\tif err != nil {\n\t\tlog.Errorf(\"GetDeviceManufacturerInfo system-version failed %s\\n\",\n\t\t\terr)\n\t\tversion = []byte{}\n\t}\n\tuuid, err := base.Exec(log, \"dmidecode\", \"-s\", \"system-uuid\").Output()\n\tif err != nil {\n\t\tlog.Errorf(\"GetDeviceManufacturerInfo system-uuid failed %s\\n\",\n\t\t\terr)\n\t\tuuid = []byte{}\n\t}\n\tproductSerial := GetProductSerial(log)\n\tproductManufacturer := string(manufacturer)\n\tproductName := string(pname)\n\tproductVersion := string(version)\n\tproductUuid := string(uuid)\n\treturn productManufacturer, productName, productVersion, productSerial, productUuid\n}", "func (o *InvoiceSeller) GetCompany() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Company\n}", "func GetCompany(c *gin.Context) {\n\tixorm, _ := c.Get(\"xorm\")\n\txormEngine, _ := ixorm.(*xorm.Engine)\n\n\tid, _ := strconv.Atoi(c.Query(\"companyId\"))\n\tname := c.Query(\"name\")\n\tzipcode := c.Query(\"zipcode\")\n\n\tlistCompany, _ := db.FindCompany(xormEngine, id, name, zipcode, true, 0)\n\n\tc.Header(\"Content-Type\", \"application/json\")\n\tif len(listCompany) > 0 {\n\t\tc.JSON(http.StatusOK, listCompany)\n\t} else {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t}\n\n}", "func getProjectNameOrTenantName(configVarResolver *providerconfig.ConfigVarResolver, rawConfig *openstacktypes.RawConfig) (string, error) {\n\tprojectName, err := configVarResolver.GetConfigVarStringValueOrEnv(rawConfig.ProjectName, envOSProjectName)\n\tif err == nil && len(projectName) > 0 {\n\t\treturn projectName, nil\n\t}\n\n\t// fallback to tenantName.\n\treturn configVarResolver.GetConfigVarStringValue(rawConfig.TenantName)\n}", "func GetLicenseUserCompany(company *string) int {\n\tvar cCompany = getCArray()\n\tstatus := C.GetLicenseUserCompany(&cCompany[0], maxCArrayLength)\n\t*company = ctoGoString(&cCompany[0])\n\treturn int(status)\n}", "func (o *Organization) GetCompany() string {\n\tif o == nil || o.Company == nil {\n\t\treturn \"\"\n\t}\n\treturn *o.Company\n}", "func FindVendor(ctx context.Context, exec boil.ContextExecutor, iD int, selectCols ...string) (*Vendor, error) {\n\tvendorObj := &Vendor{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from `vendors` where `id`=?\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(ctx, exec, vendorObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from vendors\")\n\t}\n\n\treturn vendorObj, nil\n}", "func (driver Driver) ManufacturerName() string {\n\treturn driver.data.MfgName.String()\n}", "func (d *Storage) CreateVendor(v authenticating.Vendor) (*[2]string, error) {\n\t// Initialize AWS session\n\tsvc := utils.SetupAWSSession()\n\n\t// TODO we need a nice util function to get multiple attributes from the DB (i.e. username and email)\n\n\t// Get username from DynamoDB\n\tresult, err := GetItemDynamoDB(svc, \"vendor\", \"username\", v.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuser := Vendor{}\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &user)\n\tif err != nil {\n\t\treturn nil, storage.ErrUnmarshaling\n\t}\n\n\t// Get email from DynamoDB\n\temail, err := ScanDynamoDB(\"vendor\", \"email\", v.Email)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check username, email doesn't exist\n\tif user.Username != \"\" || len(email.Items) != 0 {\n\t\tcolor.Red(\"Username or email already exists\")\n\t\treturn nil, authenticating.ErrVendorAlreadyExists\n\t}\n\n\t// Check email is a valid email address\n\t// TODO in a later refactor, this should be taken out of this function and put inside another... this is business logic, not database logic i.e. not depending on DynamoDB\n\tif len(v.Email) < 3 && len(v.Email) > 254 {\n\t\treturn nil, authenticating.ErrInvalidEmailLength\n\t}\n\n\tif !emailRegex.MatchString(v.Email) {\n\t\treturn nil, authenticating.ErrInvalidEmailMatching\n\t}\n\tparts := strings.Split(v.Email, \"@\")\n\tmx, err := net.LookupMX(parts[1])\n\tif err != nil || len(mx) == 0 {\n\t\treturn nil, authenticating.ErrInvalidEmail\n\t}\n\n\t// Generate key pair for new vendor\n\tskVendor, pkVendor, err := keys.GenerateKeys()\n\tif err != nil {\n\t\tcolor.Red(\"Failed to generate keys\")\n\t\treturn nil, keys.ErrFailedToGenerateKeys\n\t}\n\n\t// Generate hash of secret key to be used as a signing measure for producing/consuming data\n\th := sha256.New()\n\th.Write([]byte(*skVendor))\n\tapiKeyHash := hex.EncodeToString(h.Sum(nil))\n\n\t// Generate Supertype ID\n\tsupertypeID, err := utils.GenerateSupertypeID(v.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Cursory check for valid email address\n\tif !utils.ValidateEmail(v.Email) {\n\t\treturn nil, storage.ErrInvalidEmail\n\t}\n\n\t// Create a final vendor with which to upload\n\tcreateVendor := authenticating.CreateVendor{\n\t\tFirstName: v.FirstName,\n\t\tLastName: v.LastName,\n\t\tEmail: v.Email,\n\t\tBusinessName: v.BusinessName,\n\t\tUsername: v.Username,\n\t\tPublicKey: *pkVendor,\n\t\tAPIKeyHash: apiKeyHash,\n\t\tSupertypeID: *supertypeID,\n\t\tAccountBalance: 0.0,\n\t}\n\n\terr = PutItemInDynamoDB(createVendor, \"vendor\", svc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeyPair := [2]string{*pkVendor, *skVendor}\n\n\treturn &keyPair, nil\n}", "func (c Config) CompanyOrDefault() string {\n\tif c.Company != \"\" {\n\t\treturn c.Company\n\t}\n\treturn DefaultCompany\n}", "func (c Config) CompanyOrDefault() string {\n\tif c.Company != \"\" {\n\t\treturn c.Company\n\t}\n\treturn DefaultCompany\n}", "func getManufacturer(){\n manufacturer, err := exec.Command(\"/bin/bash\", \"-c\", \"dmidecode --type 3 | awk '/Manufacturer/ {print $2}'\").Output()\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"%s\", manufacturer)\n}", "func (c FieldsCollection) CompanyName() *models.Field {\n\treturn c.MustGet(\"CompanyName\")\n}", "func extractVirusName(line string) string {\n\tkeyvalue := strings.Split(line, \"INFECTED\")\n\treturn strings.Trim(strings.TrimSpace(keyvalue[1]), \"[]\")\n}", "func Vendorlogin(c buffalo.Context) error {\n\n\treturn c.Render(200, r.HTML(\"Vendor_Login.html\", \"master_page/login_tmp.html\"))\n}", "func (os OS) String() string {\n\treturn fmt.Sprintf(\"%s:%s\", os.Vendor, os.Version)\n}", "func (t *SimpleChaincode) GetUsername(stub *shim.ChaincodeStub) (string, error) {\n\n bytes, err := stub.GetCallerCertificate();\n if err != nil { return \"\", errors.New(\"Couldn't retrieve caller certificate\") }\n x509Cert, err := x509.ParseCertificate(bytes); // Extract Certificate from result of GetCallerCertificate \n \n if err != nil { return \"\", errors.New(\"Couldn't parse certificate\") }\n fmt.Println(\"############## CERT #################\")\n\tfmt.Println(x509Cert) \n\n\tcallerRole, err := stub.ReadCertAttribute(\"role\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading attribute 'role' [%v] \\n\", err)\n\t\t//return \"\", fmt.Errorf(\"Failed fetching caller role. Error was [%v]\", err)\n\t}\n\n\tfmt.Println(\"############### CALLER ROLE ##################\")\n\tfmt.Println(string(callerRole))\n\n\taf, err := stub.ReadCertAttribute(\"affiliation\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading attribute 'role' [%v] \\n\", err)\n\t\t\n\t}\n\n\tfmt.Println(\"Affiliation #############\")\n\tfmt.Println(string(af))\n\n\tar, err := stub.ReadCertAttribute(\"affiliationRole\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading attribute 'role' [%v] \\n\", err)\n\t\t\n\t}\n\n\tfmt.Println(\"AffiliationROLE\")\n\tfmt.Println(string(ar))\n\n\tbytes, err2 := stub.GetCallerMetadata();\n if err2 != nil { fmt.Println(\"Couldn't retrieve caller metadata\") }\n\t\n\tfmt.Println(string(bytes)) \n\n \n return x509Cert.Subject.CommonName, nil\n}", "func (v *Kounta) GetCompany(token string) (*Company, error) {\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tu, _ := url.ParseRequestURI(baseURL)\n\tu.Path = companiesURL\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tr, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Header = http.Header(make(map[string][]string))\n\tr.Header.Set(\"Accept\", \"application/json\")\n\tr.Header.Set(\"Authorization\", \"Bearer \"+token)\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawResBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//\tfmt.Println(\"GetCompany Body\", string(rawResBody))\n\n\tif res.StatusCode == 200 {\n\t\tvar resp Company\n\t\terr = json.Unmarshal(rawResBody, &resp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &resp, nil\n\t}\n\treturn nil, fmt.Errorf(\"Failed to get Kounta Company %s\", res.Status)\n\n}", "func (p Details) GetCompanyID() string {\n\treturn p.CompanyID.Hex()\n}", "func (o *NetworkElementSummaryAllOf) SetVendor(v string) {\n\to.Vendor = &v\n}", "func (l *License) GetName() string {\n\tif l == nil || l.Name == nil {\n\t\treturn \"\"\n\t}\n\treturn *l.Name\n}", "func nonVendoredPkgPath(pkgPath string) string {\n\tlastVendorIndex := strings.LastIndex(pkgPath, \"/vendor/\")\n\tif lastVendorIndex == -1 {\n\t\treturn pkgPath\n\t}\n\treturn pkgPath[lastVendorIndex+len(\"/vendor/\"):]\n}", "func (o *InlineResponse2004People) GetCompanyNameOk() (*string, bool) {\n\tif o == nil || o.CompanyName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CompanyName, true\n}", "func (p *provider) getProjectNameOrTenantName(rawConfig *openstacktypes.RawConfig) (string, error) {\n\tprojectName, err := p.configVarResolver.GetConfigVarStringValueOrEnv(rawConfig.ProjectName, \"OS_PROJECT_NAME\")\n\tif err == nil && len(projectName) > 0 {\n\t\treturn projectName, nil\n\t}\n\n\t//fallback to tenantName.\n\treturn p.configVarResolver.GetConfigVarStringValueOrEnv(rawConfig.TenantName, \"OS_TENANT_NAME\")\n}", "func GetCompanyOfficer(w http.ResponseWriter, req *http.Request) {\n\n\t// Check for a company number in request\n\tvars := mux.Vars(req)\n\n\tcompanyNumber, err := utils.GetValueFromVars(vars, \"company_number\")\n\tif err != nil {\n\t\tlog.ErrorR(req, err)\n\t\tm := models.NewMessageResponse(\"company number not in request context\")\n\t\tutils.WriteJSONWithStatus(w, req, m, http.StatusBadRequest)\n\t\treturn\n\t}\n\tcompanyNumber = strings.ToUpper(companyNumber)\n\n\t// Check for Officer ID in request\n\tofficerID, err := utils.GetValueFromVars(vars, \"officer_id\")\n\tif err != nil {\n\t\tlog.ErrorR(req, err)\n\t\tm := models.NewMessageResponse(\"officer ID not in request context\")\n\t\tutils.WriteJSONWithStatus(w, req, m, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcompanyOfficer, responseType, err := service.GetOfficer(companyNumber, officerID)\n\tif err != nil {\n\t\tlog.ErrorR(req, fmt.Errorf(\"error calling Oracle API to get officer: %v\", err))\n\t\tm := models.NewMessageResponse(\"there was a problem communicating with the Oracle API\")\n\t\tutils.WriteJSONWithStatus(w, req, m, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif responseType == service.NotFound {\n\t\tm := models.NewMessageResponse(\"No officer found\")\n\t\tutils.WriteJSONWithStatus(w, req, m, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tutils.WriteJSON(w, req, companyOfficer)\n}", "func (s *service) GetCompanyBySigningEntityName(ctx context.Context, signingEntityName string) (*models.Company, error) {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"v2.company.service.GetCompanyBySigningEntityName\",\n\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\"signingEntityName\": signingEntityName,\n\t}\n\n\tlog.WithFields(f).Warn(\"looking up company record by signing entity name...\")\n\tcompanyModel, err := s.companyRepo.GetCompanyBySigningEntityName(ctx, signingEntityName)\n\tif err != nil {\n\t\tif _, ok := err.(*utils.CompanyNotFound); ok { // nolint\n\t\t\t// As a backup, in case the signing entity name was not set on the old records, lookup the company by it's normal name\n\t\t\tlog.WithFields(f).Debugf(\"signing entity name not found. as a backup, searching company by name using signing entity name value: %s\", signingEntityName)\n\t\t\tcompanyModel, err = s.companyRepo.GetCompanyByName(ctx, signingEntityName)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(f).WithError(err).Warn(\"unable to lookup company name by attempting to use the signing entity name\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tlog.WithFields(f).WithError(err).Warn(\"unable to lookup company by signing entity name\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif companyModel == nil {\n\t\tlog.WithFields(f).Debugf(\"search by company signing entity name: %s didn't locate the record\", signingEntityName)\n\t\t// As a backup, in case the signing entity name was not set on the old records, lookup the company by it's normal name\n\t\tlog.WithFields(f).Debugf(\"as a backup, searching company by name using signing entity name value: %s\", signingEntityName)\n\t\tcompanyModel, err = s.companyRepo.GetCompanyByName(ctx, signingEntityName)\n\t\tif err != nil {\n\t\t\tlog.WithFields(f).WithError(err).Warn(\"unable to lookup company name by attempting to use the signing entity name\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif companyModel == nil {\n\t\t\tlog.WithFields(f).Debugf(\"search by company name: %s didn't locate the record\", signingEntityName)\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\t// Convert from v1 to v2 model - use helper: Copy(toValue interface{}, fromValue interface{})\n\tvar v2CompanyModel v2Models.Company\n\tcopyErr := copier.Copy(&v2CompanyModel, &companyModel)\n\tif copyErr != nil {\n\t\tlog.WithFields(f).Warnf(\"problem converting v1 company model to a v2 company model, error: %+v\", copyErr)\n\t\treturn nil, copyErr\n\t}\n\n\treturn &v2CompanyModel, nil\n}", "func getstring(org string) string {\n\tresult := \"\"\n\t// it is a little status machine( IN ESPCAE: '\"...\\', NOT IN ESPCE: '\"...'(\n\t// mormal string that do not have char '\\')\n\tIN_ESPCAE_STATUS := false\n\tfor _, v := range org[1 : len(org)-1] {\n\t\tif IN_ESPCAE_STATUS {\n\t\t\t// if now in espcae status, it will espcae char '\\', '\\\"', and \"\\'\"\n\t\t\tif v == '\\\\' || v == '\"' || v == '\\'' {\n\t\t\t\tresult += string(v)\n\t\t\t\t// back to normal status\n\t\t\t\tIN_ESPCAE_STATUS = false\n\t\t\t} else {\n\t\t\t\t// it do not matter, we do not need to espcae it, so we back the\n\t\t\t\t// normal string( e.g. \"\\a\" -> \"\\a\" )\n\t\t\t\tresult += string('\\\\')\n\t\t\t\tresult += string(v)\n\t\t\t}\n\t\t} else if v == '\\\\' {\n\t\t\t// if match the char '\\', then change self's status\n\t\t\tIN_ESPCAE_STATUS = true\n\t\t} else {\n\t\t\t// in normal status\n\t\t\tresult += string(v)\n\t\t}\n\t}\n\treturn result\n}", "func (x ThirdPartyServiceEntity) GetName() string {\n\treturn x.Name\n}", "func ShopFullName(name string) string {\n\tname = strings.TrimSpace(name)\n\tname = strings.Trim(name, \".\")\n\tif strings.Contains(name, \"myshopify.com\") {\n\t\treturn name\n\t}\n\treturn name + \".myshopify.com\"\n}", "func (m *InsuranceMutation) OldCompany(ctx context.Context) (v string, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, fmt.Errorf(\"OldCompany is allowed only on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, fmt.Errorf(\"OldCompany requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldCompany: %w\", err)\n\t}\n\treturn oldValue.Company, nil\n}", "func (o *InlineResponse200115) GetCompanyOk() (*InlineResponse200115Company, bool) {\n\tif o == nil || o.Company == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Company, true\n}", "func (m *CreatePostRequestBody) GetManufacturer()(*string) {\n return m.manufacturer\n}", "func (m *CloudPcConnection) GetTenantDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"tenantDisplayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o *Platform) GetDeveloper() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Developer\n}", "func (o *PartnerCustomerCreateRequest) GetLegalEntityNameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.LegalEntityName, true\n}", "func (o DomainOutput) Cname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Domain) pulumi.StringOutput { return v.Cname }).(pulumi.StringOutput)\n}", "func (ccid *CCID) GetName() string {\n\tif ccid.ChaincodeSpec == nil {\n\t\tpanic(\"nil chaincode spec\")\n\t}\n\n\tname := ccid.ChaincodeSpec.ChaincodeId.Name\n\tif ccid.Version != \"\" {\n\t\tname = name + \"-\" + ccid.Version\n\t}\n\n\t//this better be chainless system chaincode!\n\tif ccid.ChainID != \"\" {\n\t\thash := util.ComputeSHA256([]byte(ccid.ChainID))\n\t\thexstr := hex.EncodeToString(hash[:])\n\t\tname = name + \"-\" + hexstr\n\t}\n\n\treturn name\n}", "func (m *InsuranceMutation) Company() (r string, exists bool) {\n\tv := m.company\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o *CustomerInfo) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func DiskVendor(disk string) string {\n\tmsg := `\nThe DiskVendor() function has been DEPRECATED and will be\nremoved in the 1.0 release of ghw. Please use the Disk.Vendor attribute.\n`\n\twarn(msg)\n\tctx := contextFromEnv()\n\treturn ctx.diskVendor(disk)\n}", "func (o *InlineResponse200115Company) GetNameOk() (*string, bool) {\n\tif o == nil || o.Name == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Name, true\n}" ]
[ "0.6398742", "0.6362965", "0.63377017", "0.6300475", "0.62950224", "0.6259747", "0.6256496", "0.61700916", "0.61029965", "0.60014296", "0.59904176", "0.598609", "0.59651405", "0.5959669", "0.5917091", "0.5840147", "0.5808993", "0.5797002", "0.5779641", "0.5743736", "0.5726435", "0.57179105", "0.5713903", "0.5703404", "0.5694947", "0.5667528", "0.5561658", "0.5468538", "0.54620504", "0.5451797", "0.5419444", "0.5391146", "0.5381472", "0.5358688", "0.53411186", "0.5293739", "0.5266614", "0.52591246", "0.5255947", "0.5254827", "0.5248698", "0.52051306", "0.5196439", "0.51961446", "0.51960546", "0.51719093", "0.5167078", "0.5158447", "0.5134029", "0.51325065", "0.5127899", "0.51253444", "0.5124471", "0.51240945", "0.5115682", "0.5114986", "0.50918233", "0.5085328", "0.50596815", "0.5051792", "0.5029283", "0.50279015", "0.50100493", "0.49717498", "0.49697638", "0.4967789", "0.49655882", "0.49494824", "0.49485075", "0.49485075", "0.49474373", "0.4940378", "0.49272287", "0.49237838", "0.49132663", "0.49085683", "0.48993766", "0.48944718", "0.48782173", "0.48695377", "0.48450866", "0.48414576", "0.48369375", "0.48315373", "0.48273155", "0.48246488", "0.48154145", "0.48124668", "0.4798887", "0.47963715", "0.47912514", "0.4791244", "0.47854793", "0.47820336", "0.47790274", "0.4766303", "0.4762437", "0.47622165", "0.4759924", "0.47583395" ]
0.7025577
0
TransformAccount converts an account from the history archive ingestion system into a form suitable for BigQuery
func TransformAccount(ledgerChange ingestio.Change) (AccountOutput, error) { ledgerEntry, outputDeleted, err := utils.ExtractEntryFromChange(ledgerChange) if err != nil { return AccountOutput{}, err } accountEntry, accountFound := ledgerEntry.Data.GetAccount() if !accountFound { return AccountOutput{}, fmt.Errorf("Could not extract account data from ledger entry; actual type is %s", ledgerEntry.Data.Type) } outputID, err := accountEntry.AccountId.GetAddress() if err != nil { return AccountOutput{}, err } outputBalance := int64(accountEntry.Balance) if outputBalance < 0 { return AccountOutput{}, fmt.Errorf("Balance is negative (%d) for account: %s", outputBalance, outputID) } //The V1 struct is the first version of the extender from accountEntry. It contains information on liabilities, and in the future //more extensions may contain extra information accountExtensionInfo, V1Found := accountEntry.Ext.GetV1() var outputBuyingLiabilities, outputSellingLiabilities int64 if V1Found { liabilities := accountExtensionInfo.Liabilities outputBuyingLiabilities, outputSellingLiabilities = int64(liabilities.Buying), int64(liabilities.Selling) if outputBuyingLiabilities < 0 { return AccountOutput{}, fmt.Errorf("The buying liabilities count is negative (%d) for account: %s", outputBuyingLiabilities, outputID) } if outputSellingLiabilities < 0 { return AccountOutput{}, fmt.Errorf("The selling liabilities count is negative (%d) for account: %s", outputSellingLiabilities, outputID) } } outputSequenceNumber := int64(accountEntry.SeqNum) if outputSequenceNumber < 0 { return AccountOutput{}, fmt.Errorf("Account sequence number is negative (%d) for account: %s", outputSequenceNumber, outputID) } outputNumSubentries := uint32(accountEntry.NumSubEntries) inflationDestAccountID := accountEntry.InflationDest var outputInflationDest string if inflationDestAccountID != nil { outputInflationDest, err = inflationDestAccountID.GetAddress() if err != nil { return AccountOutput{}, err } } outputFlags := uint32(accountEntry.Flags) outputHomeDomain := string(accountEntry.HomeDomain) outputMasterWeight := int32(accountEntry.MasterKeyWeight()) outputThreshLow := int32(accountEntry.ThresholdLow()) outputThreshMed := int32(accountEntry.ThresholdMedium()) outputThreshHigh := int32(accountEntry.ThresholdHigh()) outputLastModifiedLedger := uint32(ledgerEntry.LastModifiedLedgerSeq) transformedAccount := AccountOutput{ AccountID: outputID, Balance: outputBalance, BuyingLiabilities: outputBuyingLiabilities, SellingLiabilities: outputSellingLiabilities, SequenceNumber: outputSequenceNumber, NumSubentries: outputNumSubentries, InflationDestination: outputInflationDest, Flags: outputFlags, HomeDomain: outputHomeDomain, MasterWeight: outputMasterWeight, ThresholdLow: outputThreshLow, ThresholdMedium: outputThreshMed, ThresholdHigh: outputThreshHigh, LastModifiedLedger: outputLastModifiedLedger, Deleted: outputDeleted, } return transformedAccount, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (acc *BaseAccount) ConvertAccount(cdc codec.Marshaler) interface{} {\n\taccount := sdk.BaseAccount{\n\t\tAddress: acc.Address,\n\t\tAccountNumber: acc.AccountNumber,\n\t\tSequence: acc.Sequence,\n\t}\n\n\tvar pkStr string\n\tif acc.PubKey == nil {\n\t\treturn account\n\t}\n\n\tvar pk crypto.PubKey\n\tif err := cdc.UnpackAny(acc.PubKey, &pk); err != nil {\n\t\treturn sdk.BaseAccount{}\n\t}\n\n\tpkStr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\taccount.PubKey = pkStr\n\treturn account\n}", "func (tr BitcoinTranslator) ToAccountMovements(address string, v interface{}) (*domain.AccountMovements, error) {\n\ttxs, _ := v.([]Transaction)\n\tam := domain.NewAccountMovements(address)\n\n\tfor _, tx := range txs {\n\t\t// Inputs will be reflected as a spent\n\t\tfor _, in := range tx.Inputs {\n\t\t\tif in.Addresses[0] != address {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tval, ok := new(big.Int).SetString(in.Value, 10)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"bitcoin translation error, cannot convert in.Value(%s) to bigint\", in.Value)\n\t\t\t}\n\t\t\tam.Spend(tx.BlockHeight, tx.BlockTime, tx.TxID, val, \"\")\n\t\t}\n\n\t\t// Outputs will be reflected as a receive\n\t\tfor _, out := range tx.Outputs {\n\t\t\tif out.Addresses[0] != address {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tval, ok := new(big.Int).SetString(out.Value, 10)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"bitcoin translation error, cannot convert out.Value(%s) to bigint\", out.Value)\n\t\t\t}\n\t\t\tam.Receive(tx.BlockHeight, tx.BlockTime, tx.TxID, val, \"\")\n\t\t}\n\t}\n\n\treturn am, nil\n}", "func (m MuxedAccount) ToAccountId() AccountId {\n\tresult := AccountId{Type: PublicKeyTypePublicKeyTypeEd25519}\n\tswitch m.Type {\n\tcase CryptoKeyTypeKeyTypeEd25519:\n\t\ted := m.MustEd25519()\n\t\tresult.Ed25519 = &ed\n\tcase CryptoKeyTypeKeyTypeMuxedEd25519:\n\t\ted := m.MustMed25519().Ed25519\n\t\tresult.Ed25519 = &ed\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unknown muxed account type: %v\", m.Type))\n\t}\n\treturn result\n}", "func TransformPaymentSummaryAccount(mctx libkb.MetaContext, p stellar1.PaymentSummary, oc OwnAccountLookupCache, accountID stellar1.AccountID) (*stellar1.PaymentLocal, error) {\n\treturn transformPaymentSummary(mctx, p, oc, accountID)\n}", "func accountToRPC(data *account.Account) *userRPC.Account {\n\tif data == nil {\n\t\treturn nil\n\t}\n\n\tacc := &userRPC.Account{\n\t\tFirstName: data.FirstName,\n\t\tLastname: data.Lastname,\n\t\tLanguageID: data.LanguageID,\n\t\tEmails: make([]*userRPC.Email, 0, len(data.Emails)),\n\t\tPhones: make([]*userRPC.Phone, 0, len(data.Phones)),\n\t\tPatronymic: accountPatronymicToRPC(data.Patronymic),\n\t\tNickName: accountNicknameToRPC(data.Nickname),\n\t\tNativeName: accountNativeNameToRPC(data.NativeName),\n\t\tMiddleName: accountMiddleNameToRPC(data.MiddleName),\n\t\tMyAddresses: make([]*userRPC.MyAddress, 0, len(data.MyAddresses)),\n\t\tOtherAddresses: make([]*userRPC.OtherAddress, 0, len(data.OtherAddresses)),\n\t\tLocation: accountUserLocationToRPC(data.Location),\n\t\tGender: genderToRPC(data.Gender),\n\t\tBirthday: accountBirthdayToRPC(data.Birthday),\n\t\tPrivacies: accountPrivaciesToRPC(data.Privacy),\n\t\tNotifications: accountNotificationsToRPC(data.Notification),\n\t\tLastChangePassword: timeToStringDayMonthAndYear(data.LastChangePassword),\n\t\tAmountOfSessions: data.AmountOfSessions,\n\n\t\t// DateOfActivation: timeToStringDayMonthAndYear(data.CreatedAt),\n\t\t// TODO:\n\t\t// :data.Status,\n\t\t// IsEditable: ,\n\t}\n\n\tfor _, email := range data.Emails {\n\t\tacc.Emails = append(acc.Emails, accountEmailToRPC(email))\n\t}\n\n\tfor _, phone := range data.Phones {\n\t\tacc.Phones = append(acc.Phones, accountPhoneToRPC(phone))\n\t}\n\n\tfor _, address := range data.MyAddresses {\n\t\tacc.MyAddresses = append(acc.MyAddresses, accountMyAddressToRPC(address))\n\t}\n\n\tfor _, address := range data.OtherAddresses {\n\t\tacc.OtherAddresses = append(acc.OtherAddresses, accountOtherAddressToRPC(address))\n\t}\n\n\treturn acc\n}", "func (tr EthereumTranslator) ToAccountMovements(address string, v interface{}) (*domain.AccountMovements, error) {\n\ttxs, _ := v.([]Transaction)\n\tam := domain.NewAccountMovements(address)\n\taddress = blockchain.NormalizeEthereumAddress(address)\n\n\tfor _, tx := range txs {\n\t\t// Do not include reverted/failed transactions\n\t\tif tx.EthereumSpecific.Status != transactionStatusSuccess {\n\t\t\tcontinue\n\t\t}\n\n\t\tval, ok := new(big.Int).SetString(tx.Value, 10)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"blockbook ethereum translation error, cannot convert in.Value(%s) to bigint\", tx.Value)\n\t\t}\n\n\t\t// Any value transfers from this address will be reflected as a spent\n\t\tif blockchain.NormalizeEthereumAddress(tx.Inputs[0].Addresses[0]) == address {\n\t\t\tam.Spend(tx.BlockHeight, tx.BlockTime, tx.TxID, val, tx.Outputs[0].Addresses[0])\n\t\t}\n\n\t\t// Any value transfers to this address will be reflected as a receive\n\t\tif blockchain.NormalizeEthereumAddress(tx.Outputs[0].Addresses[0]) == address {\n\t\t\tam.Receive(tx.BlockHeight, tx.BlockTime, tx.TxID, val, tx.Inputs[0].Addresses[0])\n\t\t}\n\t}\n\n\treturn am, nil\n}", "func (h *HUOBI) AccountTransferRecords(ctx context.Context, code currency.Pair, transferType string, createDate, pageIndex, pageSize int64) (InternalAccountTransferData, error) {\n\tvar resp InternalAccountTransferData\n\treq := make(map[string]interface{})\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treq[\"contract_code\"] = codeValue\n\tif !common.StringDataCompareInsensitive(validTransferType, transferType) {\n\t\treturn resp, fmt.Errorf(\"invalid transferType received\")\n\t}\n\treq[\"type\"] = transferType\n\tif createDate > 90 {\n\t\treturn resp, fmt.Errorf(\"invalid create date value: only supports up to 90 days\")\n\t}\n\treq[\"create_date\"] = strconv.FormatInt(createDate, 10)\n\tif pageIndex != 0 {\n\t\treq[\"page_index\"] = pageIndex\n\t}\n\tif pageSize > 0 && pageSize <= 50 {\n\t\treq[\"page_size\"] = pageSize\n\t}\n\treturn resp, h.FuturesAuthenticatedHTTPRequest(ctx, exchange.RestFutures, http.MethodPost, huobiSwapInternalTransferRecords, nil, req, &resp)\n}", "func (a Account) ToDTO() AccountDTO {\n\treturn AccountDTO{\n\t\tID: a.ID,\n\t\tUsername: a.Username,\n\t\tOwner: a.Owner,\n\t}\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func (mc *MoacChain) accountProcessing(trade map[string]interface{}, timestamp int64, number int64) (err error) {\n\n\tgourpS.Lock()\n\tdefer gourpS.Unlock()\n\n\ttype tradeModel struct {\n\t\tBlockNumber string `json:\"blockNumber\"`\n\t\tGas string `json:\"gas\"`\n\t\tGasPrice string `json:\"gasPrice\"`\n\t\tFrom string `json:\"from\"`\n\t\tTo string `json:\"to\"`\n\t\tValue string `json:\"value\"`\n\t\tTransactionIndex string `json:\"transactionIndex\"`\n\t\tShardingFlag string `json:\"shardingFlag\"`\n\t\tSyscnt string `json:\"syscnt\"`\n\t\tNonce string `json:\"nonce\"`\n\t\tV string `json:\"v\"`\n\t\tR string `json:\"r\"`\n\t\tS string `json:\"s\"`\n\t\tInput string `json:\"input\"`\n\t\tHash string `json:\"hash\"`\n\t}\n\n\tfmt.Println(\"trade\", trade)\n\n\tvar tm tradeModel\n\tbytes, err := json.Marshal(trade)\n\tif err == nil {\n\t\tjson.Unmarshal(bytes, &tm)\n\n\t\tif err5 := mc.getTransactionReceipt(tm.Hash); err5 != nil && err5.Error() == \"\" {\n\t\t\treturn err\n\t\t}\n\n\t\ttm.From = strings.ToLower(tm.From)\n\t\ttm.To = strings.ToLower(tm.To)\n\t\ttm.Hash = strings.ToLower(tm.Hash)\n\t\tif tm.From == \"\" || tm.To == \"\" {\n\t\t\treturn\n\t\t}\n\t\tif tm.TransactionIndex != \"0x0\" {\n\t\t\tuAddrs := make([]database.UserAddress, 0)\n\n\t\t\tif len(tm.Input) > 10 && tm.Input[2:10] == \"a9059cbb\" && len(tm.Input) == 138 {\n\t\t\t\terr = database.Engine.Where(\"currency_address = ? or currency_address = ?\", tm.From, \"0x\"+tm.Input[34:74]).Find(&uAddrs)\n\t\t\t} else {\n\t\t\t\terr = database.Engine.Where(\"currency_address = ? or currency_address = ?\", tm.From, tm.To).Find(&uAddrs)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tfor _, value := range uAddrs {\n\t\t\t\t\ttr := new(database.TradeRecording)\n\t\t\t\t\tflag, tmpErr := database.Engine.Where(\"transfer_hash = ?\", tm.Hash).Get(tr)\n\n\t\t\t\t\tvar currencyId uint64\n\t\t\t\t\tvar vn *big.Float\n\t\t\t\t\tif tmpErr == nil {\n\t\t\t\t\t\tif !flag {\n\n\t\t\t\t\t\t\ttr.ChainType = \"MOAC\"\n\t\t\t\t\t\t\tif len(tm.Input) > 10 && tm.Input[2:10] == \"a9059cbb\" && len(tm.Input) == 138 {\n\n\t\t\t\t\t\t\t\ttr.ContractAddress = tm.To\n\t\t\t\t\t\t\t\ttr.ReceiveAddress = \"0x\" + tm.Input[34:74]\n\t\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\tvn, _ = strconv.ParseUint(tm.Input[74:], 16, 64)\n\t\t\t\t\t\t\t\tvn, _, _ = big.ParseFloat(tm.Input[74:], 16, 'f', big.ToZero)\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\ttr.ContractAddress = \"\"\n\t\t\t\t\t\t\t\ttr.ReceiveAddress = tm.To\n\t\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\tvn, _ = strconv.ParseUint(tm.Value[2:], 16, 64)\n\n\t\t\t\t\t\t\t\tvn, _, _ = big.ParseFloat(tm.Value[2:], 16, 'f', big.ToZero)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttr.SendAddress = tm.From\n\t\t\t\t\t\t\tgas, _, _ := big.ParseFloat(tm.Gas[2:], 16, 'f', big.ToZero)\n\t\t\t\t\t\t\tgasPrice, _, _ := big.ParseFloat(tm.GasPrice[2:], 16, 'f', big.ToZero)\n\t\t\t\t\t\t\tgasTotal, _ := gas.Mul(gas, gasPrice).Float64()\n\t\t\t\t\t\t\ttr.MinerCosts = gasTotal / math.Pow10(18)\n\t\t\t\t\t\t\ttr.TransferHash = tm.Hash\n\t\t\t\t\t\t\ttr.TransferData = tm.Input\n\t\t\t\t\t\t\ttr.BlockHeight, _ = strconv.ParseInt(tm.BlockNumber[2:], 16, 64)\n\t\t\t\t\t\t\ttr.TransferTime = timestamp\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcm := new(database.CurrencyManagement)\n\t\t\t\t\t\tdatabase.Engine.Where(\"currency_contract_address = ? and chain_type = ?\", tr.ContractAddress, \"MOAC\").Get(cm)\n\t\t\t\t\t\tif cm.CurrencyName == \"\" {\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\terr = mc.getContractInfo(tm.To)\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\tdatabase.Engine.Where(\"currency_contract_address = ? and chain_type = ?\", tr.ContractAddress, \"MOAC\").Get(cm)\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\tif cm.CurrencyName == \"\" {\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn //\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrencyId = uint64(cm.CurrencyId)\n\t\t\t\t\t\ttr.ChainType = cm.ChainType\n\t\t\t\t\t\ttr.CurrencyName = cm.CurrencyName\n\t\t\t\t\t\ttr.ContractPrecision = cm.ContractPrecision\n\t\t\t\t\t\tif vn != nil {\n\t\t\t\t\t\t\tif fv, _ := vn.Float64(); fv != 0 {\n\t\t\t\t\t\t\t\t//tr.TransferNumber = vn //float64(vn) / math.Pow10(cm.ContractPrecision)\n\n\t\t\t\t\t\t\t\ttr.TransferNumber, _ = new(big.Float).Mul(big.NewFloat(math.Pow10(-cm.ContractPrecision)), vn).Float64()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttmpTr := new(database.TradeRecording)\n\t\t\t\t\t\tdirNumber := tr.TransferNumber\n\t\t\t\t\t\tif value.CurrencyAddress == tr.SendAddress {\n\n\t\t\t\t\t\t\ttr.SendUserId = value.UserId\n\t\t\t\t\t\t\tdirNumber = -tr.TransferNumber\n\t\t\t\t\t\t\t//\t\t\t\t\t\t\tdirNumber = 0\n\t\t\t\t\t\t\texistFlag, existErr := database.Engine.Where(\"send_user_id = ? and transfer_hash = ?\", value.UserId, tr.TransferHash).Get(tmpTr)\n\t\t\t\t\t\t\tif existErr == nil && existFlag {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmoacCurrencyId := int64(2)\n\t\t\t\t\t\t\tvar tmpCM database.CurrencyManagement\n\t\t\t\t\t\t\tdatabase.Engine.Where(\"chain_type = ? and currency_name = ?\", \"MOAC\", \"MOAC\").Get(&tmpCM)\n\t\t\t\t\t\t\tif tmpCM.CurrencyId != 0 {\n\t\t\t\t\t\t\t\tmoacCurrencyId = tmpCM.CurrencyId\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tuserA := new(database.UserAssets)\n\t\t\t\t\t\t\teFlag, eErr := database.Engine.Where(\"user_id = ? and currency_id = ?\", value.UserId, moacCurrencyId).Get(userA)\n\t\t\t\t\t\t\tif eErr == nil {\n\t\t\t\t\t\t\t\tmoacnumber, _ := mc.getBalance(value.CurrencyAddress, \"\", \"0x\"+strconv.FormatInt(number, 16), 18)\n\t\t\t\t\t\t\t\tdatabase.SessionSubmit(func(session *xorm.Session) (err1 error) {\n\t\t\t\t\t\t\t\t\tuserA.CurrencyNumber = moacnumber\n\t\t\t\t\t\t\t\t\tif eFlag {\n\t\t\t\t\t\t\t\t\t\t_, err1 = session.Where(\"user_id = ? and currency_id = ?\", value.UserId, moacCurrencyId).Update(userA)\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tuserA.CurrencyId = int64(moacCurrencyId)\n\t\t\t\t\t\t\t\t\t\tuserA.UserId = value.UserId\n\t\t\t\t\t\t\t\t\t\t_, err1 = session.Insert(tr)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn err1\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\ttr.AcceptUserId = value.UserId\n\t\t\t\t\t\t\texistFlag, existErr := database.Engine.Where(\"accept_user_id = ? and transfer_hash = ?\", value.UserId, tr.TransferHash).Get(tmpTr)\n\t\t\t\t\t\t\tif existErr == nil && existFlag {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar flag1 bool\n\t\t\t\t\t\tua := new(database.UserAssets)\n\t\t\t\t\t\tflag1, err = database.Engine.Where(\"user_id = ? and currency_id = ?\", value.UserId, currencyId).Get(ua)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tua.CurrencyNumber = ua.CurrencyNumber + dirNumber\n\t\t\t\t\t\terr = database.SessionSubmit(func(session *xorm.Session) (err1 error) {\n\t\t\t\t\t\t\tif flag {\n\t\t\t\t\t\t\t\t_, err1 = session.Where(\"transfer_hash = ?\", tm.Hash).Update(tr)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t_, err1 = session.Insert(tr)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif err1 == nil {\n\t\t\t\t\t\t\t\tif flag1 {\n\t\t\t\t\t\t\t\t\t_, err1 = session.Table(\"bcw_user_assets\").Where(\"user_id = ? and currency_id = ?\", value.UserId, currencyId).Update(map[string]interface{}{\"currency_number\": ua.CurrencyNumber})\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tua.CurrencyId = int64(currencyId)\n\t\t\t\t\t\t\t\t\tua.UserId = value.UserId\n\t\t\t\t\t\t\t\t\tua.CurrencyNumber = dirNumber\n\t\t\t\t\t\t\t\t\t_, err1 = session.Insert(ua)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err1\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tuInfos := make([]database.UserInfo, 0)\n\t\t\t\t\t\t\tvar err2 error\n\t\t\t\t\t\t\tif value.CurrencyAddress == tr.SendAddress {\n\n\t\t\t\t\t\t\t\terr2 = database.Engine.Where(\"id = ?\", tr.SendUserId).Find(&uInfos)\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\terr2 = database.Engine.Where(\"id = ?\", tr.AcceptUserId).Find(&uInfos)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif err2 == nil {\n\t\t\t\t\t\t\t\tfor _, tmpInfo := range uInfos {\n\t\t\t\t\t\t\t\t\tvar uNotify database.UserNotify\n\t\t\t\t\t\t\t\t\tvar tmpStr string\n\t\t\t\t\t\t\t\t\tif value.CurrencyAddress == tr.SendAddress {\n\n\t\t\t\t\t\t\t\t\t\ttmpStr = \"\" + big.NewFloat(tr.TransferNumber).String() + \"\" + tr.CurrencyName + \"\"\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\ttmpStr = \"\" + big.NewFloat(tr.TransferNumber).String() + \"\" + tr.CurrencyName + \"\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tuNotify.NotifyContent = tmpStr\n\t\t\t\t\t\t\t\t\tuNotify.NotifyReadFlag = 0\n\t\t\t\t\t\t\t\t\tuNotify.NotifyTitle = \"\"\n\t\t\t\t\t\t\t\t\tuNotify.NotifyUrl = \"\"\n\t\t\t\t\t\t\t\t\tuNotify.UserId = tmpInfo.Id\n\t\t\t\t\t\t\t\t\tdatabase.SessionSubmit(func(session *xorm.Session) (err1 error) {\n\t\t\t\t\t\t\t\t\t\t_, err1 = session.Insert(uNotify)\n\t\t\t\t\t\t\t\t\t\treturn err1\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tif tmpInfo.PushId != \"\" {\n\t\t\t\t\t\t\t\t\t\tjpushclient.SendJPush(tmpStr, tmpInfo.PushId, tmpInfo.MachineType)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (sc Funcs) TransferAccountToChain(ctx wasmlib.ScFuncClientContext) *TransferAccountToChainCall {\n\tf := &TransferAccountToChainCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferAccountToChain)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView)\n\treturn f\n}", "func (db *IndexerDb) processAccount(account *generated.Account) {\n\tif !db.hasTotalRewardsSupport() {\n\t\taccount.Rewards = 0\n\t}\n}", "func UnmarshalAccount(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(Account)\n\terr = core.UnmarshalPrimitive(m, \"url\", &obj.URL)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"id\", &obj.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"crn\", &obj.CRN)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"parent\", &obj.Parent)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_account_id\", &obj.EnterpriseAccountID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_id\", &obj.EnterpriseID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_path\", &obj.EnterprisePath)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"name\", &obj.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"state\", &obj.State)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"owner_iam_id\", &obj.OwnerIamID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"paid\", &obj.Paid)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"owner_email\", &obj.OwnerEmail)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"is_enterprise_account\", &obj.IsEnterpriseAccount)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_at\", &obj.CreatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_by\", &obj.CreatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_at\", &obj.UpdatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_by\", &obj.UpdatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (acc *BaseAccount) Convert() interface{} {\n\t// error don't use it\n\treturn nil\n}", "func (s *PostgresWalletStorage) StoreAccount(account *Account) error {\n\tmarshaledMetainfo, err := json.Marshal(account.Metainfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = s.db.Exec(\n\t\t`INSERT INTO accounts (address, metainfo) VALUES ($1, $2)`,\n\t\taccount.Address,\n\t\tmarshaledMetainfo,\n\t)\n\treturn err\n}", "func (oc *contractTransmitter) FromAccount() (ocrtypes.Account, error) {\n\treturn ocrtypes.Account(oc.transmitter.FromAddress().String()), nil\n}", "func mapRowsToUserAccount(rows *sql.Rows) (*UserAccount, error) {\n\tvar (\n\t\tua UserAccount\n\t\terr error\n\t)\n\terr = rows.Scan(&ua.UserID, &ua.AccountID, &ua.Roles, &ua.Status, &ua.CreatedAt, &ua.UpdatedAt, &ua.ArchivedAt)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\treturn &ua, nil\n}", "func (s *Service) ExportAccountHistory(accountID int64) ([]types.Payment, error) {\n\taccount, err := s.FindAccountByID(accountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar payments []types.Payment\n\n\tfor _, payment := range s.payments {\n\t\tif payment.AccountID == account.ID {\n\t\t\tdata := types.Payment{\n\t\t\t\tID: payment.ID,\n\t\t\t\tAccountID: payment.AccountID,\n\t\t\t\tAmount: payment.Amount,\n\t\t\t\tCategory: payment.Category,\n\t\t\t\tStatus: payment.Status,\n\t\t\t}\n\t\t\tpayments = append(payments, data)\n\t\t}\n\t}\n\treturn payments, nil\n}", "func (e *copyS2SMigrationBlobEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azblob.ServiceURL, destBaseURL url.URL,\n\tcontainerPrefix, blobPrefix, blobNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateContainersInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tcontainerPrefix,\n\t\tfunc(containerItem azblob.ContainerItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append container name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(containerItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match container names in account:\n\t\t\t// a. https://<blobservice>/container*/blob*.vhd\n\t\t\t// b. https://<blobservice>/ which equals to https://<blobservice>/*\n\t\t\treturn e.addTransfersFromContainer(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewContainerURL(containerItem.Name),\n\t\t\t\ttmpDestURL,\n\t\t\t\tblobPrefix,\n\t\t\t\tblobNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func Transfertobankaccount(v float64) predicate.Bulk {\n\treturn predicate.Bulk(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldTransfertobankaccount), v))\n\t})\n}", "func (account *DatabaseAccount) ConvertTo(hub conversion.Hub) error {\n\tdestination, ok := hub.(*v20210515s.DatabaseAccount)\n\tif !ok {\n\t\treturn fmt.Errorf(\"expected documentdb/v1api20210515storage/DatabaseAccount but received %T instead\", hub)\n\t}\n\n\treturn account.AssignProperties_To_DatabaseAccount(destination)\n}", "func AddressToAccountId(address string) (result xdr.AccountId, err error) {\n\n\tbytes, err := strkey.Decode(strkey.VersionByteAccountID, address)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar raw xdr.Uint256\n\tcopy(raw[:], bytes)\n\tpk, err := xdr.NewPublicKey(xdr.CryptoKeyTypeKeyTypeEd25519, raw)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = xdr.AccountId(pk)\n\n\treturn\n}", "func AchAccount() string {\n\treturn Numerify(\"############\")\n}", "func AddressToMuxedAccount(address string) (MuxedAccount, error) {\n\tresult := MuxedAccount{}\n\terr := result.SetAddress(address)\n\n\treturn result, err\n}", "func DecodeAccount(na ipld.NodeAssembler, header types.StateAccount) error {\n\tma, err := na.BeginMap(15)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, upFunc := range requiredUnpackFuncs {\n\t\tif err := upFunc(ma, header); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid DAG-ETH Account binary (%v)\", err)\n\t\t}\n\t}\n\treturn ma.Finish()\n}", "func (ds *DiskSyncer) ExportAccount(a *Account, dir string) error {\n\terr := make(chan error)\n\ter := &exportRequest{\n\t\tdir: dir,\n\t\ta: a,\n\t\terr: err,\n\t}\n\tds.exportAccount <- er\n\treturn <-err\n}", "func (txState *TxState) QueryTxsByAccount(account string, start, offset int64) Transactions {\n\n\tvar txs Transactions\n\t// id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num, block_num, sign\n\tsqlStr := \"select id, sender, receiver, amount, input, expired, time_stamp, nonce, ref_block_num from transaction_records where sender=? or receiver=? limit ?, ?;\"\n\trows, err := txState.db.Queryx(sqlStr, account, account, start, offset)\n\tif err != nil {\n\t\ttxState.log.Error(\"query txs by account failed\", \"err\", err.Error())\n\t\treturn txs\n\t}\n\n\tfor rows.Next() {\n\t\tvar tmp Transaction\n\t\trows.Scan(&tmp.ID, &tmp.Sender, &tmp.Receiver, &tmp.Value, &tmp.Input, &tmp.ExpiredNum, &tmp.TimeStamp, &tmp.Nonce, &tmp.RefBlockNum)\n\t\ttxs = append(txs, &tmp)\n\t}\n\treturn txs\n}", "func (st *Account) ToProto() *accountpb.Account {\n\tacPb := &accountpb.Account{}\n\tacPb.Nonce = st.nonce\n\tif _, ok := accountpb.AccountType_name[st.accountType]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tacPb.Type = accountpb.AccountType(st.accountType)\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.String()\n\t}\n\tacPb.Root = make([]byte, len(st.Root))\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.isCandidate\n\tif st.votingWeight != nil {\n\t\tacPb.VotingWeight = st.votingWeight.Bytes()\n\t}\n\treturn acPb\n}", "func (ga *GenesisAccount) ToUserAccount() (acc *UserAccount, err error) {\n\treturn &UserAccount{\n\t\tId: ga.Id,\n\t\tBaseAccount: auth.BaseAccount{\n\t\t\tAddress: ga.Address,\n\t\t\tCoins: ga.Coins.Sort(),\n\t\t},\n\t}, nil\n}", "func convertTx(ethTx *ethtypes.Transaction) *types.Transaction {\n\ttx := &types.Transaction{}\n\ttx.ContractCreation = ethTx.CreatesContract()\n\ttx.Gas = ethTx.Gas.String()\n\ttx.GasCost = ethTx.GasPrice.String()\n\ttx.Hash = hex.EncodeToString(ethTx.Hash())\n\ttx.Nonce = fmt.Sprintf(\"%d\", ethTx.Nonce)\n\ttx.Recipient = hex.EncodeToString(ethTx.Recipient)\n\ttx.Sender = hex.EncodeToString(ethTx.Sender())\n\ttx.Value = ethTx.Value.String()\n\treturn tx\n}", "func (o AnomalySubscriptionOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AnomalySubscription) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}", "func AccountActivity(c *gin.Context) {\n\tvar (\n\t\treqPayload model.AccountActivityReq\n\t\tdata interface{}\n\t\terr error\n\t)\n\tif reqPayload, err = util.VAccountActivity(c); err == nil {\n\t\tdata, err = util.PAccountActivity(reqPayload)\n\t}\n\tlib.GinResponse(c, data, err)\n}", "func (am *analysisMapper) toDTO(ent entity.AnalysisResults) analysisDTO {\n\treturn analysisDTO{\n\t\tID: ent.ID.String(),\n\t\tCreatedAt: ent.DateCreated,\n\t\tProjectID: ent.ProjectID.String(),\n\t\tProjectRef: ent.ProjectName,\n\t\tMiners: ent.PipelineMiners,\n\t\tSplitters: ent.PipelineSplitters,\n\t\tExpanders: ent.PipelineExpanders,\n\t\tFiles: summarizerDTO{\n\t\t\tTotal: int32(ent.FilesTotal),\n\t\t\tValid: int32(ent.FilesValid),\n\t\t\tFailed: int32(ent.FilesError),\n\t\t\tErrorSamples: ent.FilesErrorSamples,\n\t\t},\n\t\tIdentifiers: summarizerDTO{\n\t\t\tTotal: int32(ent.IdentifiersTotal),\n\t\t\tValid: int32(ent.IdentifiersValid),\n\t\t\tFailed: int32(ent.IdentifiersError),\n\t\t\tErrorSamples: ent.IdentifiersErrorSamples,\n\t\t},\n\t}\n}", "func SaveAccountTransaction(validators []*schema.Validator, transactions []*schema.Transaction) {\n\n\tfor _, tx := range transactions {\n\t\tvar listAccountAddress = getListAccountAddres(tx.Messages)\n\t\tfor _, address := range listAccountAddress {\n\t\t\torm.Save(document.CollectionAccountTransaction, &document.AccountTransaction{\n\t\t\t\tHeight: tx.Height,\n\t\t\t\tAccountAddr: address,\n\t\t\t\tTxHash: tx.TxHash,\n\t\t\t})\n\t\t}\n\t}\n}", "func parseAccount(s *goquery.Selection) (*Account, error) {\n\ttitle := s.Find(\".col.span_6_of_12\").Text()\n\tcurrency := s.Find(\".col.span_2_of_12\").Text()\n\n\tattr, exists := s.Find(\".col.span_3_of_12 a\").Eq(0).Attr(\"onclick\")\n\tif !exists {\n\t\treturn nil, errors.New(\"Account id attr not found.\")\n\t}\n\n\tid, err := parseID(attr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tacc := &Account{\n\t\tID: id,\n\t\tTitle: cleanString(title),\n\t\tCurrency: cleanString(currency),\n\t}\n\treturn acc, nil\n}", "func CreateAccount(info *Account) (*Account, error){\n\tgate := data.NewGateway()\n\tdto := info.ToDto()\n\tif acc, err := gate.Create(dto); err != nil {\n\t\tlog.Printf(err.Error())\n\t\treturn nil, err\n\t}else {\n\t\treturn NewAccountFromDto(acc), nil\n\t}\n}", "func Account(cluster string, tier toolchainv1alpha1.NSTemplateTier, modifiers ...UaInMurModifier) MurModifier {\n\treturn func(mur *toolchainv1alpha1.MasterUserRecord) error {\n\t\tmur.Spec.UserAccounts = []toolchainv1alpha1.UserAccountEmbedded{}\n\t\treturn AdditionalAccount(cluster, tier, modifiers...)(mur)\n\t}\n}", "func Account(client *ticketmatic.Client) (*ticketmatic.AccountInfo, error) {\n\tr := client.NewRequest(\"GET\", \"/{accountname}/tools/account\", \"json\")\n\n\tvar obj *ticketmatic.AccountInfo\n\terr := r.Run(&obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func (account *DatabaseAccount) ConvertFrom(hub conversion.Hub) error {\n\tsource, ok := hub.(*v20210515s.DatabaseAccount)\n\tif !ok {\n\t\treturn fmt.Errorf(\"expected documentdb/v1api20210515storage/DatabaseAccount but received %T instead\", hub)\n\t}\n\n\treturn account.AssignProperties_From_DatabaseAccount(source)\n}", "func (o *ResolveBatchParams) SetAccount(account *string) {\n\to.Account = account\n}", "func (repo *Repository) Archive(ctx context.Context, claims auth.Claims, req UserAccountArchiveRequest, now time.Time) error {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Archive\")\n\tdefer span.Finish()\n\n\t// Validate the request.\n\tv := webcontext.Validator()\n\terr := v.Struct(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure the claims can modify the user specified in the request.\n\terr = repo.CanModifyAccount(ctx, claims, req.AccountID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If now empty set it to the current time.\n\tif now.IsZero() {\n\t\tnow = time.Now()\n\t}\n\n\t// Always store the time as UTC.\n\tnow = now.UTC()\n\n\t// Postgres truncates times to milliseconds when storing. We and do the same\n\t// here so the value we return is consistent with what we store.\n\tnow = now.Truncate(time.Millisecond)\n\n\t// Build the update SQL statement.\n\tquery := sqlbuilder.NewUpdateBuilder()\n\tquery.Update(userAccountTableName)\n\tquery.Set(query.Assign(\"archived_at\", now))\n\tquery.Where(query.And(\n\t\tquery.Equal(\"user_id\", req.UserID),\n\t\tquery.Equal(\"account_id\", req.AccountID),\n\t))\n\n\t// Execute the query with the provided context.\n\tsql, args := query.Build()\n\tsql = repo.DbConn.Rebind(sql)\n\t_, err = repo.DbConn.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\terr = errors.WithMessagef(err, \"archive account %s from user %s failed\", req.AccountID, req.UserID)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (b *MemBridge) PushAccount(acc *types.Account) error {\n\t// we need valid account\n\tif nil == acc {\n\t\treturn fmt.Errorf(\"invalid or nil account can not be pushed to the in-memory cache\")\n\t}\n\n\t// encode account\n\tdata, err := acc.Marshal()\n\tif err != nil {\n\t\tb.log.Criticalf(\"can not marshal account to JSON; %s\", err.Error())\n\t\treturn err\n\t}\n\n\t// set the data to cache\n\treturn b.cache.Set(accountId(&acc.Address), data)\n}", "func (m *manager) migrateStorageAccounts(ctx context.Context) error {\n\tresourceGroup := stringutils.LastTokenByte(m.doc.OpenShiftCluster.Properties.ClusterProfile.ResourceGroupID, '/')\n\tif len(m.doc.OpenShiftCluster.Properties.WorkerProfiles) == 0 {\n\t\tm.log.Error(\"skipping migrateStorageAccounts due to missing WorkerProfiles.\")\n\t\treturn nil\n\t}\n\tclusterStorageAccountName := \"cluster\" + m.doc.OpenShiftCluster.Properties.StorageSuffix\n\tregistryStorageAccountName := m.doc.OpenShiftCluster.Properties.ImageRegistryStorageAccountName\n\n\tt := &arm.Template{\n\t\tSchema: \"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\",\n\t\tContentVersion: \"1.0.0.0\",\n\t\tResources: []*arm.Resource{\n\t\t\tm.storageAccount(clusterStorageAccountName, m.doc.OpenShiftCluster.Location, false),\n\t\t\tm.storageAccount(registryStorageAccountName, m.doc.OpenShiftCluster.Location, false),\n\t\t},\n\t}\n\n\treturn arm.DeployTemplate(ctx, m.log, m.deployments, resourceGroup, \"storage\", t, nil)\n}", "func (am *analysisMapper) toEntity(dto analysisDTO) entity.AnalysisResults {\n\treturn entity.AnalysisResults{\n\t\tID: uuid.MustParse(dto.ID),\n\t\tDateCreated: dto.CreatedAt,\n\t\tProjectName: dto.ProjectRef,\n\t\tProjectID: uuid.MustParse(dto.ProjectID),\n\t\tPipelineMiners: dto.Miners,\n\t\tPipelineSplitters: dto.Splitters,\n\t\tPipelineExpanders: dto.Expanders,\n\t\tFilesTotal: int(dto.Files.Total),\n\t\tFilesValid: int(dto.Files.Valid),\n\t\tFilesError: int(dto.Files.Failed),\n\t\tFilesErrorSamples: dto.Files.ErrorSamples,\n\t\tIdentifiersTotal: int(dto.Identifiers.Total),\n\t\tIdentifiersValid: int(dto.Identifiers.Valid),\n\t\tIdentifiersError: int(dto.Identifiers.Failed),\n\t\tIdentifiersErrorSamples: dto.Identifiers.ErrorSamples,\n\t}\n}", "func (o OneDashboardJsonOutput) AccountId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *OneDashboardJson) pulumi.IntOutput { return v.AccountId }).(pulumi.IntOutput)\n}", "func queryAccount(ctx sdk.Context, req abci.RequestQuery, keeper AccountKeeper) ([]byte, error) {\n\tvar params types.QueryAccountParams\n\tif err := keeper.cdc.UnmarshalJSON(req.Data, &params); err != nil {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())\n\t}\n\n\taccount := keeper.GetAccount(ctx, params.Id)\n\tif account == nil {\n\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"account %s does not exist\", params.Id)\n\t}\n\n\tbz, err := codec.MarshalJSONIndent(keeper.cdc, account)\n\tif err != nil {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())\n\t}\n\n\treturn bz, nil\n}", "func (c *Client) Account(account string) (*response.Account, error) {\n\tvar data *d3.Account\n\n\tep := endpointAccount(c.region, account)\n\n\tq, err := c.get(ep, &data)\n\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn &response.Account{\n\t\tData: data,\n\t\tEndpoint: ep,\n\t\tQuota: q,\n\t\tRegion: c.region,\n\t}, nil\n}", "func (o GetAggregateCompliancePacksPackOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAggregateCompliancePacksPack) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func (o BucketReplicationConfigRuleDestinationOutput) Account() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleDestination) *string { return v.Account }).(pulumi.StringPtrOutput)\n}", "func (ec *executionContext) field_Mutation_createAccount_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.NewAccount\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNNewAccount2githubᚗcomᚋannoyingᚑorangeᚋecpᚑapiᚋgraphᚋmodelᚐNewAccount(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\n}", "func (a *Funcs) Account() (string, error) {\n\ta.stsInit.Do(a.initSTS)\n\treturn a.sts.Account()\n}", "func (o AnalyzerOutput) StorageAccount() AnalyzerStorageAccountOutput {\n\treturn o.ApplyT(func(v *Analyzer) AnalyzerStorageAccountOutput { return v.StorageAccount }).(AnalyzerStorageAccountOutput)\n}", "func convertAuditInfo(ai *asset.AuditInfo, chainParams *chaincfg.Params) (*auditInfo, error) {\n\tif ai.Coin == nil {\n\t\treturn nil, fmt.Errorf(\"no coin\")\n\t}\n\n\top, ok := ai.Coin.(*output)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown coin type %T\", ai.Coin)\n\t}\n\n\trecip, err := stdaddr.DecodeAddress(ai.Recipient, chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &auditInfo{\n\t\toutput: op, // *output\n\t\trecipient: recip, // btcutil.Address\n\t\tcontract: ai.Contract, // []byte\n\t\tsecretHash: ai.SecretHash, // []byte\n\t\texpiration: ai.Expiration, // time.Time\n\t}, nil\n}", "func (o DelegatedAdminAccountOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DelegatedAdminAccount) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}", "func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// source tokens are from an account, so subtractAccount true and tokenSrc unbonded\n\tnewShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturn newShares, nil\n}", "func (o GetAggregateConfigRulesRuleOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAggregateConfigRulesRule) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func (c *Client) MoveAccount(ctx context.Context, params *MoveAccountInput, optFns ...func(*Options)) (*MoveAccountOutput, error) {\n\tif params == nil {\n\t\tparams = &MoveAccountInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"MoveAccount\", params, optFns, addOperationMoveAccountMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*MoveAccountOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *LogSource) SetAccount(v string) *LogSource {\n\ts.Account = &v\n\treturn s\n}", "func (inst *DeprecatedCreateMasterEdition) SetMetadataAccount(metadata ag_solanago.PublicKey) *DeprecatedCreateMasterEdition {\n\tinst.AccountMetaSlice[7] = ag_solanago.Meta(metadata)\n\treturn inst\n}", "func (c *Client) MoveAccount(ctx context.Context, params *MoveAccountInput, optFns ...func(*Options)) (*MoveAccountOutput, error) {\n\tif params == nil {\n\t\tparams = &MoveAccountInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"MoveAccount\", params, optFns, c.addOperationMoveAccountMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*MoveAccountOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (n *ns1) transformZone(ns1Zone *dns.Zone) zone {\n\treturn zone{id: ns1Zone.ID, name: ns1Zone.Zone}\n}", "func contractAccountToEVMAddress(contractAccount string) (crypto.Address, error) {\n\tcontractAccountValid := contractAccount[2:18]\n\tcontractAccountValid = contractAccountPrefixs + contractAccountValid\n\n\treturn crypto.AddressFromBytes([]byte(contractAccountValid))\n}", "func (self* userRestAPI) account(w http.ResponseWriter, r *http.Request) {\n\n\t// Read arguments\n\tband,number,err := self.extractBandAndNumber(r)\n\tif err != nil {\n\t\tlogError(err)\n\t\thttp.Error(w, fmt.Sprintf(\"\\nFailed to parse arguments '%s'\\n\",err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Retrieve history for specified traveller\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tpromises,err := self.engine.AccountAsJSON(band,number,flap.EpochTime(time.Now().Unix()))\n\tif err != nil {\n\t\tlogError(err)\n\t\thttp.Error(w, fmt.Sprintf(\"\\nFailed to retrieve account with error '%s'\\n\",err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tio.WriteString(w,promises)\n\n}", "func AccountImpl(authRegister *AuthRegister, preAccount *PreAccount) *Account {\n\treturn &Account{\n\t\tUserId: 0,\n\t\tUserName: authRegister.UserName,\n\t\tMailAddress: preAccount.MailAddress,\n\t\tPassword: util.ToCrypt(authRegister.Password),\n\t}\n}", "func (o LookupAccountTeamResultOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAccountTeamResult) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func (store *SQLStore) TransferTx(ctx context.Context, arg TransferTxParams) (TransferTxResult, error) {\n\t//create empty result \n\tvar result TransferTxResult\n\n\terr := store.execTx(ctx, func(q *Queries) error {\n\t\tvar err error \n\t\t\n\n\t\tresult.Transfer, err = q.CreateTransfer(ctx, CreateTransferParams{\n\t\t\tFromAccountID: arg.FromAccountID,\n\t\t\tToAccountID: arg.ToAccountID,\n\t\t\tAmount: arg.Amount,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\n\n\t\t// moving money out of account\n\t\tresult.FromEntry, err = q.CreateEntry(ctx, CreateEntryParams{\n\t\t\tAccountID: arg.FromAccountID,\n\t\t\tAmount: -arg.Amount,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\n\t\t// moving money into an account\n\t\tresult.ToEntry, err = q.CreateEntry(ctx, CreateEntryParams{\n\t\t\tAccountID: arg.ToAccountID,\n\t\t\tAmount: arg.Amount,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\n\t\t// make sure we always execute transactions in a standard order \n\t\tif arg.FromAccountID < arg.ToAccountID {\n\t\t\tresult.FromAccount, result.ToAccount, err = addMoney(ctx, q, arg.FromAccountID, -arg.Amount, arg.ToAccountID, arg.Amount)\n\t\t} else {\n\t\t\tresult.ToAccount, result.FromAccount, err = addMoney(ctx, q, arg.ToAccountID, arg.Amount, arg.FromAccountID, -arg.Amount)\n\n\t}\n\n\t\treturn nil\n\t})\n\n\treturn result, err\n}", "func (o ObfuscationRuleOutput) AccountId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *ObfuscationRule) pulumi.IntOutput { return v.AccountId }).(pulumi.IntOutput)\n}", "func (a anchoreClient) transform(fromType interface{}, toType interface{}) error {\n\tif err := mapstructure.Decode(fromType, toType); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to unmarshal to 'toType' type\")\n\t}\n\n\treturn nil\n}", "func (rs *Resolver) Transfer(args *struct{ ToTransfer inputs.TransferInput }) (*types.Transaction, error) {\n\t// get the source id\n\tfid, err := strconv.Atoi(string(args.ToTransfer.FromAccountId))\n\tif err != nil {\n\t\t// log the error and quit\n\t\trs.log.Errorf(\"GQL->Mutation->Transfer(): Invalid source account ID [%s]. %s\", args.ToTransfer.FromAccountId, err.Error())\n\t\treturn nil, err\n\t}\n\n\t// get the source\n\tfrom, err := rs.Db.AccountById(fid)\n\tif err != nil {\n\t\t// log the error and quit\n\t\trs.log.Errorf(\"GQL->Mutation->Transfer(): Source account not found for account id [%s]. %s\", args.ToTransfer.FromAccountId, err.Error())\n\t\treturn nil, err\n\t}\n\n\t// get the target id\n\ttid, err := strconv.Atoi(string(args.ToTransfer.ToAccountId))\n\tif err != nil {\n\t\t// log the error and quit\n\t\trs.log.Errorf(\"GQL->Mutation->Transfer(): Invalid destination account ID [%s]. %s\", args.ToTransfer.ToAccountId, err.Error())\n\t\treturn nil, err\n\t}\n\n\t// get the source\n\tto, err := rs.Db.AccountById(tid)\n\tif err != nil {\n\t\t// log the error and quit\n\t\trs.log.Errorf(\"GQL->Mutation->Transfer(): Destination account not found for account id [%s]. %s\", args.ToTransfer.ToAccountId, err.Error())\n\t\treturn nil, err\n\t}\n\n\t// log the action\n\trs.log.Debugf(\"GQL->Mutation->Transfer(): Sending %s FTM tokens [%s -> %s].\", args.ToTransfer.Amount.ToFTM(), from.Name, to.Name)\n\n\t// do the transfer\n\ttr, err := rs.Rpc.TransferTokens(from, to, args.ToTransfer.Amount)\n\tif err != nil {\n\t\t// log the action\n\t\trs.log.Errorf(\"GQL->Mutation->Transfer(): Can not send tokens. %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\t// return nothing\n\treturn types.NewTransaction(tr, rs.Repository), nil\n}", "func (o InventoryDestinationBucketOutput) AccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InventoryDestinationBucket) *string { return v.AccountId }).(pulumi.StringPtrOutput)\n}", "func (o LookupSpatialAnchorsAccountResultOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpatialAnchorsAccountResult) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func (o AdminAccountOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AdminAccount) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}", "func (o SplitTunnelOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SplitTunnel) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}", "func (o *NumbersACH) SetAccount(v string) {\n\to.Account = v\n}", "func (pg *Postgres) CreateAccount(name string, isActive bool) (*dto.Account, error) {\n\tvar id int\n\trow := pg.db.QueryRow(\"INSERT INTO account (name, isActive) VALUES ($1, $2) RETURNING id\", name, isActive)\n\n\tif err := row.Scan(&id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dto.Account{\n\t\tID: id,\n\t\tName: name,\n\t\tIsActive: isActive,\n\t}, nil\n}", "func (h *UserRepos) Account(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tdata := make(map[string]interface{})\n\tf := func() error {\n\n\t\tclaims, err := auth.ClaimsFromContext(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tacc, err := h.AccountRepo.ReadByID(ctx, claims, claims.Audience)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata[\"account\"] = acc.Response(ctx)\n\n\t\treturn nil\n\t}\n\n\tif err := f(); err != nil {\n\t\treturn web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"user-account.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func (o WorkerDomainOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerDomain) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}", "func (o GetAggregateDeliveriesDeliveryOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAggregateDeliveriesDelivery) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func (c *TransferRouter) postAccountTransaction(userID id.User, origDep *model.Depository, recDep *model.Depository, amount model.Amount, transferType model.TransferType, requestID string) (*accounts.Transaction, error) {\n\tif c.accountsClient == nil {\n\t\treturn nil, errors.New(\"accounts enabled but nil client\")\n\t}\n\n\t// Let's lookup both accounts. Either account can be \"external\" (meaning of a RoutingNumber Accounts doesn't control).\n\t// When the routing numbers don't match we can't do much verify the remote account as we likely don't have Account-level access.\n\t//\n\t// TODO(adam): What about an FI that handles multiple routing numbers? Should Accounts expose which routing numbers it currently supports?\n\treceiverAccount, err := c.accountsClient.SearchAccounts(requestID, userID, recDep)\n\tif err != nil || receiverAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s receiver depository=%s: %v\", userID, recDep.ID, err)\n\t}\n\torigAccount, err := c.accountsClient.SearchAccounts(requestID, userID, origDep)\n\tif err != nil || origAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s originator depository=%s: %v\", userID, origDep.ID, err)\n\t}\n\t// Submit the transactions to Accounts (only after can we go ahead and save off the Transfer)\n\ttransaction, err := c.accountsClient.PostTransaction(requestID, userID, createTransactionLines(origAccount, receiverAccount, amount, transferType))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating transaction for transfer user=%s: %v\", userID, err)\n\t}\n\tc.logger.Log(\"transfers\", fmt.Sprintf(\"created transaction=%s for user=%s amount=%s\", transaction.ID, userID, amount.String()))\n\treturn transaction, nil\n}", "func (o *V0037JobProperties) SetAccount(v string) {\n\to.Account = &v\n}", "func NewAccountInfo(name string, bic string, iban string, balance int32, predecessor string) *AccountInfo {\n\taccountInfo := AccountInfo{Name: name, BIC: bic, IBAN: iban, Balance: balance, Predecessor: predecessor}\n\taccountInfo.Transactions = []*Transaction{}\n\n\treturn &accountInfo\n}", "func (account *DatabaseAccount_Spec) ConvertToARM(resolved genruntime.ConvertToARMResolvedDetails) (interface{}, error) {\n\tif account == nil {\n\t\treturn nil, nil\n\t}\n\tresult := &DatabaseAccount_Spec_ARM{}\n\n\t// Set property \"Identity\":\n\tif account.Identity != nil {\n\t\tidentity_ARM, err := (*account.Identity).ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tidentity := *identity_ARM.(*ManagedServiceIdentity_ARM)\n\t\tresult.Identity = &identity\n\t}\n\n\t// Set property \"Kind\":\n\tif account.Kind != nil {\n\t\tkind := *account.Kind\n\t\tresult.Kind = &kind\n\t}\n\n\t// Set property \"Location\":\n\tif account.Location != nil {\n\t\tlocation := *account.Location\n\t\tresult.Location = &location\n\t}\n\n\t// Set property \"Name\":\n\tresult.Name = resolved.Name\n\n\t// Set property \"Properties\":\n\tif account.AnalyticalStorageConfiguration != nil ||\n\t\taccount.ApiProperties != nil ||\n\t\taccount.BackupPolicy != nil ||\n\t\taccount.Capabilities != nil ||\n\t\taccount.ConnectorOffer != nil ||\n\t\taccount.ConsistencyPolicy != nil ||\n\t\taccount.Cors != nil ||\n\t\taccount.DatabaseAccountOfferType != nil ||\n\t\taccount.DefaultIdentity != nil ||\n\t\taccount.DisableKeyBasedMetadataWriteAccess != nil ||\n\t\taccount.EnableAnalyticalStorage != nil ||\n\t\taccount.EnableAutomaticFailover != nil ||\n\t\taccount.EnableCassandraConnector != nil ||\n\t\taccount.EnableFreeTier != nil ||\n\t\taccount.EnableMultipleWriteLocations != nil ||\n\t\taccount.IpRules != nil ||\n\t\taccount.IsVirtualNetworkFilterEnabled != nil ||\n\t\taccount.KeyVaultKeyUri != nil ||\n\t\taccount.Locations != nil ||\n\t\taccount.NetworkAclBypass != nil ||\n\t\taccount.NetworkAclBypassResourceIds != nil ||\n\t\taccount.PublicNetworkAccess != nil ||\n\t\taccount.VirtualNetworkRules != nil {\n\t\tresult.Properties = &DatabaseAccountCreateUpdateProperties_ARM{}\n\t}\n\tif account.AnalyticalStorageConfiguration != nil {\n\t\tanalyticalStorageConfiguration_ARM, err := (*account.AnalyticalStorageConfiguration).ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tanalyticalStorageConfiguration := *analyticalStorageConfiguration_ARM.(*AnalyticalStorageConfiguration_ARM)\n\t\tresult.Properties.AnalyticalStorageConfiguration = &analyticalStorageConfiguration\n\t}\n\tif account.ApiProperties != nil {\n\t\tapiProperties_ARM, err := (*account.ApiProperties).ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tapiProperties := *apiProperties_ARM.(*ApiProperties_ARM)\n\t\tresult.Properties.ApiProperties = &apiProperties\n\t}\n\tif account.BackupPolicy != nil {\n\t\tbackupPolicy_ARM, err := (*account.BackupPolicy).ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbackupPolicy := *backupPolicy_ARM.(*BackupPolicy_ARM)\n\t\tresult.Properties.BackupPolicy = &backupPolicy\n\t}\n\tfor _, item := range account.Capabilities {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Properties.Capabilities = append(result.Properties.Capabilities, *item_ARM.(*Capability_ARM))\n\t}\n\tif account.ConnectorOffer != nil {\n\t\tconnectorOffer := *account.ConnectorOffer\n\t\tresult.Properties.ConnectorOffer = &connectorOffer\n\t}\n\tif account.ConsistencyPolicy != nil {\n\t\tconsistencyPolicy_ARM, err := (*account.ConsistencyPolicy).ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconsistencyPolicy := *consistencyPolicy_ARM.(*ConsistencyPolicy_ARM)\n\t\tresult.Properties.ConsistencyPolicy = &consistencyPolicy\n\t}\n\tfor _, item := range account.Cors {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Properties.Cors = append(result.Properties.Cors, *item_ARM.(*CorsPolicy_ARM))\n\t}\n\tif account.DatabaseAccountOfferType != nil {\n\t\tdatabaseAccountOfferType := *account.DatabaseAccountOfferType\n\t\tresult.Properties.DatabaseAccountOfferType = &databaseAccountOfferType\n\t}\n\tif account.DefaultIdentity != nil {\n\t\tdefaultIdentity := *account.DefaultIdentity\n\t\tresult.Properties.DefaultIdentity = &defaultIdentity\n\t}\n\tif account.DisableKeyBasedMetadataWriteAccess != nil {\n\t\tdisableKeyBasedMetadataWriteAccess := *account.DisableKeyBasedMetadataWriteAccess\n\t\tresult.Properties.DisableKeyBasedMetadataWriteAccess = &disableKeyBasedMetadataWriteAccess\n\t}\n\tif account.EnableAnalyticalStorage != nil {\n\t\tenableAnalyticalStorage := *account.EnableAnalyticalStorage\n\t\tresult.Properties.EnableAnalyticalStorage = &enableAnalyticalStorage\n\t}\n\tif account.EnableAutomaticFailover != nil {\n\t\tenableAutomaticFailover := *account.EnableAutomaticFailover\n\t\tresult.Properties.EnableAutomaticFailover = &enableAutomaticFailover\n\t}\n\tif account.EnableCassandraConnector != nil {\n\t\tenableCassandraConnector := *account.EnableCassandraConnector\n\t\tresult.Properties.EnableCassandraConnector = &enableCassandraConnector\n\t}\n\tif account.EnableFreeTier != nil {\n\t\tenableFreeTier := *account.EnableFreeTier\n\t\tresult.Properties.EnableFreeTier = &enableFreeTier\n\t}\n\tif account.EnableMultipleWriteLocations != nil {\n\t\tenableMultipleWriteLocations := *account.EnableMultipleWriteLocations\n\t\tresult.Properties.EnableMultipleWriteLocations = &enableMultipleWriteLocations\n\t}\n\tfor _, item := range account.IpRules {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Properties.IpRules = append(result.Properties.IpRules, *item_ARM.(*IpAddressOrRange_ARM))\n\t}\n\tif account.IsVirtualNetworkFilterEnabled != nil {\n\t\tisVirtualNetworkFilterEnabled := *account.IsVirtualNetworkFilterEnabled\n\t\tresult.Properties.IsVirtualNetworkFilterEnabled = &isVirtualNetworkFilterEnabled\n\t}\n\tif account.KeyVaultKeyUri != nil {\n\t\tkeyVaultKeyUri := *account.KeyVaultKeyUri\n\t\tresult.Properties.KeyVaultKeyUri = &keyVaultKeyUri\n\t}\n\tfor _, item := range account.Locations {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Properties.Locations = append(result.Properties.Locations, *item_ARM.(*Location_ARM))\n\t}\n\tif account.NetworkAclBypass != nil {\n\t\tnetworkAclBypass := *account.NetworkAclBypass\n\t\tresult.Properties.NetworkAclBypass = &networkAclBypass\n\t}\n\tfor _, item := range account.NetworkAclBypassResourceIds {\n\t\tresult.Properties.NetworkAclBypassResourceIds = append(result.Properties.NetworkAclBypassResourceIds, item)\n\t}\n\tif account.PublicNetworkAccess != nil {\n\t\tpublicNetworkAccess := *account.PublicNetworkAccess\n\t\tresult.Properties.PublicNetworkAccess = &publicNetworkAccess\n\t}\n\tfor _, item := range account.VirtualNetworkRules {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Properties.VirtualNetworkRules = append(result.Properties.VirtualNetworkRules, *item_ARM.(*VirtualNetworkRule_ARM))\n\t}\n\n\t// Set property \"Tags\":\n\tif account.Tags != nil {\n\t\tresult.Tags = make(map[string]string, len(account.Tags))\n\t\tfor key, value := range account.Tags {\n\t\t\tresult.Tags[key] = value\n\t\t}\n\t}\n\treturn result, nil\n}", "func (acc *Account) Encode() *accountstore.Account {\n\treturn &accountstore.Account{\n\t\tInstagramUsername: acc.InstagramUsername,\n\t\tInstagramId: acc.InstagramID,\n\t\tOwnerId: acc.OwnerID,\n\t\tCookie: acc.Cookie,\n\t\tValid: acc.Valid,\n\t\tRole: acc.Role,\n\t\tCreatedAt: acc.CreatedAt.Unix(),\n\t\tCreatedAtAgo: uint64(time.Since(acc.CreatedAt).Seconds()),\n\t}\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func GetAccountInfoFrom(bic string, iban string, from time.Time) (*model.AccountInfo, error) {\n\tpath := fmt.Sprintf(\"%s/%s/%s\",\n\t\tconfig.Configuration.Seaweed.AccountFolder,\n\t\tbic,\n\t\tiban)\n\n\tvar accountInfo *model.AccountInfo\n\tdirectory, err := filer.ReadDirectory(path, from.UTC().Format(time.RFC3339Nano))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// No files found after given time\n\tif len(directory.Files) == 0 {\n\t\taccountInfo, err = GetLatestAccountInfo(bic, iban)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttransactionAfterFrom := accountInfo.GetTransactionsAfter(from)\n\t\treturn model.NewAccountInfo(accountInfo.Name, bic, iban, accountInfo.Balance, transactionAfterFrom), nil\n\t}\n\n\taccountInfos, err := getAllAccountInfoFromDirectory(directory)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpredecessorAccountInfo, err := GetAccountInfo(bic, iban, accountInfos[0].Predecessor)\n\tif err != nil && err != ErrEmptyID {\n\t\treturn nil, err\n\t} else if err == ErrEmptyID {\n\t\taccountInfo = createAccountInfoFromListOfAccountInfos(accountInfos, from, time.Time{})\n\n\t\treturn accountInfo, nil\n\t}\n\n\taccountInfos = append([]*model.AccountInfo{predecessorAccountInfo}, accountInfos...)\n\taccountInfo = createAccountInfoFromListOfAccountInfos(accountInfos, from, time.Time{})\n\n\treturn accountInfo, nil\n}", "func (o AggregatorAggregatorAccountOutput) AccountType() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AggregatorAggregatorAccount) string { return v.AccountType }).(pulumi.StringOutput)\n}", "func (inst *DeprecatedCreateMasterEdition) SetRentInfoAccount(rentInfo ag_solanago.PublicKey) *DeprecatedCreateMasterEdition {\n\tinst.AccountMetaSlice[11] = ag_solanago.Meta(rentInfo)\n\treturn inst\n}", "func (o GetRulesRuleOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRule) string { return v.AccountId }).(pulumi.StringOutput)\n}", "func NewAccount(id string) esfazz.Aggregate {\n\tacc := AccountModel()\n\tacc.Id = id\n\treturn acc\n}", "func (s *DataLakeSource) SetAccount(v string) *DataLakeSource {\n\ts.Account = &v\n\treturn s\n}", "func (c *Client) Account(filter *models.JAccount) (*models.JAccount, error) {\n\tc.init()\n\n\tif filter.ID != \"\" {\n\t\tif account, ok := c.accounts[filter.ID]; ok {\n\t\t\treturn account, nil\n\t\t}\n\t}\n\n\tparams := &account.PostRemoteAPIJAccountOneParams{\n\t\tBody: filter,\n\t}\n\n\tparams.SetTimeout(c.timeout())\n\n\tresp, err := c.client().JAccount.PostRemoteAPIJAccountOne(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar account models.JAccount\n\n\tif err := remoteapi.Unmarshal(resp.Payload, &account); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.accounts[account.ID] = &account\n\n\treturn &account, nil\n}", "func (o *ContentProviderReadDetailed) SetAccount(v string) {\n\to.Account = v\n}", "func (h *HUOBI) AccountTransferData(ctx context.Context, code currency.Pair, subUID, transferType string, amount float64) (InternalAccountTransferData, error) {\n\tvar resp InternalAccountTransferData\n\treq := make(map[string]interface{})\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treq[\"contract_code\"] = codeValue\n\treq[\"subUid\"] = subUID\n\treq[\"amount\"] = amount\n\tif !common.StringDataCompareInsensitive(validTransferType, transferType) {\n\t\treturn resp, fmt.Errorf(\"invalid transferType received\")\n\t}\n\treq[\"type\"] = transferType\n\treturn resp, h.FuturesAuthenticatedHTTPRequest(ctx, exchange.RestFutures, http.MethodPost, huobiSwapInternalTransferData, nil, req, &resp)\n}", "func AccountFromBytes(accountBytes []byte) (*Account, error) {\n\n\t// Parse the key variant\n\tkeyVariant, keyVariantLength := util.FromVarint64(accountBytes)\n\n\t// Check key type\n\tif 0 == keyVariantLength || keyVariant&publicKeyCode != publicKeyCode {\n\t\treturn nil, fault.NotPublicKey\n\t}\n\n\t// compute algorithm\n\tkeyAlgorithm := keyVariant >> algorithmShift\n\tif keyAlgorithm >= algorithmLimit {\n\t\treturn nil, fault.InvalidKeyType\n\t}\n\n\t// network selection\n\tisTest := 0 != keyVariant&testKeyCode\n\n\t// Compute key length\n\tkeyLength := len(accountBytes) - keyVariantLength\n\tif keyLength <= 0 {\n\t\treturn nil, fault.InvalidKeyLength\n\t}\n\n\t// return a pointer to the specific account type\n\tswitch keyAlgorithm {\n\tcase ED25519:\n\t\tif keyLength != ed25519.PublicKeySize {\n\t\t\treturn nil, fault.InvalidKeyLength\n\t\t}\n\t\tpublicKey := accountBytes[keyVariantLength:]\n\t\taccount := &Account{\n\t\t\tAccountInterface: &ED25519Account{\n\t\t\t\tTest: isTest,\n\t\t\t\tPublicKey: publicKey,\n\t\t\t},\n\t\t}\n\t\treturn account, nil\n\tcase Nothing:\n\t\tif 2 != keyLength {\n\t\t\treturn nil, fault.InvalidKeyLength\n\t\t}\n\t\tpublicKey := accountBytes[keyVariantLength:]\n\t\taccount := &Account{\n\t\t\tAccountInterface: &NothingAccount{\n\t\t\t\tTest: isTest,\n\t\t\t\tPublicKey: publicKey,\n\t\t\t},\n\t\t}\n\t\treturn account, nil\n\tdefault:\n\t\treturn nil, fault.InvalidKeyType\n\t}\n}", "func (t *Transaction) QueryAccount() *AccountQuery {\n\treturn (&TransactionClient{config: t.config}).QueryAccount(t)\n}", "func (o CustomPagesOutput) AccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CustomPages) pulumi.StringPtrOutput { return v.AccountId }).(pulumi.StringPtrOutput)\n}", "func accountId(addr *common.Address) string {\n\tvar sb strings.Builder\n\n\t// add the prefix and actual address\n\tsb.WriteString(accountExistenceCacheIdPrefix)\n\tsb.WriteString(addr.String())\n\n\treturn sb.String()\n}", "func (o DocumentDbOutputDataSourceOutput) AccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DocumentDbOutputDataSource) *string { return v.AccountId }).(pulumi.StringPtrOutput)\n}", "func CacheAccount(c appengine.Context, acc *ds.Account) {\n\tmk := prefixAccForUID + acc.UserID\n\n\tif err := memcache.Set(c, &memcache.Item{Key: mk, Value: acc.Encode(), Expiration: cachedAccExpiration}); err != nil {\n\t\tc.Warningf(\"Failed to set %s in memcache: %v\", mk, err)\n\t}\n}", "func enrichTxn(aeroClient *aero.Client, incomingTxn *webTxn, enrichedTxn *enrichedTxn) (txnOutcome string, err error) {\n\t// read enriched data by UserID\n\tgetKey, err := aero.NewKey(namespace, setName, incomingTxn.UserID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trecord, err := aeroClient.Get(nil, getKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// marshal record.Bins in this struct and build\n\t// first build the inner array: [log(amount),v1,...v28]\n\t// using tryFloat()\n\n\tpcaValues := [inputLength]float64{}\n\n\t// store classification\n\ttxnOutcome = record.Bins[classBin].(string)\n\n\t// amount is log(amount)\n\tpcaValues[inputLength-1] = math.Log(tryFloat(record.Bins[amountBin], 0))\n\n\t// v1 through v28\n\tfor i := 0; i <= len(record.Bins)-3; i++ {\n\t\tpcaValues[i] = tryFloat(record.Bins[\"V\"+strconv.Itoa(i)], 0)\n\t}\n\n\t// next populate 2D array\n\tenrichedTxn.Inputs[0] = pcaValues\n\n\treturn txnOutcome, err\n}" ]
[ "0.6316797", "0.55070037", "0.5405292", "0.53862804", "0.5345793", "0.5311514", "0.53047794", "0.522594", "0.52171564", "0.51677674", "0.5159792", "0.50788945", "0.5050137", "0.5047248", "0.5041177", "0.49972457", "0.49734724", "0.49655464", "0.49417832", "0.4909045", "0.4907376", "0.49060714", "0.48741305", "0.48295125", "0.4812915", "0.48078772", "0.47872922", "0.47716853", "0.4769762", "0.47697532", "0.4768203", "0.4758189", "0.4755685", "0.4753657", "0.47456083", "0.47390622", "0.47353464", "0.47315508", "0.4728611", "0.47151372", "0.470876", "0.47070417", "0.4700458", "0.4699289", "0.46959072", "0.46786267", "0.466921", "0.4666364", "0.4663986", "0.46572876", "0.46156892", "0.46096975", "0.46082225", "0.45931676", "0.4589934", "0.45831683", "0.45809287", "0.45751286", "0.45719758", "0.45704323", "0.45627493", "0.45569673", "0.4550769", "0.45464072", "0.45437837", "0.4543411", "0.45418462", "0.4541009", "0.45369565", "0.45322877", "0.45317373", "0.45312297", "0.45310035", "0.45248047", "0.451839", "0.45181373", "0.45122144", "0.4512171", "0.45034778", "0.44994962", "0.44927967", "0.44900626", "0.44893467", "0.44840112", "0.44816795", "0.44808686", "0.44794762", "0.44778466", "0.44760716", "0.4475153", "0.44712603", "0.44663444", "0.44623798", "0.44611993", "0.44596288", "0.4455644", "0.44547147", "0.44542828", "0.44532108", "0.44332916" ]
0.704444
0
equal compares two string slices and determines if they are the same.
func equal(left, right []string) bool { if len(left) != len(right) { return false } for i, value := range left { if value != right[i] { return false } } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func equalStringSlice(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func equalSlice(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringSlicesEqual(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif a[k] != b[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringSlicesEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor idx, v := range a {\n\t\tif v != b[idx] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equalSlice(a, b []string) bool {\n\tif a == nil && b == nil {\n\t\treturn true\n\t}\n\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func SliceStringsEq(a []string, b []string) bool {\n\n\tvar aa []string\n\tvar bb []string\n\n\tif a == nil {\n\t\taa = make([]string, 0)\n\t} else {\n\t\taa = a\n\t}\n\n\tif b == nil {\n\t\tbb = make([]string, 0)\n\t} else {\n\t\tbb = b\n\t}\n\n\tif len(aa) != len(bb) {\n\t\treturn false\n\t}\n\n\tfor i := range aa {\n\t\tif aa[i] != bb[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func stringSlicesEqual(slice1 []string, slice2 []string) bool {\n\t// Check both nil or both not nil\n\tif slice1 == nil && slice2 == nil {\n\t\treturn true\n\t} else if slice1 == nil && slice2 != nil {\n\t\treturn false\n\t} else if slice1 != nil && slice2 == nil {\n\t\treturn false\n\t}\n\n\t// Length must be the same\n\tif len(slice1) != len(slice2) {\n\t\treturn false\n\t}\n\n\t// Contents must be the same\n\tsep := \"|||\"\n\tslices1String := strings.Join(slice1, sep)\n\tslices2String := strings.Join(slice2, sep)\n\tif slices1String != slices2String {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func TestEqStringSlice(t *testing.T) {\n\tt.Parallel()\n\tvar tests = []struct {\n\t\ta []string\n\t\tb []string\n\t\texpected bool\n\t}{\n\t\t{[]string{\"foo\", \"bar\"}, []string{\"foo\", \"bar\"}, true},\n\t\t{[]string{\"foo\", \"bar\"}, []string{\"bar\", \"foo\"}, false},\n\t\t{[]string{\"foo\", \"bar\"}, []string{\"bar\"}, false},\n\t\t{[]string{\"foo\", \"bar\"}, []string{\"\\x66\\x6f\\x6f\", \"bar\"}, true},\n\t}\n\tfor _, test := range tests {\n\t\tactual := primitives.EqSlices(&test.a, &test.b)\n\t\tassert.Equal(t, test.expected, actual, \"expected value '%v' | actual : '%v'\", test.expected, actual)\n\t}\n}", "func stringSliceEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualSlice(a, b []string) bool {\n\tsort.Strings(a)\n\tsort.Strings(b)\n\treturn reflect.DeepEqual(a, b)\n}", "func StringSliceEquals(lhs []string, rhs []string) bool {\n\tif lhs == nil && rhs == nil {\n\t\treturn true\n\t}\n\n\tif lhs == nil && rhs != nil {\n\t\treturn false\n\t}\n\n\tif lhs != nil && rhs == nil {\n\t\treturn false\n\t}\n\n\tif len(lhs) != len(rhs) {\n\t\treturn false\n\t}\n\n\tfor i := range lhs {\n\t\tif lhs[i] != rhs[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func sliceEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor _, v := range a {\n\t\tif !stringInSlice(v, b) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SliceEqualsString(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tdiff := make(map[string]int, len(x))\n\tfor _, ix := range x {\n\t\tdiff[ix]++\n\t}\n\tfor _, iy := range y {\n\t\tif _, ok := diff[iy]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tdiff[iy]--\n\t\tif diff[iy] == 0 {\n\t\t\tdelete(diff, iy)\n\t\t}\n\t}\n\n\treturn len(diff) == 0\n}", "func StringsSliceEqual(a, b []string) bool {\n\tif !sort.StringsAreSorted(a) {\n\t\tsort.Strings(a)\n\t}\n\tif !sort.StringsAreSorted(b) {\n\t\tsort.Strings(b)\n\t}\n\tfor i := range b {\n\t\tif !StringsSliceContains(a, b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i := range a {\n\t\tif !StringsSliceContains(b, a[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StrSlicesEqual(lhs, rhs []string) bool {\n\tif len(lhs) == 0 && len(rhs) == 0 {\n\t\treturn true\n\t}\n\tif len(lhs) != len(rhs) {\n\t\treturn false\n\t}\n\ttotal := make(map[string]bool, len(lhs))\n\tfor _, item := range lhs {\n\t\ttotal[item] = true\n\t}\n\tfor _, item := range rhs {\n\t\tif _, ok := total[item]; ok {\n\t\t\tdelete(total, item)\n\t\t\tcontinue\n\t\t}\n\t\ttotal[item] = true\n\t}\n\treturn len(total) == 0\n}", "func SlicesEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualsSliceOfString(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SliceStringEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\taCopy := make([]string, len(a))\n\tbCopy := make([]string, len(a))\n\tfor x, aVal := range a {\n\t\taCopy[x] = aVal\n\t\tbCopy[x] = b[x]\n\t}\n\tsort.Strings(aCopy)\n\tsort.Strings(bCopy)\n\treturn sortedStringSliceEqual(aCopy, bCopy)\n}", "func EqualSlice(dst, src []byte) bool {\n\tif len(dst) != len(src) {\n\t\treturn false\n\t}\n\tfor idx, b := range dst {\n\t\tif b != src[idx] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equalStringSliceIgnoreOrder(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tfound := false\n\n\t\tfor j := 0; j < len(b); j++ {\n\t\t\tif a[i] == b[j] {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func sortedStringSliceEqual(a, b []string) bool {\n\tfor x, aVal := range a {\n\t\tbVal := b[x]\n\t\tif aVal != bVal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(x, y []string) bool {\n if len(x) != len(y) {\n return false\n }\n for i := range x {\n if x[i] != y[i] {\n return false\n }\n }\n return true\n}", "func Test_AreEqualSlices_one_shorter(t *testing.T) {\n // create two equal slices\n a := []byte{ 0xDE, 0xAD, 0xBE, 0xEF }\n b := []byte{ 0xDE, 0xAD, 0xBE }\n //\tmake test -> log failure but continue testing\n if AreEqualSlices(a,b) { t.Error(\"different length slices determined equal\") }\n}", "func CompareStringSlices(a, b []string) bool {\n\tif (a == nil) != (b == nil) {\n\t\treturn false\n\t}\n\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func compareStringSlices(expected, actual []string) (index int, matched bool) {\n\t// compare the two slices\n\tif len(expected) != len(actual) {\n\t\treturn 0, false\n\t}\n\n\tsort.Strings(actual)\n\tsort.Strings(expected)\n\tfor index, _ := range expected {\n\t\tif expected[index] != actual[index] {\n\t\t\treturn index, false\n\t\t}\n\t}\n\treturn len(expected), true\n}", "func Equal(s1, s2 []string) bool {\n\tif len(s1) != len(s2) {\n\t\treturn false\n\t}\n\tfor _, e := range s1 {\n\t\tif !Contains(s2, e) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tfor i := range x {\n\t\tif x[i] != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tfor i := range x {\n\t\tif x[i] != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(a, b []byte) bool {\n if len(a) != len(b) {\n return false\n }\n for i :=0 ; i < len(a) ; i++ {\n if a[i] != b[i] {\n return false\n }\n }\n return true\n}", "func SliceStringPEqual(a, b []*string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tsa := make([]string, len(a))\n\tsb := make([]string, len(a))\n\tfor x, aPtr := range a {\n\t\tsa[x] = *aPtr\n\t\tsb[x] = *b[x]\n\t}\n\tsort.Strings(sa)\n\tsort.Strings(sb)\n\tfor x, aVal := range sa {\n\t\tbVal := sb[x]\n\t\tif aVal != bVal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SliceStringPEqual(a, b []*string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tsa := make([]string, len(a))\n\tsb := make([]string, len(a))\n\tfor x, aPtr := range a {\n\t\tsa[x] = *aPtr\n\t\tsb[x] = *b[x]\n\t}\n\tsort.Strings(sa)\n\tsort.Strings(sb)\n\treturn sortedStringSliceEqual(sa, sb)\n}", "func Test_AreEqualSlices_unequal(t *testing.T) {\n // create two equal slices\n a := []byte{ 0xDE, 0xAD, 0xBE, 0xEF }\n b := []byte{ 0xCA, 0xFE, 0xBA, 0xBE }\n // make test -> log failure but continue testing\n if AreEqualSlices(a,b) { t.Error(\"unequal slices determined equal\") }\n}", "func ssEqual(s1, s2 []string) bool {\n\tif len(s1) != len(s2) {\n\t\treturn false\n\t}\n\tfor x, s := range s1 {\n\t\tif s != s2[x] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tm := make(map[string]int, len(a))\n\tfor i := range a {\n\t\tm[a[i]]++\n\t\tm[b[i]]--\n\t}\n\tfor _, v := range m {\n\t\tif v != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CompareSliceStr(s1, s2 []string) bool {\n\tif len(s1) != len(s2) {\n\t\treturn false\n\t}\n\n\tfor i := range s1 {\n\t\tif s1[i] != s2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func OkEqualStringSlices(t *testing.T, found, expected []string) {\n\tif len(expected) != len(found) {\n\t\tt.Logf(\"not ok - slice Found has %d elements, while slice Expected has %d\\n\", len(found), len(expected))\n\t\tt.Logf(\"Found: %v\", found)\n\t\tt.Logf(\"Expected: %v\", expected)\n\t\tt.Fail()\n\t\treturn\n\t}\n\tfor N := 0; N < len(found); N++ {\n\t\tif found[N] == expected[N] {\n\t\t\tt.Logf(\"ok - element %d of Found and the same in Expected are equal [%v]\\n\", N, found[N])\n\t\t} else {\n\t\t\tt.Logf(\"not ok - element %d of Found differs from the corresponding one in Expected. \"+\n\t\t\t\t\"Expected '%s' - found: '%s'\\n\", N, expected[N], found[N])\n\t\t\tt.Fail()\n\t\t}\n\t}\n}", "func equalPairSlice(a, b []Pair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func StringArraysEqual(a, b []string) (ok bool) {\n\tif len(a) != len(b) {\n\t\treturn\n\t}\n\n\tsort.Strings(a)\n\tsort.Strings(b)\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn\n\t\t}\n\t}\n\treturn true\n}", "func Equal(lhs, rhs []string) (rv bool) {\n\tif len(lhs) == len(rhs) {\n\t\tfor i, s := range lhs {\n\t\t\tif s != rhs[i] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\trv = true\n\t}\n\treturn\n}", "func (p intSlice) Equal(q permutation.Sequence) bool { return reflect.DeepEqual(p, q) }", "func TestCompareStrings(t *testing.T) {\n\tstrings1 := []string{\"one\", \"two\", \"three\"}\n\tstrings2 := []string{\"one\", \"two\"}\n\tstrings3 := []string{\"one\", \"two\", \"THREE\"}\n\n\tif !compareStrings(strings1, strings1) {\n\t\tt.Error(\"Equal slices fail check!\")\n\t}\n\n\tif compareStrings(strings1, strings2) {\n\t\tt.Error(\"Different size slices are OK!\")\n\t}\n\n\tif compareStrings(strings1, strings3) {\n\t\tt.Error(\"Slice with different strings are OK!\")\n\t}\n}", "func sortedEqualEmptyStrSlice(x, y []string) bool {\n\tif len(x) == 0 || len(y) == 0 {\n\t\treturn true\n\t}\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\n\txCpy := make([]string, len(x))\n\tyCpy := make([]string, len(y))\n\tcopy(xCpy, x)\n\tcopy(yCpy, y)\n\n\tsort.Strings(xCpy)\n\tsort.Strings(yCpy)\n\n\tfor i := 0; i < len(xCpy); i++ {\n\t\tif xCpy[i] != yCpy[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func testEqualitySlicesOfPlayer(a, b []Player) bool {\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func areEqual(b []byte, s string) bool {\n if len(b) != len(s) {\n return false\n }\n\n for i, byte := range b {\n if byte != s[i] {\n return false\n }\n }\n\n return true\n}", "func SliceCompare(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tfor i := range x {\n\t\tif x[i] != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualCardSlice(a, b []Card) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualIgnoreOrder(slice1, slice2 []string) bool {\n\tif len(slice1) != len(slice2) {\n\t\treturn false\n\t}\n\n\t// sort and compare\n\ts1 := StringSlice(slice1)\n\ts2 := StringSlice(slice2)\n\tsort.Sort(s1)\n\tsort.Sort(s2)\n\tfor i, str := range s1 {\n\t\tif str != s2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func doSlicesIntersect(s1, s2 []string) bool {\n if s1 == nil || s2 == nil {\n return false\n }\n for _, str := range s1 {\n if isElementInSlice(str, s2) {\n return true\n }\n }\n return false\n}", "func EqualsSliceOfCollateAndCharset(a, b []CollateAndCharset) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsCollateAndCharset(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func eq(x, y []string) bool {\n\t// NOTE: list equal, not set equal\n\treturn strs.Equal(x, y)\n}", "func strEq(s1, s2 string) bool {\n if len(s1) != len(s2) {\n return false\n }\n\n for i := range s1 {\n if s1[i] != s2[i] {\n return false\n }\n }\n\n return true\n}", "func ArrayEqual(array1, array2 []string) bool { return Array2Set(array1).Equal(Array2Set(array2)) }", "func Strings(tst *testing.T, msg string, a, b []string) {\n\tif len(a) != len(b) {\n\t\tPrintFail(\"%s error len(%q)=%d != len(%q)=%d\\n\", msg, a, len(a), b, len(b))\n\t\ttst.Errorf(\"%s failed: slices have different lengths: %v != %v\", msg, a, b)\n\t\treturn\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tPrintFail(\"%s error %v != %v\\n\", msg, a[i], b[i])\n\t\t\ttst.Errorf(\"%s failed: slices are different: %dth comp %v != %v\\n%v != \\n%v\", msg, i, a[i], b[i], a, b)\n\t\t\treturn\n\t\t}\n\t}\n\tPrintOk(msg)\n}", "func slicesIdentical(slice1 []core.VarId, slice2 []core.VarId) bool {\n\tslice1Length := len(slice1)\n\tif slice1Length != len(slice2) {\n\t\treturn false\n\t}\n\tcountIdenticalValues := 0\n\tfor _, element1 := range slice1 {\n\t\telementIdentical := false\n\t\tfor _, element2 := range slice2 {\n\t\t\tif element1 == element2 {\n\t\t\t\tcountIdenticalValues += 1\n\t\t\t\telementIdentical = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !elementIdentical {\n\t\t\tcountIdenticalValues = 0\n\t\t}\n\t}\n\tif slice1Length == countIdenticalValues {\n\t\treturn true\n\t}\n\treturn false\n}", "func SetEqual(a, b []string) bool {\n\tsetA := make([]string, len(a))\n\tcopy(setA, a)\n\tsort.Sort(sort.StringSlice(setA))\n\n\tsetB := make([]string, len(b))\n\tcopy(setB, b)\n\tsort.Sort(sort.StringSlice(setB))\n\n\treturn StrictlyEqual(setA, setB)\n}", "func equal(a, b interface{}) bool {\n\taSlice, aOk := a.([]interface{})\n\tbSlice, bOk := b.([]interface{})\n\n\tif aOk && bOk {\n\t\t// Both are slices\n\t\treturn sliceEqual(aSlice, bSlice)\n\t}\n\n\tif aOk || bOk {\n\t\t// One of the 2 is a slice\n\t\treturn false\n\t}\n\n\t// None is a slice\n\treturn a == b\n}", "func StrictlyEqual(a, b []string) bool {\n\tif a == nil && b == nil {\n\t\treturn true\n\t} else if a == nil || b == nil {\n\t\treturn false\n\t} else if len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualSlice(a, b []float64) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif EpsilonEqual(a[0], b[0]) != true {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CompareSliceStrU(s1, s2 []string) bool {\n\tif len(s1) != len(s2) {\n\t\treturn false\n\t}\n\n\tfor i := range s1 {\n\t\tfor j := len(s2) - 1; j >= 0; j-- {\n\t\t\tif s1[i] == s2[j] {\n\t\t\t\ts2 = append(s2[:j], s2[j+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif len(s2) > 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func StringS(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (ss *StringSet) Equal(ss1 *StringSet) bool {\n\tif ss.Len() != ss1.Len() {\n\t\treturn false\n\t}\n\tfor s := range ss.set {\n\t\tif !ss1.Contain(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func eq(x, y []string) bool {\n\t// NOTE: set equal\n\treturn sset.Equal(x, y)\n}", "func equal(a []int, b []int) bool {\n\tvar length int\n\n\tif len(a) < len(b) {\n\t\tlength = len(a)\n\t} else {\n\t\tlength = len(b)\n\t}\n\n\tfor i := 0; i < length; i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SliceEquals(slice1, slice2 interface{}) (bool, error) {\n\t//Determine if both slices are of the same type.\n\t// if slice1.(type) != slice2.(type) {\n\t// \tfmt.Println(\"Types of the two slices are different!\")\n\t// \treturn false\n\t// }\n\n\toneSubsetTwo, err := SliceSubset(slice1, slice2)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"There was an issue computing SliceSubset(slice1,slice2): %v\", err)\n\t}\n\n\ttwoSubsetOne, err := SliceSubset(slice2, slice1)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"There was an issue computing SliceSubset(slice2,slice1): %v\", err)\n\t}\n\n\treturn oneSubsetTwo && twoSubsetOne, nil\n\n}", "func ByteSlicesEqual(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor idx, v := range a {\n\t\tif v != b[idx] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SameElements(a0, b0 []string) bool {\n // shallow copy input arrays\n a := append([]string(nil), a0...)\n b := append([]string(nil), b0...)\n\n if a == nil && b == nil {\n return true\n }\n if a == nil || b == nil {\n return false\n }\n if len(a) != len(b) {\n return false\n }\n\n sort.Strings(a)\n sort.Strings(b)\n for i := range a {\n if a[i] != b[i] {\n return false\n }\n }\n return true\n}", "func recordsSliceEquals(l, r []Record) bool {\n\tif len(l) != len(r) {\n\t\treturn false\n\t}\n\tfor i := range l {\n\t\tif l[i] != r[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func assertEqualTokenSlices(t *testing.T, a, e [][]byte) {\n\tif len(a) != len(e) {\n\t\tt.Errorf(\"Expected number of tokens: %d Actual: %d\", len(e), len(a))\n\t}\n\tfor i, token := range a {\n\t\tif !bytes.Equal(token, e[i]) {\n\t\t\tt.Error(\"Tokens not equal\")\n\t\t}\n\t}\n}", "func dnsNamesEqual(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tsort.Strings(a)\n\tsort.Strings(b)\n\tfor i, s := range a {\n\t\tif b[i] != s {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringSliceSubset(a []string, b []string) error {\n\taset := make(map[string]bool)\n\tfor _, v := range a {\n\t\taset[v] = true\n\t}\n\n\tfor _, v := range b {\n\t\t_, ok := aset[v]\n\t\tif !ok {\n\t\t\treturn trace.BadParameter(\"%v not in set\", v)\n\t\t}\n\n\t}\n\treturn nil\n}", "func EqualsSliceOfRefOfRenameTablePair(a, b []*RenameTablePair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsRefOfRenameTablePair(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func byteSlicesEqual(a [][]byte) bool {\n\tif len(a) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, v := range a[1:] {\n\t\tif !bytes.Equal(a[0], v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(a, b interface{}) bool {\n\tarrA := reflect.ValueOf(a)\n\tarrB := reflect.ValueOf(b)\n\n\tif arrA.Kind() != reflect.Slice {\n\t\tpanic(\"invalid data-type, occurred in sxutil package\")\n\t}\n\tif arrB.Kind() != reflect.Slice {\n\t\tpanic(\"invalid data-type, occurred in sxutil package\")\n\t}\n\n\tif arrA.Len() != arrB.Len() {\n\t\treturn false\n\t}\n\n\tm := make(map[interface{}]bool)\n\n\tfor i := 0; i < arrA.Len(); i++ {\n\t\tm[arrA.Index(i).Interface()] = true\n\t}\n\n\tfor i := 0; i < arrB.Len(); i++ {\n\t\tif _, ok := m[arrB.Index(i).Interface()]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tm = make(map[interface{}]bool)\n\n\tfor i := 0; i < arrB.Len(); i++ {\n\t\tm[arrB.Index(i).Interface()] = true\n\t}\n\n\tfor i := 0; i < arrA.Len(); i++ {\n\t\tif _, ok := m[arrA.Index(i).Interface()]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func SortedStringsEqual(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tif a == nil || b == nil {\n\t\treturn a == nil && b == nil\n\t}\n\n\tfor i, _ := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func equal(slice1, slice2 Coef) bool {\n\tfor index := range slice1 {\n\t\tif math.Abs(slice1[index]-slice2[index]) > epsilon {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func inStringSlice(ss []string, str string) bool {\n\tfor _, s := range ss {\n\t\tif strings.EqualFold(s, str) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Equal(a, b Vector) bool {\n\tpanicLength(a, b)\n\tfor i := 0; i < a.Len(); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func AssertEqualStringArray(expected []string, result []string) {\n\tAssertType(expected, result)\n\tif expected == nil && result == nil {\n\t\treturn\n\t}\n\tif len(expected) != len(result) {\n\t\tpanic(fmt.Sprintf(\"Error: [] Different count of items\\nExpected Value: %v\\nResult: %v\", expected, result))\n\t}\n\tfor expectedIdx := range expected {\n\t\telementExists := false\n\t\tfor resultIdx := range result {\n\t\t\tif result[resultIdx] == expected[expectedIdx] {\n\t\t\t\telementExists = true\n\t\t\t}\n\t\t}\n\t\tif !elementExists {\n\t\t\tpanic(fmt.Sprintf(\"Error: [] Item missing: %v.\\nExpected Value: %v\\nResult: %v\", expected[expectedIdx], expected, result))\n\t\t}\n\t}\n}", "func (ids IDSlice) Equal(o IDSlice) bool {\n\tif len(ids) != len(o) {\n\t\treturn false\n\t}\n\tfor idx, id := range ids {\n\t\tif o[idx] != id {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(s1, s2 Set) bool {\n\tif Same(s1, s2) {\n\t\treturn true\n\t}\n\n\tif len(s1) != len(s2) {\n\t\treturn false\n\t}\n\n\tfor e := range s1 {\n\t\tif _, ok := s2[e]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func ArrayEquals(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tvar found bool\n\tfor i := range a {\n\t\tfound = false\n\t\tfor j := range b {\n\t\t\tif a[i] == b[j] {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func stringSliceOverlaps(left []string, right []string) bool {\n\tfor _, s := range left {\n\t\tfor _, t := range right {\n\t\t\tif s == t {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func main(){\n // declare and initialise a string array\n // month[1] - January\n // month[12] - December\n // month[0] - \"\" (zero value for string)\n months := [...]string{1: \"January\",\n 2: \"February\",\n 3: \"March\",\n 4: \"April\",\n 5: \"May\",\n 6: \"June\",\n 7: \"July\",\n 8: \"August\",\n 9: \"September\",\n 10: \"October\",\n 11: \"November\",\n 12: \"December\"}\n\n // built-ins len and cap return length and capacity of slices\n // s[i:j] creates a new slice that refers to elements of sequence s from i to j-1\n // if i is omitted, i = 0\n // if j is omitted, j = len(s)\n fmt.Println(months[1:]) // [Januaray ... December]\n fmt.Println(months[1:13]) // [Januaray ... December]\n\n // define two slices for quarter-2 and summer\n Q2 := months[4:7]\n summer := months[6:9]\n fmt.Println(Q2)\n fmt.Println(summer)\n fmt.Printf(\"Capacity of Q2 %d\\n\", cap(Q2)) // 9 - capacity is from start of slice to end of array\n fmt.Printf(\"Capacity of summer %d\\n\", cap(summer)) // 7\n\n // iterate slices and check of common elements\n for _, s := range summer {\n for _, q := range Q2 {\n if s == q {\n fmt.Printf(\"%s appears in both\\n\", s)\n }\n }\n }\n // slicing beyond cap(s) causes panic\n // fmt.Println(summer[:20]) // panic: out of range\n // slicing beyond len(s) extends the slice\n\n // even though len(summer) is 3, this works.\n endlessSummer := summer[:5] // extend a slice (within capacity)\n fmt.Println(endlessSummer) // \"[June July August September October]\"\n\n\n //unlike arrays, slices are not comparable using \"==\" \n fmt.Println(equal(Q2, summer)) // false\n // however, this \"deep equivalance\" is not always practical \n // for e.g a slice could contain itself\n // s := []interface{}{\"one\", nil}\n // s[1] = s\n // s2 := s[1].([]interface{})\n // s3 := s2[1].([]interface{})\n // No matter how deep we go, the 2nd element will always be the slice value pointing to the same array as s, wrapped in an interface{} value.\n\n // slice elements are indirect\n // The only legal slice comparison is against nil\n\n if summer == nil {\n fmt.Println(\"summer is nil\")\n }\n\n // zero value of slice is nil\n // - nil slice has no underlying array\n // - slice of of lenght and capacity 0 are could still be non-nil slice\n // []int{} or make([]int, 3)[3:] are no-nil slices with len and cap 0 \n\n // to test if slice is empty, use len and not nil to compare\n var s []int \n fmt.Printf(\"len(s) - %d, s == nil - %t\\n\",len(s), s == nil) // len(s) - s == nil - true\n s = nil \n fmt.Printf(\"len(s) - %d, s == nil - %t\\n\",len(s), s == nil) // len(s) - s == nil - true\n s = []int(nil)\n fmt.Printf(\"len(s) - %d, s == nil - %t\\n\",len(s), s == nil) // len(s) - s == nil - true\n s = []int{}\n fmt.Printf(\"len(s) - %d, s == nil - %t\\n\",len(s), s == nil) // len(s) - s == nil - false\n\n // built-in function make can be used to create slices of a specified type, len and cap\n // make([]T, len)\n // make([]T, len, cap) //same as make([]T, cap)[:len]\n make_s := make([]int, 3)\n fmt.Printf(\"slice of type %T. len(make_s) - %d , cap(make_s) - %d\\n\", make_s, len(make_s), cap(make_s)) // slice of type []int. len(make_s) - 3 , cap(make_s) - 3\n // len as to be smaller than capacity\n make_s2 := make([]int, 3 , 6)\n fmt.Printf(\"slice of type %T. len(make_s2) - %d , cap(make_s2) - %d\\n\", make_s2, len(make_s2), cap(make_s2)) // slice of type []int. len(make_s2) - 3 , cap(make_s2) - 3\n\n\n // built-in append function appends items to slices\n // the below code is equivalent declaring and initializing a slice\n // var runes []rune(\"Hello, 世界\") .\n // it demonstrates use of append to build a slice of nine runes\n\n // declare an empty rune\n var runes []rune\n for _, r := range \"Hello, 世界\" {\n //iteratively append elements to rune\n // since the resultant slice may or may not refer to the same underlying array\n // it is usual practice to assing the result of append to the same variable\n runes = append(runes, r)\n }\n fmt.Printf(\"%q\\n\", runes) // ['H' 'e' 'l' 'l' 'o' ',' ' ' ' B ' ' F ']\n\n // updating the variable is required for any function that changes the length or capacity of the slice\n // since this may result in refering to a different underlying array\n\n var x []int\n x = append(x,1)\n x = append(x, 2, 3)\n x = append(x, 4, 5, 6)\n // varaible followed by ellipsis does slice unpacking\n // in-build append accepts any number of final arguments\n x = append(x, x...) // append slice x\n fmt.Println(x) // [1 2 3 4 5 6 1 2 3 4 5 6]\n\n\n // slices as as stack\n var stack []int\n\n for _, v := range x {\n stack = append(stack, v) // push v\n fmt.Printf(\"Push %d, stack %d\\n\", v, stack)\n }\n\n\n for i := len(stack); i > 0 ; i-- {\n top := stack[len(stack) -1 ] // top of stack\n stack = stack[:len(stack) - 1] //shrkink stack\n fmt.Printf(\"Pop %d, stack %d\\n\", top, stack)\n }\n\n remove_test := []int{5,6,7,8,9}\n fmt.Println(remove(remove_test, 2))\n}", "func equal(x, y []int) bool {\n\tif len(x) != len(y) {\n\t\treturn false // if the length is not the same we can stop right there\n\t}\n\t// for i := range x {\n\t// \tif x[i] != y[i] {\n\t// \t\treturn false\n\t// \t}\n\t// }\n\tfor i, v := range x {\n\t\tif v != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equalFolds(s string, str ...string) bool {\n\tfor _, v := range str {\n\t\tif strings.EqualFold(s, v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func StringSlicesIntersection(a, b []string) (c []string) {\n\tm := make(map[string]bool)\n\n\tfor _, item := range a {\n\t\tm[item] = true\n\t}\n\n\tfor _, item := range b {\n\t\tif _, ok := m[item]; ok {\n\t\t\tc = append(c, item)\n\t\t}\n\t}\n\treturn\n}", "func tagArraysEqual(a []GeneratedType, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tfound := false\n\t\tfor j := 0; j < len(b); j++ {\n\t\t\tif a[i].(string) == b[j] {\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\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func compareSlices(A, B []int) bool {\n\tif len(A) != len(B) {\n\t\treturn false\n\t}\n\n\tsort.Ints(A)\n\tsort.Ints(B)\n\n\tfor i, a := range A {\n\t\tif a != B[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (s String) Equal(other String) bool {\n\tif len(s) != len(other) {\n\t\treturn false\n\t}\n\tfor key := range s {\n\t\tif !other.Contains(key) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StrEquivalent(one, two []string) bool {\n\tif len(one) != len(two) {\n\t\treturn false\n\t}\n\tfor _, v := range one {\n\t\tif StrAt(two, v) < 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func differenceStringSlice(sliceA []string, sliceB []string) []string {\n\tvar diff []string\n\n\tfor _, a := range sliceA {\n\t\tfound := false\n\t\tfor _, b := range sliceB {\n\t\t\tif a == b {\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\tdiff = append(diff, a)\n\t\t}\n\t}\n\n\treturn diff\n}", "func TestEqIntSlice(t *testing.T) {\n\tt.Parallel()\n\tvar tests = []struct {\n\t\ta []int\n\t\tb []int\n\t\texpected bool\n\t}{\n\t\t{[]int{1, 2}, []int{1, 2}, true},\n\t\t{[]int{1, 2}, []int{2, 1}, false},\n\t\t{[]int{1, 2}, []int{1}, false},\n\t\t{[]int{1, 2}, []int{1, 2, 1}, false},\n\t}\n\tfor _, test := range tests {\n\t\tactual := primitives.EqSlices(&test.a, &test.b)\n\t\tassert.Equal(t, test.expected, actual, \"expected value '%v' | actual : '%v'\", test.expected, actual)\n\t}\n}", "func StringArrayEquivalent(tb testing.TB, exp []string, act []string) {\n\tAssert(tb, len(exp) == len(act), fmt.Sprintf(\"Expected %d items, but only found %d\", len(exp), len(act)))\n\n\tfor _, expectedItem := range exp {\n\t\tthisItemMatches := false\n\t\tfor _, actualItem := range act {\n\t\t\tif strings.EqualFold(strings.TrimSpace(expectedItem), strings.TrimSpace(actualItem)) {\n\t\t\t\tthisItemMatches = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tAssert(tb, thisItemMatches, fmt.Sprintf(\"Unable to find matching actual item for expected item %s\", expectedItem))\n\t}\n}", "func EqualInt8Slice(a, b []int8) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringInSlice(a string, slice []string) bool {\n\tfor _, b := range slice {\n\t\tif a == b {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Equal(s1, s2 Set) bool {\n\tif s1.Len() != s2.Len() {\n\t\treturn false\n\t}\n\tfor k := range s1 {\n\t\tif _, ok := s2[k]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(a, b []interface{}) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringInSliceCS(a string, list []string) bool {\n\tfor _, b := range list {\n\t\tif a == b {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func compare2DSlices(A, B []int) bool {\n\tif len(A) != len(B) {\n\t\treturn false\n\t}\n\n\tif len(A) == 0 {\n\t\treturn true // empty slices is equal\n\t}\n\n\tsort.Ints(A)\n\tsort.Ints(B)\n\n\tfor i, a := range A {\n\t\tif a != B[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func OkEqualByteSlices(t *testing.T, found, expected []byte) {\n\tif len(expected) != len(found) {\n\t\tt.Logf(\"not ok - slice Found has %d elements, while slice Expected has %d\\n\", len(found), len(expected))\n\t\tt.Logf(\"Found: %v\", found)\n\t\tt.Logf(\"Expected: %v\", expected)\n\t\tt.Fail()\n\t\treturn\n\t}\n\tfor N := 0; N < len(found); N++ {\n\t\tif found[N] == expected[N] {\n\t\t\tt.Logf(\"ok - byte %d of Found and the same in Expected are equal [%x]\\n\", N, found[N])\n\t\t} else {\n\t\t\tt.Logf(\"not ok - byte %d of Found differs from the corresponding one in Expected. \"+\n\t\t\t\t\"Expected '%x' - found: '%x'\\n\", N, expected[N], found[N])\n\t\t\tt.Fail()\n\t\t}\n\t}\n}" ]
[ "0.82696867", "0.8176309", "0.8130287", "0.80586714", "0.80283535", "0.8026674", "0.802485", "0.7932646", "0.78799474", "0.7861998", "0.7798794", "0.77114105", "0.7710674", "0.765556", "0.7647003", "0.7531228", "0.75034845", "0.747733", "0.74554133", "0.7453913", "0.74116373", "0.73862183", "0.7383728", "0.73701775", "0.72917783", "0.71896166", "0.71747786", "0.71747786", "0.7168261", "0.7123306", "0.7102224", "0.70899725", "0.7071659", "0.70639896", "0.7059976", "0.70469725", "0.70455194", "0.7025865", "0.7021787", "0.6928365", "0.68949616", "0.6873936", "0.6857002", "0.68323135", "0.6806812", "0.67555565", "0.67448", "0.6726074", "0.67122334", "0.6709096", "0.6705748", "0.6700661", "0.66111267", "0.66023517", "0.66015327", "0.65954995", "0.65949774", "0.6578099", "0.6562148", "0.6539178", "0.65187484", "0.6510018", "0.64975834", "0.6496168", "0.6495975", "0.6477866", "0.64747375", "0.64728993", "0.6412638", "0.63931644", "0.6380709", "0.6361512", "0.630579", "0.6302501", "0.63021755", "0.6299885", "0.6265038", "0.62568283", "0.62383", "0.6222157", "0.6207226", "0.620613", "0.6198502", "0.619259", "0.6188849", "0.61881196", "0.6172555", "0.6143168", "0.61207503", "0.61191964", "0.6115086", "0.6098994", "0.6093604", "0.60776997", "0.60724497", "0.6068584", "0.60446", "0.60293686", "0.60206115", "0.6018881" ]
0.7105393
30
DefaultRegions returns the default regions supported by AWS NOTE: in the future this list is subject to change
func DefaultRegions() []string { return []string{ "us-east-2", "us-east-1", "us-west-1", "us-west-2", "ap-south-1", "ap-northeast-2", "ap-southeast-1", "ap-northeast-1", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1", } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetRegions() ([]Region, error) {\n\tvar regions []Region\n\tarvanConfig := config.GetConfigInfo()\n\tarvanServer := arvanConfig.GetServer()\n\thttpReq, err := http.NewRequest(\"GET\", arvanServer+apiPrefix+defaultRegion+regionsEndpoint, nil)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\thttpReq.Header.Add(\"accept\", \"application/json\")\n\thttpReq.Header.Add(\"User-Agent\", \"ar-cli\")\n\thttpResp, err := http.DefaultClient.Do(httpReq)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\t// read body\n\tdefer httpResp.Body.Close()\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\t// parse response\n\terr = json.Unmarshal(body, &regions)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\n\treturn regions, nil\n}", "func GetRegions(sess *session.Session) (*ec2.DescribeRegionsOutput, error) {\n // snippet-start:[ec2.go.regions_and_zones.regions]\n svc := ec2.New(sess)\n\n resultRegions, err := svc.DescribeRegions(nil)\n // snippet-end:[ec2.go.regions_and_zones.regions]\n if err != nil {\n return nil, err\n }\n\n return resultRegions, nil\n}", "func (o *AmazonAccountAccessKeys) GetDefaultRegion() RegionTypes {\n\tif o == nil || o.DefaultRegion == nil {\n\t\tvar ret RegionTypes\n\t\treturn ret\n\t}\n\treturn *o.DefaultRegion\n}", "func TestGetAllRegions(t *testing.T) {\n\tawsRegionSample := []string{\"ap-southeast-1\", \"us-west-2\", \"ap-northeast-1\", \"eu-west-2\", \"eu-central-1\"}\n\tawsChinaSample := []string{\"cn-north-1\", \"cn-northwest-1\"}\n\n\tawsRegions := GetAllRegions()\n\tfor _, region := range awsRegionSample {\n\t\tif !stringInSlice(region, awsRegions) {\n\t\t\tt.Errorf(\"Could not find region %s in retrieved list: %v\", region, awsRegions)\n\t\t}\n\t}\n\n\t// Test the same for China\n\tawsRegions = GetAllChinaRegions()\n\tfor _, region := range awsChinaSample {\n\t\tif !stringInSlice(region, awsRegions) {\n\t\t\tt.Errorf(\"Could not find region %s in retrieved list: %v\", region, awsRegions)\n\t\t}\n\t}\n}", "func GetSupportedRegions() map[string]bool {\n\treturn supportedRegions\n}", "func (m *VirtualEndpoint) GetSupportedRegions()([]CloudPcSupportedRegionable) {\n val, err := m.GetBackingStore().Get(\"supportedRegions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcSupportedRegionable)\n }\n return nil\n}", "func GetEnabledRegions() ([]string, error) {\n\tvar regionNames []string\n\n\t// We don't want to depend on a default region being set, so instead we\n\t// will choose a region from the list of regions that are enabled by default\n\t// and use that to enumerate all enabled regions.\n\t// Corner case: user has intentionally disabled one or more regions that are\n\t// enabled by default. If that region is chosen, API calls will fail.\n\t// Therefore we retry until one of the regions works.\n\tregions, err := retryDescribeRegions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, region := range regions.Regions {\n\t\tregionNames = append(regionNames, awsgo.StringValue(region.RegionName))\n\t}\n\n\treturn regionNames, nil\n}", "func (o *AmazonAccountAccessKeys) HasDefaultRegion() bool {\n\tif o != nil && o.DefaultRegion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *AmazonAccountAccessKeys) GetDefaultRegionOk() (*RegionTypes, bool) {\n\tif o == nil || o.DefaultRegion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DefaultRegion, true\n}", "func (a *CloudProviderCredentialsApiService) ListAWSRegions(ctx _context.Context) ApiListAWSRegionsRequest {\n\treturn ApiListAWSRegionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (a *AzureInfoer) GetRegions() (map[string]string, error) {\n\n\tallLocations := make(map[string]string)\n\tsupLocations := make(map[string]string)\n\n\t// retrieve all locations for the subscription id (some of them may not be supported by the required provider\n\tif locations, err := a.subscriptionsClient.ListLocations(context.TODO(), a.subscriptionId); err == nil {\n\t\t// fill up the map: DisplayName - > Name\n\t\tfor _, loc := range *locations.Value {\n\t\t\tallLocations[*loc.DisplayName] = *loc.Name\n\t\t}\n\t} else {\n\t\tlog.Errorf(\"error while retrieving azure locations. err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\t// identify supported locations for the namespace and resource type\n\tconst (\n\t\tproviderNamespace = \"Microsoft.Compute\"\n\t\tresourceType = \"locations/vmSizes\"\n\t)\n\n\tif providers, err := a.providersClient.Get(context.TODO(), providerNamespace, \"\"); err == nil {\n\t\tfor _, pr := range *providers.ResourceTypes {\n\t\t\tif *pr.ResourceType == resourceType {\n\t\t\t\tfor _, displName := range *pr.Locations {\n\t\t\t\t\tif loc, ok := allLocations[displName]; ok {\n\t\t\t\t\t\tlog.Debugf(\"found supported location. [name, display name] = [%s, %s]\", loc, displName)\n\t\t\t\t\t\tsupLocations[loc] = displName\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Debugf(\"unsupported location. [name, display name] = [%s, %s]\", loc, displName)\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} else {\n\t\tlog.Errorf(\"error while retrieving supported locations for provider: %s. err: %s\", providerNamespace, err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn supLocations, nil\n}", "func ExampleRDS_DescribeSourceRegions_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DescribeSourceRegionsInput{\n\t\tRegionName: aws.String(\"us-east-1\"),\n\t}\n\n\tresult, err := svc.DescribeSourceRegions(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (c *Client) ListRegions() (strset.Set, strset.Set, error) {\n\tvar allRegions strset.Set\n\tvar enabledRegions strset.Set\n\n\terr := parallel.RunFirstErr(\n\t\tfunc() error {\n\t\t\tvar err error\n\t\t\tallRegions, err = c.ListAllRegions()\n\t\t\treturn err\n\t\t},\n\t\tfunc() error {\n\t\t\tvar err error\n\t\t\tenabledRegions, err = c.ListEnabledRegions()\n\t\t\treturn err\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn allRegions, enabledRegions, nil\n}", "func GetAvailableRegions(client *godo.Client, ctx context.Context) ([]godo.Region, error) {\n\tregions, err := rawGetRegions(client, ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar listRegions []godo.Region\n\tfor _, region := range regions {\n\t\tif region.Available {\n\t\t\tlistRegions = append(listRegions, region)\n\t\t}\n\t}\n\treturn listRegions, nil\n}", "func GetRegions() ([]string, error) {\n\t// The DescribeRegions call does not work without region\n\tsvc := ec2.New(session.New(), aws.NewConfig().WithRegion(\"us-east-1\"))\n\n\tresp, err := svc.DescribeRegions(&ec2.DescribeRegionsInput{})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.Regions != nil {\n\t\tregionNames := make([]string, 0, len(resp.Regions))\n\n\t\tfor _, region := range resp.Regions {\n\t\t\tregionNames = append(regionNames, *region.RegionName)\n\t\t}\n\n\t\treturn regionNames, nil\n\t}\n\n\treturn nil, errors.New(\"No valid regions found\")\n}", "func GetRegionList() []*ec2.Region {\n\tsess := session.Must(session.NewSession(&aws.Config{Region: aws.String(\"us-east-1\")}))\n\tsvc := ec2.New(sess)\n\n\t// Create a context with a timeout that will abort the request if it takes too long\n\tctx, cancelFn := context.WithTimeout(context.Background(), time.Second*5)\n\tdefer cancelFn()\n\n\tresp, err := svc.DescribeRegionsWithContext(ctx, nil)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn nil\n\t}\n\n\treturn resp.Regions\n}", "func (c *Client) DescribeRegions(request *DescribeRegionsRequest) (response *DescribeRegionsResponse, err error) {\n return c.DescribeRegionsWithContext(context.Background(), request)\n}", "func GetTargetRegions(enabledRegions []string, selectedRegions []string, excludedRegions []string) ([]string, error) {\n\tif len(enabledRegions) == 0 {\n\t\treturn nil, fmt.Errorf(\"Cannot have empty enabled regions\")\n\t}\n\n\t// neither selectedRegions nor excludedRegions => select enabledRegions\n\tif len(selectedRegions) == 0 && len(excludedRegions) == 0 {\n\t\treturn enabledRegions, nil\n\t}\n\n\tif len(selectedRegions) > 0 && len(excludedRegions) > 0 {\n\t\treturn nil, fmt.Errorf(\"Cannot specify both selected and excluded regions\")\n\t}\n\n\tvar invalidRegions []string\n\n\t// Validate selectedRegions\n\tfor _, selectedRegion := range selectedRegions {\n\t\tif !collections.ListContainsElement(enabledRegions, selectedRegion) {\n\t\t\tinvalidRegions = append(invalidRegions, selectedRegion)\n\t\t}\n\t}\n\tif len(invalidRegions) > 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid values for region: [%s]\", invalidRegions)\n\t}\n\n\tif len(selectedRegions) > 0 {\n\t\treturn selectedRegions, nil\n\t}\n\n\t// Validate excludedRegions\n\tfor _, excludedRegion := range excludedRegions {\n\t\tif !collections.ListContainsElement(enabledRegions, excludedRegion) {\n\t\t\tinvalidRegions = append(invalidRegions, excludedRegion)\n\t\t}\n\t}\n\tif len(invalidRegions) > 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid values for exclude-region: [%s]\", invalidRegions)\n\t}\n\n\t// Filter out excludedRegions from enabledRegions\n\tvar targetRegions []string\n\tif len(excludedRegions) > 0 {\n\t\tfor _, region := range enabledRegions {\n\t\t\tif !collections.ListContainsElement(excludedRegions, region) {\n\t\t\t\ttargetRegions = append(targetRegions, region)\n\t\t\t}\n\t\t}\n\t}\n\tif len(targetRegions) == 0 {\n\t\treturn nil, fmt.Errorf(\"Cannot exclude all regions: %s\", excludedRegions)\n\t}\n\treturn targetRegions, nil\n}", "func AWSRegion_Values() []string {\n\treturn []string{\n\t\tAWSRegionAfSouth1,\n\t\tAWSRegionApEast1,\n\t\tAWSRegionApSouth1,\n\t\tAWSRegionApSouth2,\n\t\tAWSRegionApSoutheast1,\n\t\tAWSRegionApSoutheast2,\n\t\tAWSRegionApSoutheast3,\n\t\tAWSRegionApNortheast1,\n\t\tAWSRegionApNortheast2,\n\t\tAWSRegionApNortheast3,\n\t\tAWSRegionCaCentral1,\n\t\tAWSRegionEuCentral1,\n\t\tAWSRegionEuCentral2,\n\t\tAWSRegionEuWest1,\n\t\tAWSRegionEuWest2,\n\t\tAWSRegionEuWest3,\n\t\tAWSRegionEuNorth1,\n\t\tAWSRegionEuSouth1,\n\t\tAWSRegionEuSouth2,\n\t\tAWSRegionMeCentral1,\n\t\tAWSRegionMeSouth1,\n\t\tAWSRegionSaEast1,\n\t\tAWSRegionUsEast1,\n\t\tAWSRegionUsEast2,\n\t\tAWSRegionUsWest1,\n\t\tAWSRegionUsWest2,\n\t\tAWSRegionCnNorth1,\n\t\tAWSRegionCnNorthwest1,\n\t}\n}", "func (db regionDatabase) GetRegions() ([]mgm.Region, error) {\n\tcon, err := db.mysql.GetConnection()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer con.Close()\n\n\trows, err := con.Query(\n\t\t\"Select uuid, name, size, httpPort, consolePort, consoleUname, consolePass, locX, locY, host from regions\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar regions []mgm.Region\n\tfor rows.Next() {\n\t\tr := mgm.Region{}\n\t\terr = rows.Scan(\n\t\t\t&r.UUID,\n\t\t\t&r.Name,\n\t\t\t&r.Size,\n\t\t\t&r.HTTPPort,\n\t\t\t&r.ConsolePort,\n\t\t\t&r.ConsoleUname,\n\t\t\t&r.ConsolePass,\n\t\t\t&r.LocX,\n\t\t\t&r.LocY,\n\t\t\t&r.Host,\n\t\t)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\tregions = append(regions, r)\n\t}\n\treturn regions, nil\n}", "func GetRegions(ctx *pulumi.Context, args *GetRegionsArgs, opts ...pulumi.InvokeOption) (*GetRegionsResult, error) {\n\tvar rv GetRegionsResult\n\terr := ctx.Invoke(\"gcp:compute/getRegions:getRegions\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func Regions() (names []string) {\n\tif RegionNames == nil {\n\t\tif RegionNames = fetchRegions(); RegionNames == nil {\n\t\t\tlog.Errorf(\"expected (regions) got ()\")\n\t\t\treturn nil\n\t\t}\n\t\tfor _, name := range RegionNames {\n\t\t\tRegionMap[name] = &Region{Name: name}\n\t\t}\n\t}\n\treturn RegionNames\n}", "func (m *MockKubernetesService) GetRegions() (do.KubernetesRegions, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRegions\")\n\tret0, _ := ret[0].(do.KubernetesRegions)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (VoiceConnectorAwsRegion) Values() []VoiceConnectorAwsRegion {\n\treturn []VoiceConnectorAwsRegion{\n\t\t\"us-east-1\",\n\t\t\"us-west-2\",\n\t}\n}", "func GetRegionAZs(region string, sess *session.Session) ([]string, error) {\n\tsvc := ec2.New(sess)\n\t// describe AvailabilityZones in the region\n\tparams := &ec2.DescribeAvailabilityZonesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(regionFilterName),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(region),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tres, err := svc.DescribeAvailabilityZones(params)\n\tif err != nil {\n\t\tglog.Errorln(\"DescribeAvailabilityZones error\", err)\n\t\treturn nil, err\n\t}\n\tif len(res.AvailabilityZones) == 0 {\n\t\tglog.Errorln(\"No AvailabilityZones in region\", region)\n\t\treturn nil, common.ErrInternal\n\t}\n\tazs := make([]string, len(res.AvailabilityZones))\n\tfor i, zone := range res.AvailabilityZones {\n\t\tazs[i] = *(zone.ZoneName)\n\t}\n\treturn azs, nil\n}", "func (a *AzureInfoer) GetRegions(service string) (map[string]string, error) {\n\tlogger := a.log.WithFields(map[string]interface{}{\"service\": service})\n\tlogger.Debug(\"getting locations\")\n\n\tallLocations := make(map[string]string)\n\tsupLocations := make(map[string]string)\n\n\t// retrieve all locations for the subscription id (some of them may not be supported by the required provider)\n\tif locations, err := a.subscriptionsClient.ListLocations(context.TODO(), a.subscriptionId); err == nil {\n\t\t// fill up the map: DisplayName - > Name\n\t\tfor _, loc := range *locations.Value {\n\t\t\tallLocations[*loc.DisplayName] = *loc.Name\n\t\t}\n\t} else {\n\t\tlogger.Error(\"error while retrieving azure locations\")\n\t\treturn nil, err\n\t}\n\n\t// identify supported locations for the namespace and resource type\n\tconst (\n\t\tproviderNamespaceForCompute = \"Microsoft.Compute\"\n\t\tresourceTypeForCompute = \"locations/vmSizes\"\n\t\tproviderNamespaceForAks = \"Microsoft.ContainerService\"\n\t\tresourceTypeForAks = \"managedClusters\"\n\t)\n\n\tswitch service {\n\tcase \"aks\":\n\t\tif providers, err := a.providersClient.Get(context.TODO(), providerNamespaceForAks, \"\"); err == nil {\n\t\t\tfor _, pr := range *providers.ResourceTypes {\n\t\t\t\tif *pr.ResourceType == resourceTypeForAks {\n\t\t\t\t\tfor _, displName := range *pr.Locations {\n\t\t\t\t\t\tif loc, ok := allLocations[displName]; ok {\n\t\t\t\t\t\t\tsupLocations[loc] = displName\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.Debug(\"unsupported location\", map[string]interface{}{\"name\": loc, \"displayname\": displName})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Error(\"failed to retrieve supported locations\", map[string]interface{}{\"resource\": resourceTypeForAks})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogger.Debug(\"found supported locations\", map[string]interface{}{\"numberOfLocations\": len(supLocations)})\n\t\treturn supLocations, nil\n\tdefault:\n\t\tif providers, err := a.providersClient.Get(context.TODO(), providerNamespaceForCompute, \"\"); err == nil {\n\t\t\tfor _, pr := range *providers.ResourceTypes {\n\t\t\t\tif *pr.ResourceType == resourceTypeForCompute {\n\t\t\t\t\tfor _, displName := range *pr.Locations {\n\t\t\t\t\t\tif loc, ok := allLocations[displName]; ok {\n\t\t\t\t\t\t\tsupLocations[loc] = displName\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.Debug(\"unsupported location\", map[string]interface{}{\"name\": loc, \"displayname\": displName})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Error(\"failed to retrieve supported locations\", map[string]interface{}{\"resource\": resourceTypeForCompute})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogger.Debug(\"found supported locations\", map[string]interface{}{\"numberOfLocations\": len(supLocations)})\n\t\treturn supLocations, nil\n\t}\n}", "func (o *AmazonAccountAccessKeys) SetDefaultRegion(v RegionTypes) {\n\to.DefaultRegion = &v\n}", "func (e Endpoints) ListRegions(ctx context.Context, token string) (regions []registry.Region, err error) {\n\trequest := ListRegionsRequest{Token: token}\n\tresponse, err := e.ListRegionsEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListRegionsResponse).Regions, response.(ListRegionsResponse).Err\n}", "func DeleteDefaultVPCs(region string, role string, deleteFlag bool, isPrivileged bool) error {\n\tenabledRegions := GetEnabledRegions(region, role, isPrivileged)\n\n\tlogrus.Infof(\"Deleting default VPCs\")\n\n\tif !deleteFlag {\n\t\tlogrus.Infof(\"Dry-run mode is active. Run again with %s flag to delete VPCs\", \"--delete\")\n\t}\n\n\tlogrus.Info(\"Identifying VPCs to delete:\")\n\n\tfor r := range enabledRegions {\n\t\tcurrentRegion := enabledRegions[r]\n\t\tlogrus.Infof(\" Processing region %s\", currentRegion)\n\n\t\tclient := getEC2Client(currentRegion)\n\t\tif !isPrivileged {\n\t\t\tclient = getEC2ClientWithRole(currentRegion, role)\n\t\t}\n\n\t\tvpc := getDefaultVPC(client)\n\t\tif vpc != \"\" {\n\t\t\tlogrus.Infof(\" found %s\", vpc)\n\n\t\t\tif deleteFlag {\n\t\t\t\tvpcInfo := Vpc{\n\t\t\t\t\tVpcID: vpc,\n\t\t\t\t\tclient: *client,\n\t\t\t\t}\n\n\t\t\t\tvpcInfo.delete()\n\t\t\t}\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Deleting default VPCs complete\")\n\n\treturn nil\n}", "func retryDescribeRegions() (*ec2.DescribeRegionsOutput, error) {\n\tfor i := 0; i < len(OptInNotRequiredRegions); i++ {\n\t\tregion := OptInNotRequiredRegions[rand.Intn(len(OptInNotRequiredRegions))]\n\t\tsvc := ec2.New(newSession(region))\n\t\tregions, err := svc.DescribeRegions(&ec2.DescribeRegionsInput{})\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\treturn regions, nil\n\t}\n\treturn nil, errors.WithStackTrace(fmt.Errorf(\"could not find any enabled regions\"))\n}", "func (a *API) ListRegions() ([]string, error) {\n\trequest := ecs.CreateDescribeRegionsRequest()\n\trequest.Scheme = \"https\"\n\n\tresponse, err := a.ecs.DescribeRegions(request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"describing regions: %v\", err)\n\t}\n\tret := make([]string, 0, len(response.Regions.Region))\n\tfor _, region := range response.Regions.Region {\n\t\tret = append(ret, region.RegionId)\n\t}\n\tsort.Strings(ret)\n\treturn ret, nil\n}", "func (s *AppsServiceOp) ListRegions(ctx context.Context) ([]*AppRegion, *Response, error) {\n\tpath := fmt.Sprintf(\"%s/regions\", appsBasePath)\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(appRegionsRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn root.Regions, resp, nil\n}", "func NewGetTimezoneRegionDefault(code int) *GetTimezoneRegionDefault {\n\treturn &GetTimezoneRegionDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (s *API) Regions() []scw.Region {\n\treturn []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}\n}", "func (c *Client) ListEnabledRegions() (strset.Set, error) {\n\tresult, err := c.EC2().DescribeRegions(&ec2.DescribeRegionsInput{\n\t\tAllRegions: aws.Bool(false),\n\t})\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tregions := strset.New()\n\tfor _, region := range result.Regions {\n\t\tif region.RegionName != nil {\n\t\t\tregions.Add(*region.RegionName)\n\t\t}\n\t}\n\n\treturn regions, nil\n}", "func (c *Client) SystemRegions() Regions {\n\tvar regions Regions\n\n\tendpoint := fmt.Sprintf(\"systems/regions\")\n\tc.invokeAPI(\"GET\", endpoint, nil, &regions)\n\n\treturn regions\n}", "func TestIntegrationDefault(t *testing.T) {\n\ts := New(genericRegions[0], genericRegions)\n\tss, err := s.Default()\n\tif err != nil {\n\t\tt.Fatalf(\"Default() failed: %v\", err)\n\t}\n\tif ss.Config == nil || ss.Config.Region == nil {\n\t\tt.Fatal(\"ss.Config or ss.Config.Region is nil\")\n\t}\n\tresult := *ss.Config.Region\n\tif result != genericRegions[0] {\n\t\tt.Fatalf(\"Default() region invalid, expected: %s, got: %s\", genericRegions[0], result)\n\t}\n}", "func (s *AwsLogSourceConfiguration) SetRegions(v []*string) *AwsLogSourceConfiguration {\n\ts.Regions = v\n\treturn s\n}", "func GetAllRegions(year int, inklSonntag bool, country ...string) (regions []Region) {\n\tgermanregions := regionFunctionListToRegionList([]func(y int, inklSonntage ...bool) Region{BadenWürttemberg, Bayern, Berlin,\n\t\tBrandenburg, Bremen, Hamburg, Hessen, MecklenburgVorpommern, Niedersachsen, NordrheinWestfalen,\n\t\tRheinlandPfalz, Saarland, Sachsen, SachsenAnhalt, SchleswigHolstein, Thüringen, Deutschland}, year, inklSonntag)\n\n\taustrianregions := regionFunctionListToRegionList([]func(y int, inklSonntage ...bool) Region{Burgenland, Kärnten, Niederösterreich,\n\t\tOberösterreich, Salzburg, Steiermark, Tirol, Vorarlberg, Wien, Österreich}, year, inklSonntag)\n\n\tif len(country) > 0 {\n\t\tc := strings.ToLower(country[0])\n\t\tif c == \"de\" {\n\t\t\tregions = germanregions\n\t\t} else if c == \"at\" {\n\t\t\tregions = austrianregions\n\t\t}\n\t} else {\n\t\tregions = append(append(germanregions, austrianregions...), All(year, inklSonntag))\n\t}\n\n\treturn regions\n}", "func GetRegionAZs(region string, azList *AZs) error {\n\n\tsess := session.Must(session.NewSession(&aws.Config{Region: aws.String(region)}))\n\tsvc := ec2.New(sess)\n\n\t// Create a context with a timeout that will abort the request if it takes too long\n\tctx, cancelFn := context.WithTimeout(context.Background(), time.Second*5)\n\tdefer cancelFn()\n\n\tresult, err := svc.DescribeAvailabilityZonesWithContext(ctx, nil)\n\n\tif err != nil {\n\t\t/*terminal.ErrorLine(\"Region AZ request timeout in [\" + region + \"], skipping...\")*/\n\t\treturn nil\n\t}\n\n\tazs := make(AZs, len(result.AvailabilityZones))\n\tfor i, az := range result.AvailabilityZones {\n\t\tazs[i] = AZ{\n\t\t\tName: aws.StringValue(az.ZoneName),\n\t\t\tRegion: aws.StringValue(az.RegionName),\n\t\t\tState: aws.StringValue(az.State),\n\t\t}\n\t}\n\n\t*azList = append(*azList, azs[:]...)\n\n\treturn nil\n}", "func (bc *BasicLineGraph) GetRegions() []*RegionInfo {\n\tbc.RLock()\n\tdefer bc.RUnlock()\n\treturn bc.Regions.GetRegions()\n}", "func Regions() int {\n\treturn int(reg.Get(TZASC_CONF, CONF_REGIONS, 0xf)) + 1\n}", "func checkRegions(regions []string) ([]string, error) {\n\tif regions[0] == \"all\" {\n\t\treturn core.AllowedRegions, nil\n\t}\n\n\tfor _, region := range regions {\n\t\tisValid := false\n\t\tfor _, allowedRegion := range core.AllowedRegions {\n\t\t\tif region == allowedRegion {\n\t\t\t\tisValid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !isValid {\n\t\t\treturn nil, fmt.Errorf(\"invalid region: %s\", region)\n\t\t}\n\t}\n\n\treturn regions, nil\n}", "func (c *Client) DescribeRegions(ctx context.Context, params *DescribeRegionsInput, optFns ...func(*Options)) (*DescribeRegionsOutput, error) {\n\tif params == nil {\n\t\tparams = &DescribeRegionsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"DescribeRegions\", params, optFns, c.addOperationDescribeRegionsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*DescribeRegionsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func getAwsRegion() (region string) {\n\tregion, _ = getAwsRegionE()\n\treturn\n}", "func (o WorkerPoolOutput) Regions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringArrayOutput { return v.Regions }).(pulumi.StringArrayOutput)\n}", "func (c Clients) Regions() map[string]*Client {\n\treturn c.regions\n}", "func (m *MockClient) DescribeRegions(input *ec2.DescribeRegionsInput) (*ec2.DescribeRegionsOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DescribeRegions\", input)\n\tret0, _ := ret[0].(*ec2.DescribeRegionsOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func DefaultARMImages() ImageSelector {\n\treturn defaultARMImages\n}", "func (client IdentityClient) ListRegions(ctx context.Context) (response ListRegionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tociResponse, err = client.listRegions(ctx)\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 = ListRegionsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListRegionsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListRegionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListRegionsResponse\")\n\t}\n\treturn\n}", "func (o AccessLevelsAccessLevelBasicConditionOutput) Regions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelsAccessLevelBasicCondition) []string { return v.Regions }).(pulumi.StringArrayOutput)\n}", "func (TranscribeRegion) Values() []TranscribeRegion {\n\treturn []TranscribeRegion{\n\t\t\"us-east-2\",\n\t\t\"us-east-1\",\n\t\t\"us-west-2\",\n\t\t\"ap-northeast-2\",\n\t\t\"ap-southeast-2\",\n\t\t\"ap-northeast-1\",\n\t\t\"ca-central-1\",\n\t\t\"eu-central-1\",\n\t\t\"eu-west-1\",\n\t\t\"eu-west-2\",\n\t\t\"sa-east-1\",\n\t\t\"auto\",\n\t}\n}", "func (c *Cluster) GetAllRegions() []*Region {\n\tregions := make([]*Region, 0, len(c.regions))\n\tfor _, region := range c.regions {\n\t\tregions = append(regions, region)\n\t}\n\treturn regions\n}", "func (o TopicMessageStoragePolicyOutput) AllowedPersistenceRegions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TopicMessageStoragePolicy) []string { return v.AllowedPersistenceRegions }).(pulumi.StringArrayOutput)\n}", "func (c *Client) GetAvailableWatchProviderRegions(\n\turlOptions map[string]string,\n) (*WatchRegionList, error) {\n\toptions := c.fmtOptions(urlOptions)\n\ttmdbURL := fmt.Sprintf(\n\t\t\"%s%sregions?api_key=%s%s\",\n\t\tbaseURL,\n\t\twatchProvidersURL,\n\t\tc.apiKey,\n\t\toptions,\n\t)\n\twatchRegionList := WatchRegionList{}\n\tif err := c.get(tmdbURL, &watchRegionList); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &watchRegionList, nil\n}", "func Regions(dbCfg db.Config) ([]models.Region, error) {\n\tvar regions []models.Region\n\n\tdatabase, err := db.OpenDatabase(dbCfg)\n\tdefer database.Close()\n\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\n\tregions = database.NewRegionsQuery().Get()\n\treturn regions, nil\n}", "func (o AccessLevelBasicConditionOutput) Regions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelBasicCondition) []string { return v.Regions }).(pulumi.StringArrayOutput)\n}", "func (a *Client) GetUniverseRegions(params *GetUniverseRegionsParams) (*GetUniverseRegionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseRegionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_regions\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/regions/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseRegionsReader{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.(*GetUniverseRegionsOK), nil\n\n}", "func knownPublicRegions(architecture types.Architecture) map[string]string {\n\trequired := rhcos.AMIRegions(architecture)\n\n\tregions := make(map[string]string)\n\tfor _, region := range endpoints.AwsPartition().Regions() {\n\t\tif required.Has(region.ID()) {\n\t\t\tregions[region.ID()] = region.Description()\n\t\t}\n\t}\n\treturn regions\n}", "func (client IdentityClient) listRegions(ctx context.Context) (common.OCIResponse, error) {\n\thttpRequest := common.MakeDefaultHTTPRequest(http.MethodGet, \"/regions\")\n\tvar err error\n\n\tvar response ListRegionsResponse\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 updateRegions() {\n\tlogrus.Debug(\"Updating regions.\")\n\n\tregions, err := getMarketRegions()\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Could not get regionIDs from ESI!\")\n\t\treturn\n\t}\n\n\tregionIDs = regions\n\tlogrus.Debug(\"Region update done.\")\n}", "func (p *AWS) Initialize(config *types.ProviderConfig) error {\n\tp.Storage = &S3{}\n\n\tif config.Zone == \"\" {\n\t\treturn errors.New(\"zone missing\")\n\t}\n\n\terr := loadAWSCreds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := session.NewSession(\n\t\t&aws.Config{\n\t\t\tRegion: aws.String(stripZone(config.Zone)),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.session = session\n\tp.dnsService = route53.New(session)\n\tp.ec2 = ec2.New(session)\n\tp.volumeService = ebs.New(session,\n\t\taws.NewConfig().\n\t\t\tWithRegion(stripZone(config.Zone)).\n\t\t\tWithMaxRetries(7))\n\n\t_, err = p.ec2.DescribeRegions(&ec2.DescribeRegionsInput{RegionNames: aws.StringSlice([]string{stripZone(config.Zone)})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"region with name %v is invalid\", config.Zone)\n\t}\n\n\treturn nil\n}", "func (client *Client) GetRegionList(request *GetRegionListRequest) (response *GetRegionListResponse, err error) {\n\tresponse = CreateGetRegionListResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func getAwsRegionE() (region string, err error) {\n\n\tif os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t} else {\n\t\t// Grab it from this EC2 instace\n\t\tregion, err = ec2metadata.New(session.New()).Region()\n\t}\n\treturn\n}", "func awsFormatRegion(r *string) aws.Region {\n\tvar region aws.Region\n\tswitch *r {\n\tcase \"us-gov-west-1\":\n\t\tregion = aws.USGovWest\n\tcase \"us-east-1\":\n\t\tregion = aws.USEast\n\tcase \"us-west-1\":\n\t\tregion = aws.USWest\n\tcase \"us-west-2\":\n\t\tregion = aws.USWest2\n\tcase \"eu-west-1\":\n\t\tregion = aws.EUWest\n\tcase \"ap-southeast-1\":\n\t\tregion = aws.APSoutheast\n\tcase \"ap-southeast-2\":\n\t\tregion = aws.APSoutheast2\n\tcase \"ap-northeast-1\":\n\t\tregion = aws.APNortheast\n\tcase \"sa-east-1\":\n\t\tregion = aws.SAEast\n\tcase \"\":\n\t\tregion = aws.USEast\n\tdefault:\n\t\tlog.Fatalf(\"Invalid Region: %s\\n\", *r)\n\t}\n\treturn region\n}", "func GetRegionNameList() (names []string) {\n\tvregions := GetRegionList()\n\tfor _, vregion := range vregions {\n\t\tnames = append(names, aws.StringValue(vregion.RegionName))\n\t}\n\treturn\n}", "func (s *ListLogSourcesInput) SetRegions(v []*string) *ListLogSourcesInput {\n\ts.Regions = v\n\treturn s\n}", "func getDefaultMachineVolumes() []string {\n\treturn []string{}\n}", "func getValidRegions() []string {\n\tvrs := make([]string, len(validRegions)*2)\n\ti := 0\n\tfor k, v := range validRegions {\n\t\tvrs[i] = k\n\t\tvrs[i+1] = v\n\t\ti += 2\n\t}\n\tsort.Strings(vrs)\n\treturn vrs\n}", "func (m *CompaniesCompanyItemRequestBuilder) CountriesRegions()(*CompaniesItemCountriesRegionsRequestBuilder) {\n return NewCompaniesItemCountriesRegionsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (a Config) RegionOrDefault() string {\n\tif a.Region != \"\" {\n\t\treturn a.Region\n\t}\n\treturn DefaultRegion\n}", "func (mc *MockCluster) ScanRegions(startKey []byte, limit int) []*core.RegionInfo {\n\treturn mc.Regions.ScanRange(startKey, limit)\n}", "func GetMarketRegions() []int64 {\n\treturn regionIDs\n}", "func (svc *ServiceDefinition) ProvisionDefaultOverrides() map[string]interface{} {\n\treturn viper.GetStringMap(svc.ProvisionDefaultOverrideProperty())\n}", "func (m *VirtualEndpoint) SetSupportedRegions(value []CloudPcSupportedRegionable)() {\n err := m.GetBackingStore().Set(\"supportedRegions\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *PhoneNumbersService) GetPhoneNumberRegions(params GetPhoneNumberRegionsParams) (*GetPhoneNumberRegionsReturn, *structure.VError, error) {\n\treq, err := s.client.NewRequest(\"POST\", \"GetPhoneNumberRegions\", params)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tresponse := &GetPhoneNumberRegionsReturn{}\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}", "func (b *CompanyRequestBuilder) CountriesRegions() *CompanyCountriesRegionsCollectionRequestBuilder {\n\tbb := &CompanyCountriesRegionsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/countriesRegions\"\n\treturn bb\n}", "func (o TopicMessageStoragePolicyPtrOutput) AllowedPersistenceRegions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TopicMessageStoragePolicy) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AllowedPersistenceRegions\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *Session) Regions(ctx context.Context, req RegionRequest) (*RegionResults, error) {\n\t// Create the URL\n\turl := s.APIURL + \"/\" + regionEndpoint\n\n\t// Call and return\n\treturn s.region(ctx, url, req)\n}", "func (a *AzureInfoer) GetZones(region string) ([]string, error) {\n\treturn []string{region}, nil\n}", "func (g *Game) Regions() (*RegionCollection, *Error) {\n\tvar result *RegionCollection\n\n\tswitch asserted := g.RegionsData.(type) {\n\t// list of IDs (strings)\n\tcase []interface{}:\n\t\tids, err := g.RegionIDs()\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\n\t\tresult = &RegionCollection{}\n\n\t\tfor _, id := range ids {\n\t\t\tregion, err := RegionByID(id)\n\t\t\tif err != nil {\n\t\t\t\treturn result, err\n\t\t\t}\n\n\t\t\tresult.Data = append(result.Data, *region)\n\t\t}\n\n\t// sub-resource due to embeds, aka \"{data:....}\"\n\tcase map[string]interface{}:\n\t\tresult = toRegionCollection(asserted)\n\t}\n\n\treturn result, nil\n}", "func NewCloudAwsVirtualMachineAllOfWithDefaults() *CloudAwsVirtualMachineAllOf {\n\tthis := CloudAwsVirtualMachineAllOf{}\n\tvar classId string = \"cloud.AwsVirtualMachine\"\n\tthis.ClassId = classId\n\tvar objectType string = \"cloud.AwsVirtualMachine\"\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func (p *HbaseClient) GetTableRegions(tableName Text) (r []*TRegionInfo, err error) {\n\tif err = p.sendGetTableRegions(tableName); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetTableRegions()\n}", "func (TranscribeMedicalRegion) Values() []TranscribeMedicalRegion {\n\treturn []TranscribeMedicalRegion{\n\t\t\"us-east-1\",\n\t\t\"us-east-2\",\n\t\t\"us-west-2\",\n\t\t\"ap-southeast-2\",\n\t\t\"ca-central-1\",\n\t\t\"eu-west-1\",\n\t\t\"auto\",\n\t}\n}", "func selectRegions(regionMap map[string]RegionInfo, regionConstraint, clusterConstraint policyv1alpha1.SpreadConstraint) []RegionInfo {\n\tgroups := make([]*GroupInfo, 0, len(regionMap))\n\tfor _, region := range regionMap {\n\t\tgroup := &GroupInfo{\n\t\t\tname: region.Name,\n\t\t\tvalue: len(region.Clusters),\n\t\t\tweight: region.Score,\n\t\t}\n\t\tgroups = append(groups, group)\n\t}\n\n\tgroups = selectGroups(groups, regionConstraint.MinGroups, regionConstraint.MaxGroups, clusterConstraint.MinGroups)\n\tif len(groups) == 0 {\n\t\treturn nil\n\t}\n\n\tresult := make([]RegionInfo, 0, len(groups))\n\tfor _, group := range groups {\n\t\tresult = append(result, regionMap[group.name])\n\t}\n\treturn result\n}", "func (m *MockRDSAPI) DescribeSourceRegions(arg0 *rds.DescribeSourceRegionsInput) (*rds.DescribeSourceRegionsOutput, error) {\n\tret := m.ctrl.Call(m, \"DescribeSourceRegions\", arg0)\n\tret0, _ := ret[0].(*rds.DescribeSourceRegionsOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (t *TikvHandlerTool) GetRegionsMeta(regionIDs []uint64) ([]RegionMeta, error) {\n\tregions := make([]RegionMeta, len(regionIDs))\n\tfor i, regionID := range regionIDs {\n\t\tregion, err := t.RegionCache.PDClient().GetRegionByID(context.TODO(), regionID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\n\t\tfailpoint.Inject(\"errGetRegionByIDEmpty\", func(val failpoint.Value) {\n\t\t\tif val.(bool) {\n\t\t\t\tregion.Meta = nil\n\t\t\t}\n\t\t})\n\n\t\tif region.Meta == nil {\n\t\t\treturn nil, errors.Errorf(\"region not found for regionID %q\", regionID)\n\t\t}\n\t\tregions[i] = RegionMeta{\n\t\t\tID: regionID,\n\t\t\tLeader: region.Leader,\n\t\t\tPeers: region.Meta.Peers,\n\t\t\tRegionEpoch: region.Meta.RegionEpoch,\n\t\t}\n\t}\n\treturn regions, nil\n}", "func (c *Client) GetServiceRegions(cloudProvider, service string) ([]string, error) {\n\tregions, _, err := c.apiClient.RegionsApi.GetRegions(context.Background(), cloudProvider, service)\n\tif err != nil {\n\t\treturn nil, emperror.WrapWith(err, \"couldn't get service availability regions\", \"cloudProvider\", cloudProvider, \"service\", service)\n\t}\n\n\tregionIds := make([]string, len(regions))\n\tfor idx, region := range regions {\n\t\tregionIds[idx] = region.Id\n\t}\n\n\treturn regionIds, nil\n}", "func generateBundlesDefaultRoles() []*settings.Bundle {\n\treturn []*settings.Bundle{\n\t\tgenerateBundleAdminRole(),\n\t\tgenerateBundleUserRole(),\n\t\tgenerateBundleGuestRole(),\n\t}\n}", "func (m *CountryNamedLocation) GetCountriesAndRegions()([]string) {\n val, err := m.GetBackingStore().Get(\"countriesAndRegions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func K3sDefaultDeployments() error {\n\treturn CheckDeployments([]string{\"coredns\", \"local-path-provisioner\", \"metrics-server\", \"traefik\"})\n}", "func (fp *BatchGetRegionsResponse_FieldTerminalPath) GetDefault() interface{} {\n\tswitch fp.selector {\n\tcase BatchGetRegionsResponse_FieldPathSelectorRegions:\n\t\treturn ([]*region.Region)(nil)\n\tcase BatchGetRegionsResponse_FieldPathSelectorMissing:\n\t\treturn ([]*region.Reference)(nil)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Invalid selector for BatchGetRegionsResponse: %d\", fp.selector))\n\t}\n}", "func GetZones(sess *session.Session) (*ec2.DescribeAvailabilityZonesOutput, error) {\n svc := ec2.New(sess)\n\n // snippet-start:[ec2.go.regions_and_zones.zones]\n resultAvalZones, err := svc.DescribeAvailabilityZones(nil)\n // snippet-end:[ec2.go.regions_and_zones.zones]\n if err != nil {\n return nil, err\n }\n\n return resultAvalZones, nil\n}", "func (s *ListDataLakesInput) SetRegions(v []*string) *ListDataLakesInput {\n\ts.Regions = v\n\treturn s\n}", "func GetAllResources(targetRegions []string, excludeAfter time.Time, resourceTypes []string, configObj config.Config) (*AwsAccountResources, error) {\n\taccount := AwsAccountResources{\n\t\tResources: make(map[string]AwsRegionResource),\n\t}\n\n\tcount := 1\n\ttotalRegions := len(targetRegions)\n\tvar resourcesCache = map[string]map[string][]*string{}\n\n\tfor _, region := range targetRegions {\n\t\tlogging.Logger.Infof(\"Checking region [%d/%d]: %s\", count, totalRegions, region)\n\n\t\tsession, err := session.NewSession(&awsgo.Config{\n\t\t\tRegion: awsgo.String(region)},\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t}\n\n\t\tresourcesInRegion := AwsRegionResource{}\n\n\t\t// The order in which resources are nuked is important\n\t\t// because of dependencies between resources\n\n\t\t// ASG Names\n\t\tasGroups := ASGroups{}\n\t\tif IsNukeable(asGroups.ResourceName(), resourceTypes) {\n\t\t\tgroupNames, err := getAllAutoScalingGroups(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(groupNames) > 0 {\n\t\t\t\tasGroups.GroupNames = awsgo.StringValueSlice(groupNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, asGroups)\n\t\t\t}\n\t\t}\n\t\t// End ASG Names\n\n\t\t// Launch Configuration Names\n\t\tconfigs := LaunchConfigs{}\n\t\tif IsNukeable(configs.ResourceName(), resourceTypes) {\n\t\t\tconfigNames, err := getAllLaunchConfigurations(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(configNames) > 0 {\n\t\t\t\tconfigs.LaunchConfigurationNames = awsgo.StringValueSlice(configNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, configs)\n\t\t\t}\n\t\t}\n\t\t// End Launch Configuration Names\n\n\t\t// LoadBalancer Names\n\t\tloadBalancers := LoadBalancers{}\n\t\tif IsNukeable(loadBalancers.ResourceName(), resourceTypes) {\n\t\t\telbNames, err := getAllElbInstances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(elbNames) > 0 {\n\t\t\t\tloadBalancers.Names = awsgo.StringValueSlice(elbNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, loadBalancers)\n\t\t\t}\n\t\t}\n\t\t// End LoadBalancer Names\n\n\t\t// LoadBalancerV2 Arns\n\t\tloadBalancersV2 := LoadBalancersV2{}\n\t\tif IsNukeable(loadBalancersV2.ResourceName(), resourceTypes) {\n\t\t\telbv2Arns, err := getAllElbv2Instances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(elbv2Arns) > 0 {\n\t\t\t\tloadBalancersV2.Arns = awsgo.StringValueSlice(elbv2Arns)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, loadBalancersV2)\n\t\t\t}\n\t\t}\n\t\t// End LoadBalancerV2 Arns\n\n\t\t// EC2 Instances\n\t\tec2Instances := EC2Instances{}\n\t\tif IsNukeable(ec2Instances.ResourceName(), resourceTypes) {\n\t\t\tinstanceIds, err := getAllEc2Instances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(instanceIds) > 0 {\n\t\t\t\tec2Instances.InstanceIds = awsgo.StringValueSlice(instanceIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ec2Instances)\n\t\t\t}\n\t\t}\n\t\t// End EC2 Instances\n\n\t\t// EBS Volumes\n\t\tebsVolumes := EBSVolumes{}\n\t\tif IsNukeable(ebsVolumes.ResourceName(), resourceTypes) {\n\t\t\tvolumeIds, err := getAllEbsVolumes(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(volumeIds) > 0 {\n\t\t\t\tebsVolumes.VolumeIds = awsgo.StringValueSlice(volumeIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ebsVolumes)\n\t\t\t}\n\t\t}\n\t\t// End EBS Volumes\n\n\t\t// EIP Addresses\n\t\teipAddresses := EIPAddresses{}\n\t\tif IsNukeable(eipAddresses.ResourceName(), resourceTypes) {\n\t\t\tallocationIds, err := getAllEIPAddresses(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(allocationIds) > 0 {\n\t\t\t\teipAddresses.AllocationIds = awsgo.StringValueSlice(allocationIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, eipAddresses)\n\t\t\t}\n\t\t}\n\t\t// End EIP Addresses\n\n\t\t// AMIs\n\t\tamis := AMIs{}\n\t\tif IsNukeable(amis.ResourceName(), resourceTypes) {\n\t\t\timageIds, err := getAllAMIs(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(imageIds) > 0 {\n\t\t\t\tamis.ImageIds = awsgo.StringValueSlice(imageIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, amis)\n\t\t\t}\n\t\t}\n\t\t// End AMIs\n\n\t\t// Snapshots\n\t\tsnapshots := Snapshots{}\n\t\tif IsNukeable(snapshots.ResourceName(), resourceTypes) {\n\t\t\tsnapshotIds, err := getAllSnapshots(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(snapshotIds) > 0 {\n\t\t\t\tsnapshots.SnapshotIds = awsgo.StringValueSlice(snapshotIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, snapshots)\n\t\t\t}\n\t\t}\n\t\t// End Snapshots\n\n\t\t// ECS resources\n\t\tecsServices := ECSServices{}\n\t\tif IsNukeable(ecsServices.ResourceName(), resourceTypes) {\n\t\t\tclusterArns, err := getAllEcsClusters(session)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(clusterArns) > 0 {\n\t\t\t\tserviceArns, serviceClusterMap, err := getAllEcsServices(session, clusterArns, excludeAfter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\t\t\t\tecsServices.Services = awsgo.StringValueSlice(serviceArns)\n\t\t\t\tecsServices.ServiceClusterMap = serviceClusterMap\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ecsServices)\n\t\t\t}\n\t\t}\n\t\t// End ECS resources\n\n\t\t// EKS resources\n\t\teksClusters := EKSClusters{}\n\t\tif IsNukeable(eksClusters.ResourceName(), resourceTypes) {\n\t\t\tif eksSupportedRegion(region) {\n\t\t\t\teksClusterNames, err := getAllEksClusters(session, excludeAfter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\t\t\t\tif len(eksClusterNames) > 0 {\n\t\t\t\t\teksClusters.Clusters = awsgo.StringValueSlice(eksClusterNames)\n\t\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, eksClusters)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// End EKS resources\n\n\t\t// RDS DB Instances\n\t\tdbInstances := DBInstances{}\n\t\tif IsNukeable(dbInstances.ResourceName(), resourceTypes) {\n\t\t\tinstanceNames, err := getAllRdsInstances(session, excludeAfter)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\n\t\t\tif len(instanceNames) > 0 {\n\t\t\t\tdbInstances.InstanceNames = awsgo.StringValueSlice(instanceNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, dbInstances)\n\t\t\t}\n\t\t}\n\t\t// End RDS DB Instances\n\n\t\t// RDS DB Clusters\n\t\t// These reference the Aurora Clusters, for the use it's the same resource (rds), but AWS\n\t\t// has different abstractions for each.\n\t\tdbClusters := DBClusters{}\n\t\tif IsNukeable(dbClusters.ResourceName(), resourceTypes) {\n\t\t\tclustersNames, err := getAllRdsClusters(session, excludeAfter)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\n\t\t\tif len(clustersNames) > 0 {\n\t\t\t\tdbClusters.InstanceNames = awsgo.StringValueSlice(clustersNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, dbClusters)\n\t\t\t}\n\t\t}\n\t\t// End RDS DB Clusters\n\n\t\t// S3 Buckets\n\t\ts3Buckets := S3Buckets{}\n\t\tif IsNukeable(s3Buckets.ResourceName(), resourceTypes) {\n\t\t\tvar bucketNamesPerRegion map[string][]*string\n\n\t\t\t// AWS S3 buckets list operation lists all buckets irrespective of regions.\n\t\t\t// For each bucket we have to make a separate call to find the bucket region.\n\t\t\t// Hence for x buckets and a total of y target regions - we need to make:\n\t\t\t// (x + 1) * y calls i.e. 1 call to list all x buckets, x calls to find out\n\t\t\t// each bucket's region and repeat the process for each of the y regions.\n\n\t\t\t// getAllS3Buckets returns a map of regions to buckets and we call it only once -\n\t\t\t// thereby reducing total calls from (x + 1) * y to only (x + 1) for the first region -\n\t\t\t// followed by a cache lookup for rest of the regions.\n\n\t\t\t// Cache lookup to check if we already obtained bucket names per region\n\t\t\tbucketNamesPerRegion, ok := resourcesCache[\"S3\"]\n\n\t\t\tif !ok {\n\t\t\t\tbucketNamesPerRegion, err = getAllS3Buckets(session, excludeAfter, targetRegions, \"\", s3Buckets.MaxConcurrentGetSize(), configObj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\n\t\t\t\tresourcesCache[\"S3\"] = make(map[string][]*string)\n\n\t\t\t\tfor bucketRegion, _ := range bucketNamesPerRegion {\n\t\t\t\t\tresourcesCache[\"S3\"][bucketRegion] = bucketNamesPerRegion[bucketRegion]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbucketNames, ok := resourcesCache[\"S3\"][region]\n\n\t\t\tif ok && len(bucketNames) > 0 {\n\t\t\t\ts3Buckets.Names = aws.StringValueSlice(bucketNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, s3Buckets)\n\t\t\t}\n\t\t}\n\t\t// End S3 Buckets\n\n\t\tif len(resourcesInRegion.Resources) > 0 {\n\t\t\taccount.Resources[region] = resourcesInRegion\n\t\t}\n\t\tcount++\n\t}\n\n\treturn &account, nil\n}", "func (bc *BasicLineGraph) GetMetaRegions() []*fidelpb.Region {\n\tbc.RLock()\n\tdefer bc.RUnlock()\n\treturn bc.Regions.GetMetaRegions()\n}", "func RestoreDefaultRegistryConfiguration() {\n\tregistryLock.Lock()\n\tdefer registryLock.Unlock()\n\tregistries = make(map[string]*RegistryEndpoint)\n\tfor k, v := range defaultRegistries {\n\t\tregistries[k] = v.DeepCopy()\n\t}\n}", "func (s *ListIndexesInput) SetRegions(v []*string) *ListIndexesInput {\n\ts.Regions = v\n\treturn s\n}", "func (e *cloudWatchExecutor) handleGetRegions(ctx context.Context, pluginCtx backend.PluginContext, parameters url.Values) ([]suggestData, error) {\n\tinstance, err := e.getInstance(ctx, pluginCtx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprofile := instance.Settings.Profile\n\tif cache, ok := e.regionCache.Load(profile); ok {\n\t\tif cache2, ok2 := cache.([]suggestData); ok2 {\n\t\t\treturn cache2, nil\n\t\t}\n\t}\n\n\tclient, err := e.getEC2Client(ctx, pluginCtx, defaultRegion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tregions := constants.Regions()\n\tec2Regions, err := client.DescribeRegions(&ec2.DescribeRegionsInput{})\n\tif err != nil {\n\t\t// ignore error for backward compatibility\n\t\tlogger.Error(\"Failed to get regions\", \"error\", err)\n\t} else {\n\t\tmergeEC2RegionsAndConstantRegions(regions, ec2Regions.Regions)\n\t}\n\n\tresult := make([]suggestData, 0)\n\tfor region := range regions {\n\t\tresult = append(result, suggestData{Text: region, Value: region, Label: region})\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].Text < result[j].Text\n\t})\n\te.regionCache.Store(profile, result)\n\n\treturn result, nil\n}", "func DefaultOptions() *Options {\n\treturn &Options{\n\t\tRegion: \"us-west-2\",\n\t\tAccessKey: os.Getenv(\"AWS_ACCESS_KEY_ID\"),\n\t\tAccessSecret: os.Getenv(\"AWS_SECRET_ACCESS_KEY\"),\n\t\tAccessToken: os.Getenv(\"AWS_SESSION_TOKEN\"),\n\t}\n}" ]
[ "0.67417514", "0.6694488", "0.6682156", "0.6320248", "0.6286656", "0.62777525", "0.624572", "0.6207566", "0.615566", "0.61505497", "0.60743976", "0.6033399", "0.6031638", "0.5974638", "0.59483427", "0.59098995", "0.59002", "0.58779293", "0.5810828", "0.57788986", "0.57502174", "0.5746598", "0.5733055", "0.5671107", "0.5640279", "0.56352663", "0.5617932", "0.55785924", "0.5542915", "0.55293715", "0.55128384", "0.5482461", "0.5479217", "0.54582953", "0.54416573", "0.5436406", "0.5434404", "0.54244757", "0.54208136", "0.54095787", "0.5387646", "0.53725314", "0.5338723", "0.5308622", "0.5286692", "0.5286312", "0.5283126", "0.5281634", "0.52765447", "0.52706945", "0.52340794", "0.5218863", "0.5215418", "0.52002585", "0.51955926", "0.5194801", "0.5187613", "0.5170705", "0.51698333", "0.5164479", "0.5160801", "0.5146841", "0.5143794", "0.51237607", "0.51214284", "0.51161087", "0.51145005", "0.51057583", "0.51022893", "0.50901544", "0.50848603", "0.50838494", "0.50785774", "0.5063689", "0.50524783", "0.5047421", "0.50412816", "0.50348496", "0.50094956", "0.50053144", "0.49769992", "0.49667907", "0.49542573", "0.49529305", "0.49470732", "0.4942844", "0.49143353", "0.4893258", "0.48914945", "0.48746046", "0.4863338", "0.48562068", "0.4855765", "0.48550525", "0.48509815", "0.48488006", "0.48455247", "0.48332068", "0.48331717", "0.48232508" ]
0.886901
0
trackConfigFileChanges monitors the host file using fsnotfiy
func trackConfigFileChanges(ctx context.Context, configFilePath string) { watcher, err := fsnotify.NewWatcher() if err != nil { logs.LogWithFields(ctx).Error(err.Error()) } err = watcher.Add(configFilePath) if err != nil { logs.LogWithFields(ctx).Error(err.Error()) } go func() { for { select { case fileEvent, ok := <-watcher.Events: if !ok { continue } if fileEvent.Op&fsnotify.Write == fsnotify.Write || fileEvent.Op&fsnotify.Remove == fsnotify.Remove { logs.LogWithFields(ctx).Info("modified file:" + fileEvent.Name) // update the host file addHost(ctx, configFilePath) } //Reading file to continue the watch watcher.Add(configFilePath) case err, _ := <-watcher.Errors: if err != nil { logs.LogWithFields(ctx).Error(err.Error()) defer watcher.Close() } } } }() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func watcher(configModel model.Config) {\n\t// Set the client variable\n\tconfig.Client = configModel.Client.Name\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer watcher.Close()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\tlogs.INFO.Println(\"Modified file -> \", event.Name)\n\t\t\t\t\t// When the file name has not been defined, it is time to\n\t\t\t\t\t// use the SetFile() method to add a new file to read.\n\t\t\t\t\tif filename == \"\" {\n\t\t\t\t\t\tstore.SetFile(event.Name)\n\t\t\t\t\t\tfilename = event.Name\n\t\t\t\t\t}\n\t\t\t\t\tif filename != \"\" && filename != event.Name {\n\t\t\t\t\t\tlogs.INFO.Println(\"Reset seek\")\n\t\t\t\t\t\tseek = 0\n\t\t\t\t\t}\n\t\t\t\t\treadLines(event.Name)\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlogs.CRITICAL.Println(\"Error on watcher: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\terr = watcher.Add(configModel.Pathlog.Name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t<-done\n}", "func watchConfig() {\n viper.WatchConfig()\n viper.OnConfigChange(func(e fsnotify.Event) {\n logrus.Info(\"Config file changed: %s\", e.Name)\n })\n}", "func (n *Notifier) configCheck() {\n\tlog.Infof(\"Checking for config changes...\")\n\n\ts := n.Source()\n\tlast := n.last\n\tnote, err := n.pullConfig(s)\n\tif err != nil && s == SourcePeer {\n\t\tlog.Errorf(\"Failed to pull configuration from peer: %v\", err)\n\t\tn.peerFailures++\n\t\tif n.peerFailures < n.engineCfg.MaxPeerConfigSyncErrors {\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Sync from peer failed %v times, falling back to config server\",\n\t\t\tn.engineCfg.MaxPeerConfigSyncErrors)\n\t\ts = SourceServer\n\t\tnote, err = n.pullConfig(s)\n\t}\n\tn.peerFailures = 0\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to pull configuration: %v\", err)\n\t\treturn\n\t}\n\n\tif s != SourceDisk && s != SourcePeer {\n\t\toldMeta := last.protobuf.Metadata\n\t\tnewMeta := note.protobuf.Metadata\n\t\tif oldMeta != nil && newMeta != nil && oldMeta.GetLastUpdated() > newMeta.GetLastUpdated() {\n\t\t\tlog.Infof(\"Ignoring out-of-date config from %v\", note.SourceDetail)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif note.Cluster.Equal(last.Cluster) {\n\t\tlog.Infof(\"No config changes found\")\n\t\treturn\n\t}\n\n\t// If there's only metadata differences, note it so we can skip some processing later.\n\toldCluster := *n.last.Cluster\n\toldCluster.Status = seesaw.ConfigStatus{}\n\tnewCluster := *note.Cluster\n\tnewCluster.Status = seesaw.ConfigStatus{}\n\tif newCluster.Equal(&oldCluster) {\n\t\tnote.MetadataOnly = true\n\t}\n\n\tnote.Cluster.Vservers = rateLimitVS(newCluster.Vservers, oldCluster.Vservers)\n\n\tlog.Infof(\"Sending config update notification\")\n\tselect {\n\tcase n.outgoing <- *note:\n\tdefault:\n\t\tlog.Warning(\"Config update channel is full. Skipped one config.\")\n\t\treturn\n\t}\n\tn.last = note\n\tlog.Infof(\"Sent config update notification\")\n\n\tif s != SourceDisk {\n\t\tif err := saveConfig(note.protobuf, n.engineCfg.ClusterFile, !note.MetadataOnly); err != nil {\n\t\t\tlog.Warningf(\"Failed to save config to %s: %v\", n.engineCfg.ClusterFile, err)\n\t\t}\n\t}\n}", "func updateConfigFile(context *cli.Context) {\n\tconfig, configFilename, err := lib.GetConfig(context)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif configFilename == \"\" {\n\t\tfmt.Println(\"Could not find a config file to update\")\n\t\treturn\n\t}\n\n\t// Same config in []byte format.\n\tconfigRaw, err := ioutil.ReadFile(configFilename)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Same config in map format so that we can detect missing keys.\n\tvar configMap map[string]interface{}\n\tif err = json.Unmarshal(configRaw, &configMap); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdirty := updateConfig(config, configMap)\n\n\tif dirty {\n\t\tconfig.ToFile(context)\n\t\tfmt.Printf(\"Wrote %s\\n\", configFilename)\n\t} else {\n\t\tfmt.Println(\"Nothing to update\")\n\t}\n}", "func ReadConfigFile(configPath string, monitor bool, logger log15.Logger) (*Config, error) {\n\tif !utils.PathExists(configPath) {\n\t\treturn nil, fmt.Errorf(\"The configuration file doesn't exist: %s\", configPath)\n\t}\n\n\tlogger.Info(\"Parsing configuration\", log15.Ctx{\"path\": configPath})\n\n\tconf := Config{logger: logger}\n\terr := parseConfig(configPath, &conf.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Watch for configuration changes\n\tif monitor {\n\t\tlogger.Info(\"Setting up configuration watch\", log15.Ctx{\"path\": configPath})\n\n\t\twatcher, err := fsnotify.NewWatcher()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup fsnotify: %v\", err)\n\t\t}\n\n\t\terr = watcher.Add(filepath.Dir(configPath))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup fsnotify watch: %v\", err)\n\t\t}\n\n\t\tpathDir := filepath.Dir(configPath)\n\t\tif pathDir == \"\" {\n\t\t\tpathDir = \"./\"\n\t\t}\n\t\tpathBase := filepath.Base(configPath)\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase ev := <-watcher.Events:\n\t\t\t\t\tif ev.Name != fmt.Sprintf(\"%s/%s\", pathDir, pathBase) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store the old config for comparison\n\t\t\t\t\toldData, _ := yaml.Marshal(conf.Config)\n\n\t\t\t\t\t// Wait for 1s for ownership changes\n\t\t\t\t\ttime.Sleep(time.Second)\n\n\t\t\t\t\t// Parse the new ocnfig\n\t\t\t\t\terr := parseConfig(configPath, conf.Config)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error(\"Failed to read the new configuration\", log15.Ctx{\"path\": configPath, \"error\": err})\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check if something changed\n\t\t\t\t\tnewData, _ := yaml.Marshal(conf.Config)\n\t\t\t\t\tif string(oldData) == string(newData) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tlogger.Info(\"Configuration file changed, reloading\", log15.Ctx{\"path\": configPath})\n\t\t\t\t\tfor _, handler := range conf.handlers {\n\t\t\t\t\t\thandler(&conf)\n\t\t\t\t\t}\n\t\t\t\tcase err := <-watcher.Errors:\n\t\t\t\t\tlogger.Error(\"Got bad file notification\", log15.Ctx{\"error\": err})\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn &conf, nil\n}", "func (fc *FilterConfig) initFsnotifyEventHandler() {\n\tconst pauseDelay = 5 * time.Second // used to let all changes be done before reloading the file\n\tgo func() {\n\t\ttimer := time.NewTimer(0)\n\t\tdefer timer.Stop()\n\t\tfirstTime := true\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tif firstTime {\n\t\t\t\t\tfirstTime = false\n\t\t\t\t} else {\n\t\t\t\t\tfc.reloadFile()\n\t\t\t\t}\n\t\t\tcase <-fc.watcher.Events:\n\t\t\t\ttimer.Reset(pauseDelay)\n\t\t\tcase err := <-fc.watcher.Errors:\n\t\t\t\tgoglog.Logger.Errorf(\"ip2location: %s\", err.Error())\n\t\t\tcase <-fc.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func initFileWatcher(configFilePath string) {\n\tvar err error\n\twatcher, err = fsnotify.NewWatcher()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Unable To Setup Logging Config File Watcher: %v\", err))\n\t}\n\tstartWatchListener(configFilePath)\n}", "func monitorLocalChanges(rootdir string, cafile string, server string, listFileInProcess *ListFileInProcess) {\n\tfmt.Println(\"*** Recursively monitoring folder\", rootdir)\n\twatcher, err := watch.NewWatcher(rootdir, hasher.PROCESSING_DIR)\n\t//watcher, err := watch.NewRecursiveWatcher(rootdir, hasher.PROCESSING_DIR)\n\tif err != nil {\n\t\tlog.Println(\"Watcher create error : \", err)\n\t}\n\tdefer watcher.Close()\n\t_done := make(chan bool)\n\n\tgo func() {\n\t\twatcher.start()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Create == fsnotify.Create:\n\t\t\t\t\tfi, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// eg. stat .subl513.tmp : no such file or directory\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if fi.IsDir() {\n\t\t\t\t\t\tfmt.Println(\"Detected new directory\", event.Name)\n\t\t\t\t\t\tif !watch.ShouldIgnoreFile(filepath.Base(event.Name), hasher.PROCESSING_DIR) {\n\t\t\t\t\t\t\tfmt.Println(\"Monitoring new folder...\")\n\t\t\t\t\t\t\twatcher.AddFolder(event.Name)\n\t\t\t\t\t\t\tconnsender := connectToServer(cafile, server)\n\t\t\t\t\t\t\tgo sendClientFolderChanges(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t\t\t//watcher.Folders <- event.Name\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(\"Detected new file, for now do nothing\", event.Name)\n\t\t\t\t\t\t// watcher.Files <- event.Name // created a file\n\t\t\t\t\t\t// TODO\n\t\t\t\t\t}\n\n\t\t\t\tcase event.Op&fsnotify.Write == fsnotify.Write:\n\t\t\t\t\t// modified a file, assuming that you don't modify folders\n\t\t\t\t\tfmt.Println(\"Detected file modification\", event.Name)\n\t\t\t\t\t// Don't handle folder change, since they receive notification\n\t\t\t\t\t// when a file they contain is changed\n\t\t\t\t\tfi, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif fi.Mode().IsRegular() {\n\t\t\t\t\t\t// watcher.Files <- event.Name\n\t\t\t\t\t\tlog.Println(\"Modified file: \", event.Name)\n\t\t\t\t\t\t// connsender := connectToServer(cafile, server)\n\t\t\t\t\t\t// go sendClientChanges(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove == fsnotify.Remove:\n\t\t\t\t\tlog.Println(\"Removed file: \", event.Name)\n\t\t\t\t\t// connsender := connectToServer(cafile, server)\n\t\t\t\t\t// go sendClientDelete(connsender, event.Name, listFileInProcess)\n\t\t\t\tcase event.Op&fsnotify.Rename == fsnotify.Rename:\n\t\t\t\t\tlog.Println(\"Renamed file: \", event.Name)\n\t\t\t\t\t// The following is to handle an issue in fsnotify\n\t\t\t\t\t// On rename, fsnotify sends three events on linux: RENAME(old), CREATE(new), RENAME(new)\n\t\t\t\t\t// fsnotify sends two events on windows: RENAME(old), CREATE(new)\n\t\t\t\t\t// The way we handle this is:\n\t\t\t\t\t// 1. If there is a second rename, skip it\n\t\t\t\t\t// 2. When the first rename happens, remove old file/folder\n\t\t\t\t\t// 3. We'll re-add it when the new create comes in\n\t\t\t\t\t// Step 2 and 3 might be optimized later by remembering which was old/new and performing simple move\n\t\t\t\t\t_, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Rename talks about a file/folder now gone, send a remove request to server\n\t\t\t\t\t\tlog.Println(\"Rename leading to delete\", event.Name)\n\t\t\t\t\t\tconnsender := connectToServer(cafile, server)\n\t\t\t\t\t\tgo sendClientDelete(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Rename talks about a file/folder already existing, skip it (do nothing)\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Chmod == fsnotify.Chmod:\n\t\t\t\t\tlog.Println(\"File changed permission: \", event.Name)\n\t\t\t\t}\n\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Println(\"Watcher watching error : \", err)\n\t\t\t\t_done <- true\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\n\t}()\n\n\t<-_done\n}", "func (uc *Userclient) iMonitorLocalChanges() {\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase ev := <-uc.watcher.Event:\r\n\t\t\tif ev.IsCreate() {\r\n\t\t\t\t//Making the key at which to store the Syncfile.\r\n\t\t\t\t//First, take the path (given by watcher.Event) and parse out the /'s to replace with ?'s\r\n\t\t\t\tpatharray := strings.Split(ev.Name, \"/\")\r\n\t\t\t\tfoundWhite := false\r\n\t\t\t\t//if for some resaons Whiteboard is in the path, take it out and all prefix\r\n\t\t\t\tvar i int\r\n\t\t\t\tfor i = 0; foundWhite == false && i < len(patharray); i++ {\r\n\t\t\t\t\tif patharray[i] == \"whiteboard\" {\r\n\t\t\t\t\t\tfoundWhite = true\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t//If it wasn't...reset i\r\n\t\t\t\tif foundWhite == false {\r\n\t\t\t\t\ti = 0\r\n\t\t\t\t}\r\n\t\t\t\t// The key is user:class?path to file (delimited by ?'s')\r\n\t\t\t\tintermed := strings.Join(patharray[i:], \"?\")\r\n\t\t\t\tclass := patharray[i]\r\n\t\t\t\tif class == \".permkey\" {\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t\tfmt.Println(\"Class \", class)\r\n\t\t\t\tkey := fmt.Sprintf(\"%v:%v\", uc.user.Username, intermed)\r\n\r\n\t\t\t\t//Changing directory madness starts here\r\n\t\t\t\t//cos apparently you have to be ni that directory (parameter is filename, not filepath)\r\n\t\t\t\t<-uc.wdChangeMutex\r\n\t\t\t\tpwd, _ := os.Getwd()\r\n\t\t\t\tfmt.Printf(\"WD %v for %v\\n\", pwd, ev.Name)\r\n\t\t\t\tfor j := i; j < len(patharray)-1; j++ {\r\n\t\t\t\t\tcdErr := os.Chdir(patharray[j])\r\n\t\t\t\t\tif cdErr != nil {\r\n\t\t\t\t\t\tfmt.Println(\"Couldn't cd into \", patharray[j])\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfile, fileErr := os.Open(patharray[len(patharray)-1])\r\n\t\t\t\tif fileErr != nil {\r\n\t\t\t\t\tfmt.Println(\"Fail \", patharray[len(patharray)-1])\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\r\n\t\t\t\texistSyncFile := uc.iGet(key)\r\n\t\t\t\tvar permissions map[string]int\r\n\r\n\t\t\t\t//if it already exists, we're just copying it over from server (don't overwrite server)\r\n\t\t\t\tif existSyncFile == nil { //if it doesn't exist\r\n\t\t\t\t\t//Make the sync file to store\r\n\t\t\t\t\tfi, statErr := file.Stat()\r\n\t\t\t\t\tif statErr != nil {\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpermissions = make(map[string]int)\r\n\t\t\t\t\tpermissions[uc.user.Username] = storageproto.WRITE\r\n\t\t\t\t\tvar files []string\r\n\t\t\t\t\tif fi.IsDir() {\r\n\t\t\t\t\t\tfiles = []string{}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tfiles = nil\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t//Finding content of file\r\n\t\t\t\t\tbuffer := bytes.NewBuffer(make([]byte, 0))\r\n\t\t\t\t\t<-uc.permkeyFileMutex\r\n\t\t\t\t\treader := bufio.NewReader(file)\r\n\t\t\t\t\tfor {\r\n\t\t\t\t\t\tline, _, readErr := reader.ReadLine()\r\n\t\t\t\t\t\tif readErr != nil {\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbuffer.Write(line)\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t\tuc.permkeyFileMutex <- 1\r\n\r\n\t\t\t\t\tsyncFile := &storageproto.SyncFile{Owner: uc.user, Class: class, UpdateTime: time.Now().Nanosecond(), Contents: buffer.Bytes(), Files: files, Permissions: permissions, Synced: true}\r\n\r\n\t\t\t\t\t//Give to midclient\r\n\t\t\t\t\tuc.iPush(key, syncFile)\r\n\t\t\t\t\t//Get parent to add to Files list\r\n\t\t\t\t\tparentfilepath := uc.homedir + \"/\" + strings.Join(patharray[:(len(patharray)-1)], \"/\")\r\n\t\t\t\t\t<-uc.fileKeyMutex\r\n\t\t\t\t\t//parent has to be in map...otherwise this would make literally 0 sense\r\n\t\t\t\t\tparentkeyperm, _ := uc.fileKeyMap[parentfilepath]\r\n\t\t\t\t\tfmt.Println(\"My parent: \", parentfilepath)\r\n\t\t\t\t\tuc.fileKeyMutex <- 1\r\n\t\t\t\t\tparentSync := uc.iGet(parentkeyperm.Key)\r\n\t\t\t\t\tif parentSync != nil {\r\n\t\t\t\t\t\tparentSync.Files = append(parentSync.Files, key)\r\n\t\t\t\t\t\tuc.iPush(parentkeyperm.Key, parentSync)\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tpermissions = existSyncFile.Permissions\r\n\t\t\t\t}\r\n\t\t\t\t//cd back to whiteboard/\r\n\t\t\t\tfor j := i; j < len(patharray)-1; j++ {\r\n\t\t\t\t\tos.Chdir(\"..\")\r\n\t\t\t\t}\r\n\t\t\t\tfile.Close()\r\n\r\n\t\t\t\t//also add to file\r\n\t\t\t\t<-uc.permkeyFileMutex\r\n\t\t\t\ttoFile := fmt.Sprintf(\"%v %v %v:%v\\n\", ev.Name, key, uc.user.Username, storageproto.WRITE)\r\n\t\t\t\t_, writeErr := uc.permkeyFile.WriteString(toFile)\r\n\t\t\t\tif writeErr != nil {\r\n\t\t\t\t\tfmt.Println(\"Write error!\")\r\n\t\t\t\t}\r\n\t\t\t\tuc.permkeyFileMutex <- 1\r\n\r\n\t\t\t\t//Hash for easy access later\r\n\t\t\t\tuc.fileKeyMap[ev.Name] = KeyPermissions{key, permissions}\r\n\r\n\t\t\t\tuc.wdChangeMutex <- 1\r\n\t\t\t\tfmt.Printf(\"Create Event: %v\\n\", ev)\r\n\t\t\t} else if ev.IsModify() {\r\n\r\n\t\t\t} else if ev.IsDelete() {\r\n\t\t\t\tfmt.Printf(\"Delete Event: %v\\n\", ev)\r\n\t\t\t} else if ev.IsRename() {\r\n\t\t\t\tfmt.Printf(\"Rename Event: %v\\n\", ev)\r\n\t\t\t}\r\n\t\tcase err := <-uc.watcher.Error:\r\n\t\t\tfmt.Println(\"File error: \", err)\r\n\t\t}\r\n\t}\r\n}", "func (plugin *PluginConfig) watch(inChan utils.InputChannel) (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tutils.Logger.Errorf(\"File input plugin watch error %s\", err)\n\t\t}\n\t}()\n\n\tvar (\n\t\tallfiles = make([]string, 0)\n\t\tfi os.FileInfo\n\t)\n\n\tif err = plugin.loadSinceDB(); err != nil {\n\t\tutils.Logger.Errorf(\"loadSinceDB return error %s\", err)\n\t\treturn\n\t}\n\n\tif len(plugin.DirsPath) < 1 {\n\t\tutils.Logger.Errorf(\"No director need to watch.\")\n\t\treturn\n\t}\n\n\t// find all log file path.\n\tfor _, dir := range plugin.DirsPath {\n\t\tfl, err := utils.FileList(dir, plugin.FileType)\n\t\tif err != nil {\n\t\t\tutils.Logger.Errorln(err)\n\t\t}\n\t\tallfiles = append(allfiles, fl...)\n\t}\n\n\t// loop save sincdb\n\tgo func() {\n\t\tplugin.wgExit.Add(1)\n\t\tdefer plugin.wgExit.Done()\n\n\t\tfor plugin.running {\n\t\t\ttime.Sleep(time.Duration(plugin.Intervals) * time.Second)\n\t\t\tif err = plugin.checkAndSaveSinceDB(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor _, fp := range allfiles {\n\t\t// get all sysmlinks.\n\t\tif fp, err = filepath.EvalSymlinks(fp); err != nil {\n\t\t\tutils.Logger.Warnf(\"Get symlinks failed: %s error %s\", fp, err)\n\t\t\tcontinue\n\t\t}\n\t\t// check file status.\n\t\tif fi, err = os.Stat(fp); err != nil {\n\t\t\tutils.Logger.Warnf(\"Get file status %s error %s\", fp, err)\n\t\t\tcontinue\n\t\t}\n\t\t// skip directory\n\t\tif fi.IsDir() {\n\t\t\tutils.Logger.Warnf(\"Skipping directory %s\", fi.Name())\n\t\t\tcontinue\n\t\t}\n\t\t// monitor file.\n\t\tutils.Logger.Info(\"Watching \", fp)\n\t\treadEventChan := make(chan fsnotify.Event, 10)\n\t\tgo plugin.loopRead(readEventChan, fp, inChan)\n\t\tgo plugin.loopWatch(readEventChan, fp, fsnotify.Create|fsnotify.Write)\n\t}\n\n\treturn\n}", "func (n *ntpService) NtpConfigFile(serverNames []string) {\n\ttmpl, err := template.New(\"test\").Parse(chronydConfigFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// if we are given a DNS name, we should expand it because it could be a pool name\n\t// like pool.ntp.org and chronyc does not support adding pools, so it would treat it\n\t// as a single server, which is not good for accuracy and redundancy.\n\tvar servers []string\n\tfor _, n := range serverNames {\n\t\taddrs, err := net.LookupHost(n)\n\t\tif err == nil {\n\t\t\tservers = append(servers, addrs...)\n\t\t} else {\n\t\t\tservers = append(servers, n)\n\t\t}\n\t}\n\tnc := ntpParams{NtpServer: servers}\n\tf, err := n.openFile(globals.NtpConfigFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Errorln(\"Unable to create ntp config file: \", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\tvar buf bytes.Buffer\n\tw := io.MultiWriter(f, &buf)\n\terr = tmpl.Execute(w, nc)\n\tif err != nil {\n\t\tlog.Errorf(\"error %v while writing to ntp config file\", err)\n\t\treturn\n\t}\n\tlog.Infof(\"Updated NTP config files: %v\", buf.String())\n\tn.restartNtpd()\n}", "func configNotify(event config.Event, source config.Source) error {\n\tlog.Info(\"instrumentation configuration is now %v\", opt)\n\n\tlog.Info(\"reconfiguring...\")\n\tif err := svc.reconfigure(); err != nil {\n\t\tlog.Error(\"failed to restart instrumentation: %v\", err)\n\t}\n\n\treturn nil\n}", "func (cm *PollingProjectConfigManager) SyncConfig(datafile []byte) {\n\tvar e error\n\tvar code int\n\tif len(datafile) == 0 {\n\t\tdatafile, code, e = cm.requester.Get()\n\n\t\tif e != nil {\n\t\t\tcmLogger.Error(fmt.Sprintf(\"request returned with http code=%d\", code), e)\n\t\t}\n\t}\n\n\tprojectConfig, err := datafileprojectconfig.NewDatafileProjectConfig(datafile)\n\tif err != nil {\n\t\tcmLogger.Error(\"failed to create project config\", err)\n\t}\n\n\tcm.configLock.Lock()\n\tif cm.projectConfig != nil {\n\t\tif cm.projectConfig.GetRevision() == projectConfig.GetRevision() {\n\t\t\tcmLogger.Debug(fmt.Sprintf(\"No datafile updates. Current revision number: %s\", cm.projectConfig.GetRevision()))\n\t\t} else {\n\t\t\tcmLogger.Debug(fmt.Sprintf(\"Received new datafile and updated config. Old revision number: %s. New revision number: %s\", cm.projectConfig.GetRevision(), projectConfig.GetRevision()))\n\t\t\tcm.projectConfig = projectConfig\n\n\t\t\tif cm.notificationCenter != nil {\n\t\t\t\tprojectConfigUpdateNotification := notification.ProjectConfigUpdateNotification{\n\t\t\t\t\tType: notification.ProjectConfigUpdate,\n\t\t\t\t\tRevision: cm.projectConfig.GetRevision(),\n\t\t\t\t}\n\t\t\t\tif err = cm.notificationCenter.Send(notification.ProjectConfigUpdate, projectConfigUpdateNotification); err != nil {\n\t\t\t\t\tcmLogger.Warning(\"Problem with sending notification\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tcm.projectConfig = projectConfig\n\t}\n\tcm.err = err\n\tcm.configLock.Unlock()\n}", "func logConfig(myid int, myConf *Config) {\n\tvar conf MyConfig\n\tfile, _ := os.Open(\"config/log_config.json\")\n\tdecoder := json.NewDecoder(file)\n\terr := decoder.Decode(&conf)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\n\tfoundMyId := false\n\t//initializing config structure from jason file.\n\tfor _, srv := range conf.Details {\n\t\tif srv.Id == myid {\n\t\t\tfoundMyId = true\n\t\t\tmyConf.Id = myid\n\t\t\tmyConf.LogDir = srv.LogDir\n\t\t\tmyConf.ElectionTimeout = srv.ElectionTimeout\n\t\t\tmyConf.HeartbeatTimeout = srv.HeartbeatTimeout\n\t\t}\n\t}\n\tif !foundMyId {\n\t\tfmt.Println(\"Expected this server's id (\\\"%d\\\") to be present in the configuration\", myid)\n\t}\n}", "func handleConfigurationChangeEvent(event cloudevents.Event, shkeptncontext string, data *keptnevents.ConfigurationChangeEventData, logger *keptnutils.Logger) error {\n\tlogger.Info(fmt.Sprintf(\"Handling Configuration Changed Event: %s\", event.Context.GetID()));\n\n\treturn nil\n}", "func (p *Patch) ConfigChanged(remotePath string) bool {\n\tfor _, patchPart := range p.Patches {\n\t\tif patchPart.ModuleName == \"\" {\n\t\t\tfor _, summary := range patchPart.PatchSet.Summary {\n\t\t\t\tif summary.Name == remotePath {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (p *Patch) ConfigChanged(remotePath string) bool {\n\tfor _, patchPart := range p.Patches {\n\t\tif patchPart.ModuleName == \"\" {\n\t\t\tfor _, summary := range patchPart.PatchSet.Summary {\n\t\t\t\tif summary.Name == remotePath {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func TriggerRefresh(client *docker.Client, logstashEndpoint string, configFile string) {\n\tdefer utils.TimeTrack(time.Now(), \"Config generation\")\n\n\tlog.Debug(\"Generating configuration...\")\n\tforwarderConfig := getConfig(logstashEndpoint, configFile)\n\n\tcontainers, err := client.ListContainers(docker.ListContainersOptions{All: false})\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve container list from docker: %s\", err)\n\t}\n\n\tlog.Debug(\"Found %d containers:\", len(containers))\n\tfor i, c := range containers {\n\t\tlog.Debug(\"%d. %s\", i+1, c.ID)\n\n\t\tcontainer, err := client.InspectContainer(c.ID)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to inspect container %s: %s\", c.ID, err)\n\t\t}\n\n\t\tforwarderConfig.AddContainerLogFile(container)\n\n\t\tcontainerConfig, err := config.NewFromContainer(container)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tlog.Error(\"Unable to look for logstash-forwarder config in %s: %s\", container.ID, err)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, file := range containerConfig.Files {\n\t\t\t\tfile.Fields[\"host\"] = container.Config.Hostname\n\t\t\t\tforwarderConfig.Files = append(forwarderConfig.Files, file)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst configPath = \"/tmp/logstash-forwarder.conf\"\n\tfo, err := os.Create(configPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to open %s: %s\", configPath, err)\n\t}\n\tdefer fo.Close()\n\n\tj, err := json.MarshalIndent(forwarderConfig, \"\", \" \")\n\tif err != nil {\n\t\tlog.Debug(\"Unable to MarshalIndent logstash-forwarder config: %s\", err)\n\t}\n\t_, err = fo.Write(j)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to write logstash-forwarder config to %s: %s\", configPath, err)\n\t}\n\tlog.Info(\"Wrote logstash-forwarder config to %s\", configPath)\n\n\tif running {\n\t\tlog.Info(\"Waiting for logstash-forwarder to stop\")\n\t\t// perhaps use SIGTERM first instead of just Kill()?\n\t\t//\t\tif err := cmd.Process.Signal(syscall.SIGTERM); err != nil {\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\tlog.Error(\"Unable to stop logstash-forwarder\")\n\t\t}\n\t\tif _, err := cmd.Process.Wait(); err != nil {\n\t\t\tlog.Error(\"Unable to wait for logstash-forwarder to stop: %s\", err)\n\t\t}\n\t\tlog.Info(\"Stopped logstash-forwarder\")\n\t}\n\tcmd = exec.Command(\"logstash-forwarder\", \"-config\", configPath)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatalf(\"Unable to start logstash-forwarder: %s\", err)\n\t}\n\trunning = true\n\tlog.Info(\"Starting logstash-forwarder...\")\n}", "func TestConfigChangeEvents(t *testing.T) {\n\tif err := testcert.GenerateCert(\"mail2.guerrillamail.com\", \"\", 365*24*time.Hour, false, 2048, \"P256\", \"./tests/\"); err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := deleteIfExists(\"../tests/mail2.guerrillamail.com.cert.pem\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := deleteIfExists(\"../tests/mail2.guerrillamail.com.key.pem\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\toldconf := &AppConfig{}\n\tif err := oldconf.Load([]byte(configJsonA)); err != nil {\n\t\tt.Error(err)\n\t}\n\tlogger, _ := log.GetLogger(oldconf.LogFile, oldconf.LogLevel)\n\tbcfg := backends.BackendConfig{\"log_received_mails\": true}\n\tbackend, err := backends.New(bcfg, logger)\n\tif err != nil {\n\t\tt.Error(\"cannot create backend\", err)\n\t}\n\tapp, err := New(oldconf, backend, logger)\n\tif err != nil {\n\t\tt.Error(\"cannot create daemon\", err)\n\t}\n\t// simulate timestamp change\n\n\ttime.Sleep(time.Second + time.Millisecond*500)\n\tif err := os.Chtimes(oldconf.Servers[1].TLS.PrivateKeyFile, time.Now(), time.Now()); err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := os.Chtimes(oldconf.Servers[1].TLS.PublicKeyFile, time.Now(), time.Now()); err != nil {\n\t\tt.Error(err)\n\t}\n\tnewconf := &AppConfig{}\n\tif err := newconf.Load([]byte(configJsonB)); err != nil {\n\t\tt.Error(err)\n\t}\n\tnewconf.Servers[0].LogFile = log.OutputOff.String() // test for log file change\n\tnewconf.LogLevel = log.InfoLevel.String()\n\tnewconf.LogFile = \"off\"\n\texpectedEvents := map[Event]bool{\n\t\tEventConfigPidFile: false,\n\t\tEventConfigLogFile: false,\n\t\tEventConfigLogLevel: false,\n\t\tEventConfigAllowedHosts: false,\n\t\tEventConfigServerNew: false, // 127.0.0.1:4654 will be added\n\t\tEventConfigServerRemove: false, // 127.0.0.1:9999 server removed\n\t\tEventConfigServerStop: false, // 127.0.0.1:3333: server (disabled)\n\t\tEventConfigServerLogFile: false, // 127.0.0.1:2526\n\t\tEventConfigServerLogReopen: false, // 127.0.0.1:2527\n\t\tEventConfigServerTimeout: false, // 127.0.0.1:2526 timeout\n\t\t//\"server_change:tls_config\": false, // 127.0.0.1:2526\n\t\tEventConfigServerMaxClients: false, // 127.0.0.1:2526\n\t\tEventConfigServerTLSConfig: false, // 127.0.0.1:2527 timestamp changed on certificates\n\t}\n\ttoUnsubscribe := map[Event]func(c *AppConfig){}\n\ttoUnsubscribeSrv := map[Event]func(c *ServerConfig){}\n\n\tfor event := range expectedEvents {\n\t\t// Put in anon func since range is overwriting event\n\t\tfunc(e Event) {\n\t\t\tif strings.Contains(e.String(), \"config_change\") {\n\t\t\t\tf := func(c *AppConfig) {\n\t\t\t\t\texpectedEvents[e] = true\n\t\t\t\t}\n\t\t\t\t_ = app.Subscribe(event, f)\n\t\t\t\ttoUnsubscribe[event] = f\n\t\t\t} else {\n\t\t\t\t// must be a server config change then\n\t\t\t\tf := func(c *ServerConfig) {\n\t\t\t\t\texpectedEvents[e] = true\n\t\t\t\t}\n\t\t\t\t_ = app.Subscribe(event, f)\n\t\t\t\ttoUnsubscribeSrv[event] = f\n\t\t\t}\n\n\t\t}(event)\n\t}\n\n\t// emit events\n\tnewconf.EmitChangeEvents(oldconf, app)\n\t// unsubscribe\n\tfor unevent, unfun := range toUnsubscribe {\n\t\t_ = app.Unsubscribe(unevent, unfun)\n\t}\n\tfor unevent, unfun := range toUnsubscribeSrv {\n\t\t_ = app.Unsubscribe(unevent, unfun)\n\t}\n\tfor event, val := range expectedEvents {\n\t\tif val == false {\n\t\t\tt.Error(\"Did not fire config change event:\", event)\n\t\t\tt.FailNow()\n\t\t}\n\t}\n\n\t// don't forget to reset\n\tif err := os.Truncate(oldconf.LogFile, 0); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (app *application) initConfFromFile() {\n\n\tvar fp confFileContent\n\n\tapp.infoLog.Printf(\"Reading config parameters from %s\", app.confFile)\n\tfdata, err := ioutil.ReadFile(app.confFile)\n\tif err != nil {\n\t\tapp.errorLog.Printf(\"Reading file %s failed err=%v\\n\", app.confFile, err)\n\t\treturn\n\t}\n\terr = json.Unmarshal(fdata, &fp)\n\tif err != nil {\n\t\tapp.errorLog.Printf(\"Unmarshal err=%v\\n\", err)\n\t\treturn\n\t}\n\n\tif (app.basicAuthUser != fp.BasicAuthUser) || (app.basicAuthPW != fp.BasicAuthPW) {\n\t\tapp.changeBasicAuth(fp.BasicAuthUser, fp.BasicAuthPW)\n\t}\n\n\tif app.debugEnabled != fp.DebugEnabled {\n\t\tapp.debugEnabled = fp.DebugEnabled\n\t\tapp.infoLog.Printf(\"Changing debug to %v\", app.debugEnabled)\n\t\tapp.debLog.SetOutput(ioutil.Discard)\n\t\tif app.debugEnabled {\n\t\t\tapp.debLog.SetOutput(app.logFile)\n\t\t}\n\t}\n\n\t// if (app.iptTbl != fp.IptTbl) && (fp.IptTbl != \"filter\") {\n\t// \tapp.errorLog.Printf(\"WARNING Change of iptables table value is not supported and this will break things - old table=%v, new table=%v\\n\", app.iptTbl, fp.IptTbl)\n\t// }\n\t// app.iptTbl = fp.IptTbl\n\n\tdel, crea := checkDiffChains(app.iptChains, fp.IptChains)\n\tif len(crea) > 0 {\n\t\tfor _, chain := range crea {\n\t\t\terr = app.ipt.NewChain(app.iptTbl, chain)\n\t\t\tif err != nil {\n\t\t\t\t// app.infoLog.Printf(\"Could not create chain=%s in table=%s; trying ClearChain\", chain, app.iptTbl)\n\t\t\t\terr = app.ipt.ClearChain(app.iptTbl, chain)\n\t\t\t\tif err != nil {\n\t\t\t\t\tapp.errorLog.Printf(\"ClearChain of chain=%s in table=%s failed: %v\\n\", chain, app.iptTbl, err)\n\t\t\t\t\tapp.errorLog.Println(\"Could not create and clear chain in table\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tapp.infoLog.Printf(\"Created (or cleared) chain=%s in table=%s\", chain, app.iptTbl)\n\t\t}\n\t}\n\tif len(del) > 0 {\n\t\tfor _, chain := range del {\n\t\t\terr = app.ipt.ClearChain(app.iptTbl, chain)\n\t\t\tif err != nil {\n\t\t\t\tapp.errorLog.Printf(\"ClearChain of chain=%s in table=%s failed: %v\\n\", chain, app.iptTbl, err)\n\t\t\t\tapp.errorLog.Println(\"Cannot delete chain in table\")\n\t\t\t}\n\t\t\terr = app.ipt.DeleteChain(app.iptTbl, chain)\n\t\t\tif err != nil {\n\t\t\t\tapp.errorLog.Printf(\"DeleteChain of chain=%s in table=%s failed: %v\\n\", chain, app.iptTbl, err)\n\t\t\t}\n\t\t\tapp.infoLog.Printf(\"Deleted chain=%s in table=%s\", chain, app.iptTbl)\n\t\t}\n\t}\n\tapp.iptChains = fp.IptChains\n\n\tapp.certFile = fp.CertFile\n\tapp.keyFile = fp.KeyFile\n\t// app.srv.Addr = fp.SrvAddr\n\tapp.srv.MaxHeaderBytes = fp.SrvMaxHeaderBytes\n\tapp.srv.IdleTimeout = fp.SrvIdleTimeout.Duration\n\tapp.srv.ReadHeaderTimeout = fp.SrvReadTimeout.Duration\n\tapp.srv.WriteTimeout = fp.SrvWriteTimeout.Duration\n\tapp.srv.TLSConfig.MinVersion = tls.VersionTLS12 // defaults to 1.2\n\tif fp.TLSMinVersion == \"1.3\" {\n\t\tapp.srv.TLSConfig.MinVersion = tls.VersionTLS13\n\t}\n}", "func loadConfigFile() {\n\tf, err := os.Open(confPath)\n\tif err != nil {\n\t\tnotify(\"Error: failed to load configuration file (./config.json). \"+err.Error(), config.Devtopic, config.Devtopicregion)\n\t\tlog.Fatal(errors.New(\"Error: failed to load configuration file (./config.json). \" + err.Error()))\n\t\treturn\n\t}\n\td := json.NewDecoder(f)\n\terr = d.Decode(&config)\n\tif err != nil {\n\t\tnotify(\"Error: failed to configure server. \"+err.Error(), config.Devtopic, config.Devtopicregion)\n\t\tlog.Fatal(errors.New(\"Error: failed to configure server. \" + err.Error()))\n\t\treturn\n\t}\n\tif config.Forecastdays > 5 {\n\t\tnotify(\"Error: Forecastdays cannot exceed 5 days, setting to 5\", config.Devtopic, config.Devtopicregion)\n\t\tlog.Println(\"Forecastdays cannot exceed 5 days, setting to 5\")\n\t\tconfig.Forecastdays = 5\n\t}\n\n}", "func setConfigFile(etcdConf *embetcd.Config, max int, min int, check int) (configFilePath string, tempDir string) {\n\t// get a temporary directory for the etcd data directory\n\ttempDir, err := ioutil.TempDir(\"\", \"TestProxyCluster\")\n\tSo(err, ShouldBeNil)\n\tSo(os.RemoveAll(tempDir), ShouldBeNil)\n\n\t// get a temporary filename for the config file\n\tfileObj, err := ioutil.TempFile(\"\", \"TestProxyClusterConfig\")\n\tSo(err, ShouldBeNil)\n\tconfigFilePath = fileObj.Name()\n\t// remove the temp file so we can overwrite it\n\tSo(os.Remove(configFilePath), ShouldBeNil)\n\n\t//// remove the temp dir so we can recreate it\n\n\tproxyConf := configEtcd\n\tproxyConf = strings.Replace(proxyConf, \"<<MAX>>\", strconv.FormatInt(int64(max), 10), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<MIN>>\", strconv.FormatInt(int64(min), 10), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<CHECK>>\", strconv.FormatInt(int64(check), 10), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<LPADDRESS>>\", etcdConf.LPUrls[0].String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<APADDRESS>>\", etcdConf.APUrls[0].String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<LCADDRESS>>\", etcdConf.LCUrls[0].String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<ACADDRESS>>\", etcdConf.ACUrls[0].String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<MADDRESS>>\", etcdConf.ListenMetricsUrls[0].String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<UNHEALTHYTTL>>\", etcdConf.UnhealthyTTL.String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<REMOVEMEMBERTIMEOUT>>\", etcdConf.RemoveMemberTimeout.String(), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<DATADIR>>\", filepath.Join(tempDir, etcdConf.Dir), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<CLUSTEROP>>\", etcdConf.ClusterState, -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<TARGETADDRESSES>>\", formatTargetAddresses(etcdConf.InitialCluster), -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<SERVERNAME>>\", etcdConf.Name, -1)\n\tproxyConf = strings.Replace(proxyConf, \"<<CLUSTERNAME>>\", etcdConf.ClusterName, -1)\n\n\tSo(ioutil.WriteFile(path.Join(configFilePath), []byte(proxyConf), os.FileMode(0666)), ShouldBeNil)\n\treturn configFilePath, tempDir\n}", "func (lf *logFile) sync() error {\n\treturn fileutil.Fsync(lf.fd)\n}", "func (m *resmgr) setConfigFromFile(path string) error {\n\tm.Info(\"applying new configuration from file %s...\", path)\n\treturn m.setConfig(path)\n}", "func (c *anypointClient) OnConfigChange(mulesoftConfig *config.MulesoftConfig) {\n\tif c.auth != nil {\n\t\tc.auth.Stop()\n\t}\n\n\tc.baseURL = mulesoftConfig.AnypointExchangeURL\n\tc.username = mulesoftConfig.Username\n\tc.password = mulesoftConfig.Password\n\tc.lifetime = mulesoftConfig.SessionLifetime\n\tc.apiClient = coreapi.NewClient(mulesoftConfig.TLS, mulesoftConfig.ProxyURL)\n\t// TODO add to config\n\tc.cache = loadOrCreateCache(mulesoftConfig.CachePath+\"/anypoint.cache\")\n\n\tvar err error\n\tc.auth, err = NewAuth(c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to authenticate: %s\", err.Error())\n\t}\n\n\tc.environment, err = c.GetEnvironmentByName(mulesoftConfig.Environment)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to connect to Mulesoft environment %s: %s\", mulesoftConfig.Environment, err.Error())\n\t}\n}", "func (a *Agent) onConfigChange() {\n\tcfg := config.GetConfig()\n\n\t// Stop Discovery & Publish\n\ta.stopDiscovery <- true\n\ta.stopPublish <- true\n\n\ta.stage = cfg.MulesoftConfig.Environment\n\ta.discoveryTags = cleanTags(cfg.MulesoftConfig.DiscoveryTags)\n\ta.discoveryIgnoreTags = cleanTags(cfg.MulesoftConfig.DiscoveryIgnoreTags)\n\ta.apicClient = coreagent.GetCentralClient()\n\ta.pollInterval = cfg.MulesoftConfig.PollInterval\n\ta.anypointClient.OnConfigChange(cfg.MulesoftConfig)\n\n\t// Restart Discovery & Publish\n\tgo a.discoveryLoop()\n\tgo a.publishLoop()\n}", "func (s *Syncthing) generateIgnoredFileConfig() (string, error) {\n\tvar ignoreFilePath = filepath.Join(s.LocalHome, IgnoredFIle)\n\tvar syncedPatternAdaption = make([]string, len(s.SyncedPattern))\n\tvar enableParseFromGitIgnore = DisableParseFromGitIgnore\n\n\tfor i, synced := range s.SyncedPattern {\n\t\tvar afterAdapt = synced\n\n\t\t// previews version support such this syntax\n\t\tif synced == \".\" {\n\t\t\tafterAdapt = \"**\"\n\t\t}\n\n\t\tif strings.Index(synced, \"./\") == 0 {\n\t\t\tafterAdapt = synced[1:]\n\t\t}\n\n\t\tsyncedPatternAdaption[i] = \"!\" + afterAdapt\n\t}\n\n\tvar ignoredPatternAdaption = make([]string, len(s.IgnoredPattern))\n\tfor i, ignored := range s.IgnoredPattern {\n\t\tvar afterAdapt = ignored\n\n\t\t// previews version support such this syntax\n\t\tif ignored == \".\" {\n\t\t\tafterAdapt = \"**\"\n\t\t}\n\n\t\tif strings.Index(ignored, \"./\") == 0 {\n\t\t\tafterAdapt = ignored[1:]\n\t\t}\n\n\t\tignoredPatternAdaption[i] = afterAdapt\n\t}\n\n\tif len(syncedPatternAdaption) == 0 {\n\t\tsyncedPatternAdaption = []string{\"!**\"}\n\t}\n\n\tignoredPattern := \"\"\n\tsyncedPattern := \"\"\n\n\tif s.EnableParseFromGitIgnore {\n\t\tlog.Infof(\"\\n Enable parsing file's ignore/sync from git ignore\\n\")\n\t\tenableParseFromGitIgnore = EnableParseFromGitIgnore\n\t} else {\n\t\tignoredPattern = strings.Join(ignoredPatternAdaption, \"\\n\")\n\t\tsyncedPattern = strings.Join(syncedPatternAdaption, \"\\n\")\n\n\t\tlog.Infof(\"IgnoredPattern: \\n\" + ignoredPattern)\n\t\tlog.Infof(\"SyncedPattern: \\n\" + syncedPattern)\n\t}\n\n\tvar values = map[string]string{\n\t\t\"enableParseFromGitIgnore\": enableParseFromGitIgnore,\n\t\t\"ignoredPattern\": ignoredPattern,\n\t\t\"syncedPattern\": syncedPattern,\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tif err := ignoredFileTemplate.Execute(buf, values); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to write .nhignore configuration template: %w\", err)\n\t}\n\n\tif err := ioutil.WriteFile(ignoreFilePath, buf.Bytes(), _const.DefaultNewFilePermission); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to generate .nhignore configuration: %w\", err)\n\t}\n\n\treturn ignoreFilePath, nil\n}", "func startWatchListener(configFilePath string) {\n\tconfigFile := filepath.Clean(configFilePath)\n\tconfigDir, _ := filepath.Split(configFile)\n\trealConfigFile, _ := filepath.EvalSymlinks(configFilePath)\n\twatcher.Add(configDir)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok { // 'Events' channel is closed\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tonWatchEvent(event, configFilePath, configFile, realConfigFile)\n\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif ok { // 'Errors' channel is not closed\n\t\t\t\t\tlog.Printf(\"watcher error: %v\\n\", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func Watch() {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer watcher.Close()\n\n\twatcher.Add(Path)\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-watcher.Events:\n\t\t\tif ev.Op == fsnotify.Write {\n\t\t\t\tlog.Println(\"config file has been changed, attempt to reload...\")\n\t\t\t\tParse(false)\n\t\t\t}\n\t\t}\n\t}\n}", "func processConfigFile(fileName string) {\n\tif verbose {\n\t\tfmt.Println(\"Processing config file:\", fileName)\n\t}\n\tprops, err := _readPropertiesFile(fileName)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error reading config file \"+fileName+\":\", err)\n\t\tos.Exit(1)\n\t}\n\t_processConfig(props)\n}", "func (lu TriceIDLookUp) FileWatcher(w io.Writer, fSys *afero.Afero, m *sync.RWMutex) {\n\n\t// creates a new file watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tmsg.FatalOnErr(err)\n\tdefer func() { msg.OnErr(watcher.Close()) }()\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tvar now, last time.Time\n\t\tfor {\n\t\t\tselect {\n\t\t\t// watch for events\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tfmt.Fprintln(w, \"EVENT:\", event, ok, time.Now().UTC())\n\n\t\t\t\tnow = time.Now()\n\t\t\t\tdiff := now.Sub(last)\n\t\t\t\tif diff > 5000*time.Millisecond {\n\t\t\t\t\tfmt.Fprintln(w, \"refreshing id.List\")\n\t\t\t\t\tm.Lock()\n\t\t\t\t\tmsg.FatalOnErr(lu.fromFile(fSys, FnJSON))\n\t\t\t\t\tlu.AddFmtCount(w)\n\t\t\t\t\tm.Unlock()\n\t\t\t\t\tlast = time.Now()\n\t\t\t\t}\n\n\t\t\t// watch for errors\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tfmt.Fprintln(w, \"ERROR1\", err, time.Now().UTC())\n\t\t\t}\n\t\t}\n\t}()\n\n\t// out of the box fsnotify can watch a single file, or a single directory\n\tmsg.InfoOnErr(watcher.Add(FnJSON), \"ERROR2\")\n\tif Verbose {\n\t\tfmt.Fprintln(w, FnJSON, \"watched now for changes\")\n\t}\n\t<-done\n}", "func TouchConfigFile() string {\n\tpath := GetUserConfigPath()\n\n\terr := ioutil.WriteFile(path, []byte(\"\\n\"), 0644)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\treturn path\n}", "func main() {\n\tcfgf, err := os.Open(\"./Monitor/cfg.json\")\n\tif err != nil {\n\t\t// Create default configuration, print message, and exit.\n\t\tcfg := &MonitorConfig{\n\t\t\tServerDir: baseDir() + \"/Binaries\",\n\t\t\tDataDir: baseDir() + \"/GameData\",\n\t\t\tLastSID: 0,\n\t\t\tHostName: \"localhost\",\n\t\t\tPort: \"2660\",\n\t\t\tAutoTLS: false,\n\t\t\tServers: make(map[int]*ServerConfig),\n\t\t\tVersions: make(map[string]BinaryStatus),\n\t\t\tTokens: make(map[string]*MonitorUser),\n\t\t\tLaunchedHandlers: make(map[int]*ServerController),\n\t\t}\n\t\terr := os.Mkdir(cfg.ServerDir, 0755)\n\t\tif err != nil && !os.IsExist(err) {\n\t\t\tfmt.Println(\"Error during setup:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\terr = os.Mkdir(cfg.DataDir, 0755)\n\t\tif err != nil && !os.IsExist(err) {\n\t\t\tfmt.Println(\"Error during setup:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\terr = os.Mkdir(baseDir()+\"/Monitor\", 0755)\n\t\tif err != nil && !os.IsExist(err) {\n\t\t\tfmt.Println(\"Error during setup:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\terr = cfg.Dump()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error during setup:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"Default config file created, please edit '\" + baseDir() + \"/Monitor/cfg.json' to change the setting to fit your needs.\")\n\t\tos.Exit(0)\n\t}\n\n\tcfg := &MonitorConfig{\n\t\tServers: make(map[int]*ServerConfig),\n\t\tVersions: make(map[string]BinaryStatus),\n\t\tTokens: make(map[string]*MonitorUser),\n\t\tLaunchedHandlers: make(map[int]*ServerController),\n\t}\n\tdec := json.NewDecoder(cfgf)\n\terr = dec.Decode(&cfg)\n\tif err != nil {\n\t\tfmt.Println(\"Could not load config file:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tGlobalConfig = cfg\n\n\t// Spin up controllers for each defined server.\n\tcfg.Lock()\n\tfor sid := range cfg.Servers {\n\t\tcfg.LaunchedHandlers[sid] = cfg.NewServerController(sid)\n\t}\n\tcfg.Unlock()\n\n\t// Start the web UI server. This doesn't really interact with the monitor in any way except\n\t// for pointing web socket connection in the right general direction.\n\tgo webUI(cfg.HostName, cfg.Port, cfg.AutoTLS)\n\n\texitSignal := make(chan os.Signal)\n\tsignal.Notify(exitSignal, os.Interrupt, os.Kill)\n\t<-exitSignal\n}", "func (client *Client) SetConfigFile(fpath string) error {\n\tinfo, err := os.Stat(fpath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif info.IsDir() {\n\t\treturn fmt.Errorf(\"the specified config file path seems to be a directory\")\n\t}\n\tclient.ConfigFilePath = fpath\n\n\tclient.flagForInit()\n\n\treturn nil\n}", "func (m *hostConfiguredContainer) updateConfigurationStatus() error {\n\t// If there is no config files configured, don't do anything.\n\tif len(m.configFiles) == 0 {\n\t\treturn nil\n\t}\n\n\t// Build list of files we need to read from the container.\n\tfiles := []string{}\n\n\t// Keep map of original paths.\n\tpaths := map[string]string{}\n\n\t// Build list of the files we should read.\n\tfor p := range m.configFiles {\n\t\tcpath := path.Join(ConfigMountpoint, p)\n\t\tfiles = append(files, cpath)\n\t\tpaths[cpath] = p\n\t}\n\n\tconfigFiles, err := m.configContainer.Read(files)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"reading configuration status: %w\", err)\n\t}\n\n\tm.configFiles = map[string]string{}\n\n\tfor _, configFile := range configFiles {\n\t\tm.configFiles[paths[configFile.Path]] = configFile.Content\n\t}\n\n\treturn nil\n}", "func SetConfig(file string) {\n\tPath.configFile = file\n}", "func TestConfigReload(t *testing.T) {\n\tserver, opts, config := runReloadServerWithConfig(t, \"./configs/reload/test.conf\")\n\tdefer removeFile(t, \"nats-server.pid\")\n\tdefer removeFile(t, \"nats-server.log\")\n\tdefer server.Shutdown()\n\n\tvar content []byte\n\tif runtime.GOOS != \"windows\" {\n\t\tcontent = []byte(`\n\t\t\tremote_syslog: \"udp://127.0.0.1:514\" # change on reload\n\t\t\tsyslog: true # enable on reload\n\t\t`)\n\t}\n\tplatformConf := filepath.Join(filepath.Dir(config), \"platform.conf\")\n\tif err := os.WriteFile(platformConf, content, 0666); err != nil {\n\t\tt.Fatalf(\"Unable to write config file: %v\", err)\n\t}\n\n\tloaded := server.ConfigTime()\n\n\tgolden := &Options{\n\t\tConfigFile: config,\n\t\tHost: \"0.0.0.0\",\n\t\tPort: 2233,\n\t\tAuthTimeout: float64(AUTH_TIMEOUT / time.Second),\n\t\tDebug: false,\n\t\tTrace: false,\n\t\tNoLog: true,\n\t\tLogtime: false,\n\t\tMaxControlLine: 4096,\n\t\tMaxPayload: 1048576,\n\t\tMaxConn: 65536,\n\t\tPingInterval: 2 * time.Minute,\n\t\tMaxPingsOut: 2,\n\t\tWriteDeadline: 10 * time.Second,\n\t\tCluster: ClusterOpts{\n\t\t\tName: \"abc\",\n\t\t\tHost: \"127.0.0.1\",\n\t\t\tPort: server.ClusterAddr().Port,\n\t\t},\n\t\tNoSigs: true,\n\t}\n\tsetBaselineOptions(golden)\n\n\tcheckOptionsEqual(t, golden, opts)\n\n\t// Change config file to new config.\n\tchangeCurrentConfigContent(t, config, \"./configs/reload/reload.conf\")\n\n\tif err := server.Reload(); err != nil {\n\t\tt.Fatalf(\"Error reloading config: %v\", err)\n\t}\n\n\t// Ensure config changed.\n\tupdated := server.getOpts()\n\tif !updated.Trace {\n\t\tt.Fatal(\"Expected Trace to be true\")\n\t}\n\tif !updated.Debug {\n\t\tt.Fatal(\"Expected Debug to be true\")\n\t}\n\tif !updated.Logtime {\n\t\tt.Fatal(\"Expected Logtime to be true\")\n\t}\n\tif !updated.LogtimeUTC {\n\t\tt.Fatal(\"Expected LogtimeUTC to be true\")\n\t}\n\tif runtime.GOOS != \"windows\" {\n\t\tif !updated.Syslog {\n\t\t\tt.Fatal(\"Expected Syslog to be true\")\n\t\t}\n\t\tif updated.RemoteSyslog != \"udp://127.0.0.1:514\" {\n\t\t\tt.Fatalf(\"RemoteSyslog is incorrect.\\nexpected: udp://127.0.0.1:514\\ngot: %s\", updated.RemoteSyslog)\n\t\t}\n\t}\n\tif updated.LogFile != \"nats-server.log\" {\n\t\tt.Fatalf(\"LogFile is incorrect.\\nexpected: nats-server.log\\ngot: %s\", updated.LogFile)\n\t}\n\tif updated.TLSConfig == nil {\n\t\tt.Fatal(\"Expected TLSConfig to be non-nil\")\n\t}\n\tif !server.info.TLSRequired {\n\t\tt.Fatal(\"Expected TLSRequired to be true\")\n\t}\n\tif !server.info.TLSVerify {\n\t\tt.Fatal(\"Expected TLSVerify to be true\")\n\t}\n\tif updated.Username != \"tyler\" {\n\t\tt.Fatalf(\"Username is incorrect.\\nexpected: tyler\\ngot: %s\", updated.Username)\n\t}\n\tif updated.Password != \"T0pS3cr3t\" {\n\t\tt.Fatalf(\"Password is incorrect.\\nexpected: T0pS3cr3t\\ngot: %s\", updated.Password)\n\t}\n\tif updated.AuthTimeout != 2 {\n\t\tt.Fatalf(\"AuthTimeout is incorrect.\\nexpected: 2\\ngot: %f\", updated.AuthTimeout)\n\t}\n\tif !server.info.AuthRequired {\n\t\tt.Fatal(\"Expected AuthRequired to be true\")\n\t}\n\tif !updated.Cluster.NoAdvertise {\n\t\tt.Fatal(\"Expected NoAdvertise to be true\")\n\t}\n\tif updated.PidFile != \"nats-server.pid\" {\n\t\tt.Fatalf(\"PidFile is incorrect.\\nexpected: nats-server.pid\\ngot: %s\", updated.PidFile)\n\t}\n\tif updated.MaxControlLine != 512 {\n\t\tt.Fatalf(\"MaxControlLine is incorrect.\\nexpected: 512\\ngot: %d\", updated.MaxControlLine)\n\t}\n\tif updated.PingInterval != 5*time.Second {\n\t\tt.Fatalf(\"PingInterval is incorrect.\\nexpected 5s\\ngot: %s\", updated.PingInterval)\n\t}\n\tif updated.MaxPingsOut != 1 {\n\t\tt.Fatalf(\"MaxPingsOut is incorrect.\\nexpected 1\\ngot: %d\", updated.MaxPingsOut)\n\t}\n\tif updated.WriteDeadline != 3*time.Second {\n\t\tt.Fatalf(\"WriteDeadline is incorrect.\\nexpected 3s\\ngot: %s\", updated.WriteDeadline)\n\t}\n\tif updated.MaxPayload != 1024 {\n\t\tt.Fatalf(\"MaxPayload is incorrect.\\nexpected 1024\\ngot: %d\", updated.MaxPayload)\n\t}\n\n\tif reloaded := server.ConfigTime(); !reloaded.After(loaded) {\n\t\tt.Fatalf(\"ConfigTime is incorrect.\\nexpected greater than: %s\\ngot: %s\", loaded, reloaded)\n\t}\n}", "func CloudConfig() {\n\tinPath, err := filepath.Abs(\"configuration/cloud-config.yml\")\n\toutPath, err := filepath.Abs(\"configuration/new-cloud-config.yml\")\n\n\tread, err := ioutil.ReadFile(inPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnewContents := string(read)\n\n\tsystemdPath, err := filepath.Abs(\"configuration/systemd\")\n\tfiles, _ := ioutil.ReadDir(systemdPath)\n\tfor _, file := range files {\n\t\tsystemdFile, _ := ioutil.ReadFile(fmt.Sprintf(\"%s/%s\", systemdPath, file.Name()))\n\t\tnewContents = strings.Replace(newContents, fmt.Sprintf(\"{{%%%s}}\", file.Name()), string(systemdFile), -1)\n\t}\n\n\tdiscovery := &Discovery{}\n\tdiscoveryURL, err := discovery.DiscoveryURL()\n\tnewContents = strings.Replace(newContents, \"{{$etcd-discovery-token}}\", discoveryURL, -1)\n\n\terr = ioutil.WriteFile(outPath, []byte(newContents), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func run(conn net.Conn, root string, allowEmptyDirs bool, watcher *fsnotify.Watcher) error {\n\tdefer conn.Close()\n\ths := psync.NewHandshake(1, psync.WireFormatGob, 0)\n\t_, err := hs.WriteTo(conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlis := psync.SrcFileLister{\n\t\tRoot: root,\n\t\tIncludeEmptyDirs: allowEmptyDirs,\n\t}\n\ts, err := lis.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\tenc := gob.NewEncoder(conn)\n\tdec := gob.NewDecoder(conn)\n\tcli := client{\n\t\tsender: psync.Sender{\n\t\t\tEnc: encWriter{\n\t\t\t\tWriter: conn,\n\t\t\t\tEncoder: enc,\n\t\t\t},\n\t\t\tRoot: root,\n\t\t},\n\t\tenc: enc,\n\t\tdec: dec,\n\t}\n\tif err = cli.sync(s, true); err != nil {\n\t\treturn err\n\t}\n\tif watcher == nil {\n\t\treturn nil\n\t}\n\tdefer watcher.Close()\n\tif err = watchDir(watcher, root); err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tselect {\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfmt.Println(\"event:\", event)\n\t\t\tswitch event.Op {\n\t\t\tcase fsnotify.Write, fsnotify.Chmod:\n\t\t\t\tsl, err := lis.AddSrcFile(nil, event.Name)\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 := cli.sync(sl, false); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase fsnotify.Create:\n\t\t\t\tvar sl []psync.SenderSrcFile\n\t\t\t\terr = watchDirFn(watcher, event.Name, func(path string) {\n\t\t\t\t\tsl, err = lis.AddSrcFile(sl, path)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t})\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 := cli.sync(sl, false); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase fsnotify.Remove:\n\t\t\t\ts, err := lis.List()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = cli.sync(s, true)\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\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlog.Println(\"error:\", err)\n\t\t}\n\t}\n}", "func scheduleAutoMappingDataReload(log logrus.FieldLogger) {\n\tlog = log.WithField(\"subsystem\", \"fs-watcher\")\n\t// originally mostly ripped straight from fsnotify.v1's NewWatcher example in the docs\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"unable to start FS watcher, will not detect changes\")\n\t\t// We continue on without aborting\n\t\treturn\n\t}\n\tlogrus.RegisterExitHandler(func() { _ = watcher.Close() })\n\n\tbasename := filepath.Base(opts.aliasfile)\n\tdirname := filepath.Dir(opts.aliasfile)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Warn(\"terminating config-watcher event dispatcher\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tl := log.WithField(\"event\", event)\n\t\t\t\tswitch filepath.Base(event.Name) {\n\t\t\t\tcase basename:\n\t\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\t\tl.Info(\"modification detected\")\n\t\t\t\t\t\t// The actual work! (also in some other edge-cases just below)\n\t\t\t\t\t\tloadMappingData(log)\n\t\t\t\t\t} else if event.Op&fsnotify.Create == fsnotify.Create {\n\t\t\t\t\t\t// better late than never\n\t\t\t\t\t\tl.Info(\"creation detected (adding watch)\")\n\t\t\t\t\t\tloadMappingData(log)\n\t\t\t\t\t\twatcher.Add(opts.aliasfile)\n\t\t\t\t\t} else if event.Op&fsnotify.Chmod == fsnotify.Chmod {\n\t\t\t\t\t\t// assume file created with 0 permissions then chmod'd more open, so our initial read might\n\t\t\t\t\t\t// have failed. Should be harmless to re-read the file. If it was chmod'd unreadable, we'll\n\t\t\t\t\t\t// error out cleanly.\n\t\t\t\t\t\tl.Info(\"chmod detected\")\n\t\t\t\t\t\tloadMappingData(log)\n\t\t\t\t\t} else if event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename {\n\t\t\t\t\t\t// I have seen this fire when the watched config file\n\t\t\t\t\t\t// is an entry in a K8S configmap and the entry was\n\t\t\t\t\t\t// modified, not deleted.\n\t\t\t\t\t\t_, err := os.Stat(event.Name)\n\t\t\t\t\t\tif err != nil && os.IsNotExist(err) {\n\t\t\t\t\t\t\tl.Info(\"file gone, confirmed, WATCH GONE\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tl.Info(\"file gone, false positive, file still exists, re-watching\")\n\t\t\t\t\t\t\t// The kernel will have removed the watch and\n\t\t\t\t\t\t\t// fsnotify will have removed its copy, to match.\n\t\t\t\t\t\t\t// We can't just ignore this, we have to add the\n\t\t\t\t\t\t\t// watch back.\n\t\t\t\t\t\t\twatcher.Add(opts.aliasfile)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// TODO: should we also remove all aliases?\n\t\t\t\t\t\t// We currently continue running with the last aliases seen, which lets us\n\t\t\t\t\t\t// steady-state on the assumption that the file is being replaced. Perhaps\n\t\t\t\t\t\t// we should start a timer and after 5 seconds, nuke the loaded aliases?\n\t\t\t\t\t}\n\t\t\t\t\t// no other scenarios known\n\t\t\t\tcase dirname:\n\t\t\t\t\t// usually ...\n\t\t\t\t\t// nothing to do; file creation will create an event named for the file, which we detect above for the file\n\t\t\t\t\t// which we care about; chmod ... we care less about.\n\t\t\t\t\tif event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename {\n\t\t\t\t\t\tl.Warn(\"directory of config file gone, nuking watcher, no notifications anymore\")\n\t\t\t\t\t\t// duplicate close on shutdown is safe\n\t\t\t\t\t\t_ = watcher.Close()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Warn(\"terminating config-watcher event dispatcher\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlog.WithError(err).Warn(\"error\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tcount := 0\n\tfor _, p := range []string{opts.aliasfile, dirname} {\n\t\terr = watcher.Add(p)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).WithField(\"file\", p).Info(\"unable to start watching\")\n\t\t\t// do not error out\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tif count == 0 {\n\t\tlog.Warn(\"unable to set up any watches, terminating FS watcher, auto-reloading gone\")\n\t\t_ = watcher.Close()\n\t}\n}", "func (pc pidController) notifyIfPIDFileChange(notifyCh chan error) {\n\tfor {\n\t\tselect {\n\t\tcase e, ok := <-pc.watcher.GetEventChannel():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase e.Op == fsnotify.Remove || e.Op == fsnotify.Rename:\n\t\t\t\t// If the PID file has been removed or moved to another path\n\t\t\t\t// okteto will try to recreate it and if it fails to recreate\n\t\t\t\t// we will wait until the other okteto process notices that needs\n\t\t\t\t// to exit.\n\t\t\t\toktetoLog.Infof(\"file %s has been moved or removed\", pc.pidFilePath)\n\t\t\t\tif err := pc.create(); err != nil {\n\t\t\t\t\toktetoLog.Infof(\"could not recreate PID file '%s': %s\", pc.pidFilePath, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase e.Op == fsnotify.Create:\n\t\t\t\t// If file has been created we just need to log it and continue waiting\n\t\t\t\t// for any change in the content of the file\n\t\t\t\toktetoLog.Infof(\"file %s has been recreated\", pc.pidFilePath)\n\t\t\t\tcontinue\n\t\t\tcase e.Op == fsnotify.Chmod:\n\t\t\t\t// If file permissions has been modified we need to log it and continue\n\t\t\t\t// waiting for any change in the content of the file\n\t\t\t\toktetoLog.Infof(\"permissions from %s have been modified\", pc.pidFilePath)\n\t\t\t\tcontinue\n\t\t\tcase e.Op == fsnotify.Write:\n\t\t\t\t// If file content has changed, we should verify that the okteto process\n\t\t\t\t// is no longer the owner of the development container and should return\n\t\t\t\t// an error as soon as possible to exit with a proper error. If the content\n\t\t\t\t// is the same we should wait until the content is modified\n\t\t\t\toktetoLog.Infof(\"file %s content has been modified\", pc.pidFilePath)\n\t\t\t\tpid := pc.pidProvider.provide()\n\t\t\t\tfilePID, err := pc.get()\n\t\t\t\tif err != nil {\n\t\t\t\t\toktetoLog.Infof(\"unable to get PID file at %s\", pc.pidFilePath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif strconv.Itoa(pid) != filePID {\n\t\t\t\t\tnotifyCh <- oktetoErrors.UserError{\n\t\t\t\t\t\tE: fmt.Errorf(\"development container has been deactivated by another 'okteto up' command\"),\n\t\t\t\t\t\tHint: \"Use 'okteto exec' to open another terminal to your development container\",\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase err, ok := <-pc.watcher.GetErrorChannel():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If there is an error on the filewatcher we should log and wait\n\t\t\t// until the other okteto process notices that needs to exit.\n\t\t\toktetoLog.Info(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *appState) loadConfigFile(ctx context.Context) error {\n\tcfgPath := a.configPath()\n\n\tif _, err := os.Stat(cfgPath); err != nil {\n\t\t// don't return error if file doesn't exist\n\t\treturn nil\n\t}\n\n\t// read the config file bytes\n\tfile, err := os.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\t// unmarshall them into the wrapper struct\n\tcfgWrapper := &ConfigInputWrapper{}\n\terr = yaml.Unmarshal(file, cfgWrapper)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshalling config: %w\", err)\n\t}\n\n\t// retrieve the runtime configuration from the disk configuration.\n\tnewCfg, err := cfgWrapper.RuntimeConfig(ctx, a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// validate runtime configuration\n\tif err := newCfg.validateConfig(); err != nil {\n\t\treturn fmt.Errorf(\"error parsing chain config: %w\", err)\n\t}\n\n\t// save runtime configuration in app state\n\ta.config = newCfg\n\n\treturn nil\n}", "func (ct *ctrlerCtx) diffConfigurationSnapshot(apicl apiclient.Services) {\n\topts := api.ListWatchOptions{}\n\n\t// get a list of all objects from API server\n\tobjlist, err := apicl.ClusterV1().ConfigurationSnapshot().List(context.Background(), &opts)\n\tif err != nil {\n\t\tct.logger.Errorf(\"Error getting a list of objects. Err: %v\", err)\n\t\treturn\n\t}\n\n\tct.logger.Infof(\"diffConfigurationSnapshot(): ConfigurationSnapshotList returned %d objects\", len(objlist))\n\n\t// build an object map\n\tobjmap := make(map[string]*cluster.ConfigurationSnapshot)\n\tfor _, obj := range objlist {\n\t\tobjmap[obj.GetKey()] = obj\n\t}\n\n\tlist, err := ct.ConfigurationSnapshot().List(context.Background(), &opts)\n\tif err != nil && !strings.Contains(err.Error(), \"not found in local cache\") {\n\t\tct.logger.Infof(\"Failed to get a list of objects. Err: %s\", err)\n\t\treturn\n\t}\n\n\t// if an object is in our local cache and not in API server, trigger delete for it\n\tfor _, obj := range list {\n\t\t_, ok := objmap[obj.GetKey()]\n\t\tif !ok {\n\t\t\tct.logger.Infof(\"diffConfigurationSnapshot(): Deleting existing object %#v since its not in apiserver\", obj.GetKey())\n\t\t\tevt := kvstore.WatchEvent{\n\t\t\t\tType: kvstore.Deleted,\n\t\t\t\tKey: obj.GetKey(),\n\t\t\t\tObject: &obj.ConfigurationSnapshot,\n\t\t\t}\n\t\t\tct.handleConfigurationSnapshotEvent(&evt)\n\t\t}\n\t}\n\n\t// trigger create event for all others\n\tfor _, obj := range objlist {\n\t\tct.logger.Infof(\"diffConfigurationSnapshot(): Adding object %#v\", obj.GetKey())\n\t\tevt := kvstore.WatchEvent{\n\t\t\tType: kvstore.Created,\n\t\t\tKey: obj.GetKey(),\n\t\t\tObject: obj,\n\t\t}\n\t\tct.handleConfigurationSnapshotEvent(&evt)\n\t}\n}", "func (_m *Environment) SetConfigFile(_a0 string) {\n\t_m.Called(_a0)\n}", "func (w *filePoller) watch(f *os.File, lastFi os.FileInfo, chClose chan struct{}) {\n\tdefer f.Close()\n\n\ttimer := time.NewTimer(watchWaitTime)\n\tif !timer.Stop() {\n\t\t<-timer.C\n\t}\n\tdefer timer.Stop()\n\n\tfor {\n\t\ttimer.Reset(watchWaitTime)\n\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tcase <-chClose:\n\t\t\tlogrus.Debugf(\"watch for %s closed\", f.Name())\n\t\t\treturn\n\t\t}\n\n\t\tfi, err := os.Stat(f.Name())\n\t\tif err != nil {\n\t\t\t// if we got an error here and lastFi is not set, we can presume that nothing has changed\n\t\t\t// This should be safe since before `watch()` is called, a stat is performed, there is any error `watch` is not called\n\t\t\tif lastFi == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If it doesn't exist at this point, it must have been removed\n\t\t\t// no need to send the error here since this is a valid operation\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tif err := w.sendEvent(fsnotify.Event{Op: fsnotify.Remove, Name: f.Name()}, chClose); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlastFi = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// at this point, send the error\n\t\t\tif err := w.sendErr(err, chClose); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif lastFi == nil {\n\t\t\tif err := w.sendEvent(fsnotify.Event{Op: fsnotify.Create, Name: fi.Name()}, chClose); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlastFi = fi\n\t\t\tcontinue\n\t\t}\n\n\t\tif fi.Mode() != lastFi.Mode() {\n\t\t\tif err := w.sendEvent(fsnotify.Event{Op: fsnotify.Chmod, Name: fi.Name()}, chClose); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlastFi = fi\n\t\t\tcontinue\n\t\t}\n\n\t\tif fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size() {\n\t\t\tif err := w.sendEvent(fsnotify.Event{Op: fsnotify.Write, Name: fi.Name()}, chClose); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlastFi = fi\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (li TriceIDLookUpLI) FileWatcher(w io.Writer, fSys *afero.Afero) {\n\n\t// creates a new file watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tmsg.FatalOnErr(err)\n\tdefer func() { msg.OnErr(watcher.Close()) }()\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tvar now, last time.Time\n\t\tfor {\n\t\t\tselect {\n\t\t\t// watch for events\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tfmt.Fprintln(w, \"EVENT:\", event, ok, time.Now().UTC())\n\n\t\t\t\tnow = time.Now()\n\t\t\t\tdiff := now.Sub(last)\n\t\t\t\tif diff > 5000*time.Millisecond {\n\t\t\t\t\tfmt.Fprintln(w, \"refreshing li list\")\n\t\t\t\t\tmsg.FatalOnErr(li.fromFile(fSys, LIFnJSON))\n\t\t\t\t\tlast = time.Now()\n\t\t\t\t}\n\n\t\t\t// watch for errors\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tfmt.Fprintln(w, \"ERROR1\", err, time.Now().UTC())\n\t\t\t}\n\t\t}\n\t}()\n\n\t// out of the box fsnotify can watch a single file, or a single directory\n\tmsg.InfoOnErr(watcher.Add(LIFnJSON), \"ERROR2\")\n\tif Verbose {\n\t\tfmt.Fprintln(w, LIFnJSON, \"watched now for changes\")\n\t}\n\t<-done\n}", "func readConfigFile() {\n\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger.Println(\"Reading config file...\")\n\n\tfileContents, err := ioutil.ReadFile(usr.HomeDir + \"/.autoq\")\n\n\tif err != nil {\n\t\tlogger.Fatalf(fmt.Sprintf(\"autoqctl: %v\\n\", err))\n\t}\n\n\tif err := json.Unmarshal(fileContents, &config); err != nil {\n\t\tlogger.Fatalf(\"Problem reading config: %s\", err)\n\t}\n\n\tlogger.Println(\"Using Autoq host: \" + config.Host)\n\n}", "func (lf *logFile) sync() error {\n\treturn lf.fd.Sync()\n}", "func (dn *Daemon) updateFiles(oldIgnConfig, newIgnConfig ign3types.Config, skipCertificateWrite bool) error {\n\tklog.Info(\"Updating files\")\n\tif err := dn.writeFiles(newIgnConfig.Storage.Files, skipCertificateWrite); err != nil {\n\t\treturn err\n\t}\n\tif err := dn.writeUnits(newIgnConfig.Systemd.Units); err != nil {\n\t\treturn err\n\t}\n\treturn dn.deleteStaleData(oldIgnConfig, newIgnConfig)\n}", "func TestLoggingDebugToFileConfig(t *testing.T) {\n\n\t/*declare settings*/\n\tmaxAge := \"1h\"\n\tflushConfig := csconfig.FlushDBCfg{\n\t\tMaxAge: &maxAge,\n\t}\n\tdbconfig := csconfig.DatabaseCfg{\n\t\tType: \"sqlite\",\n\t\tDbPath: \"./ent\",\n\t\tFlush: &flushConfig,\n\t}\n\tcfg := csconfig.LocalApiServerCfg{\n\t\tListenURI: \"127.0.0.1:8080\",\n\t\tLogMedia: \"file\",\n\t\tLogDir: \".\",\n\t\tDbConfig: &dbconfig,\n\t}\n\tlvl := log.DebugLevel\n\texpectedFile := \"./crowdsec_api.log\"\n\texpectedLines := []string{\"/test42\"}\n\tcfg.LogLevel = &lvl\n\n\tos.Remove(\"./crowdsec.log\")\n\tos.Remove(expectedFile)\n\n\t// Configure logging\n\tif err := types.SetDefaultLoggerConfig(cfg.LogMedia, cfg.LogDir, *cfg.LogLevel); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tapi, err := NewServer(&cfg)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create api : %s\", err)\n\t}\n\tif api == nil {\n\t\tt.Fatalf(\"failed to create api #2 is nbill\")\n\t}\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/test42\", nil)\n\treq.Header.Set(\"User-Agent\", UserAgent)\n\tapi.router.ServeHTTP(w, req)\n\tassert.Equal(t, 404, w.Code)\n\t//wait for the request to happen\n\ttime.Sleep(500 * time.Millisecond)\n\n\t//check file content\n\tdata, err := ioutil.ReadFile(expectedFile)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to read file : %s\", err)\n\t}\n\n\tfor _, expectedStr := range expectedLines {\n\t\tif !strings.Contains(string(data), expectedStr) {\n\t\t\tt.Fatalf(\"expected %s in %s\", expectedStr, string(data))\n\t\t}\n\t}\n\n\tos.Remove(\"./crowdsec.log\")\n\tos.Remove(expectedFile)\n\n}", "func TestEvconf(t *testing.T) {\n timeout := 1 * time.Second\n finished := make(chan bool)\n go func() {\n for {\n select {\n case <-time.After(timeout):\n applog.Panic(\"TestEvconf took longer than %v\", timeout)\n case <-finished:\n return\n }\n }\n }()\n // Log to stdout\n applog.SetOutput(os.Stdout)\n applog.Level = applog.DebugLevel\n // Create config_test.json\n f, _ := os.Create(\"config_test.json\")\n f.WriteString(\"{\\n \\\"string_key\\\": \\\"I'm Cool!\\\"\\n}\\n\")\n f.Close()\n\n c := New(\"config_test.json\", &config)\n loaded := make(chan bool)\n numCalls := 0\n c.OnLoad(func() {\n numCalls++\n loaded <- true\n })\n c.Ready()\n\n <-loaded\n\n if config.StringKey != \"I'm Cool!\" {\n t.Errorf(\n \"OnLoad#1 expected \\\"I'm Cool!\\\", got %v\",\n config.StringKey,\n )\n }\n\n // should not increase numCalls\n c.Ready()\n\n // Update config_test.json\n f, _ = os.Create(\"_config_test.json\")\n f.WriteString(\"{\\n \\\"string_key\\\": \\\"I'm Cooler!\\\"\\n}\\n\")\n f.Close()\n os.Remove(\"config_test.json\")\n os.Rename(\"_config_test.json\", \"config_test.json\")\n\n <-loaded\n\n if config.StringKey != \"I'm Cooler!\" {\n t.Errorf(\n \"OnLoad#2 expected \\\"I'm Cooler!\\\", got %v\",\n config.StringKey,\n )\n }\n\n // Update config_test.json with invalid data -- don't overwrite valid configs\n f, _ = os.Create(\"_config_test.json\")\n f.WriteString(\"{\\n \\\"not_string_key\\\": \\\"I'm Coolest!\\\"\\n}\\n\")\n f.Close()\n os.Remove(\"config_test.json\")\n os.Rename(\"_config_test.json\", \"config_test.json\")\n\n <-loaded\n\n if config.StringKey != \"I'm Cooler!\" {\n t.Errorf(\n \"OnLoad#3 expected \\\"I'm Cooler!\\\", got %v\",\n config.StringKey,\n )\n }\n\n // Update config_test.json with different OnLoad -- shouldn't call the old one\n c.OnLoad(func() {\n loaded <- true\n })\n f, _ = os.Create(\"_config_test.json\")\n f.WriteString(\"{\\n \\\"string_key\\\": \\\"I'm Coolest!\\\"\\n}\\n\")\n f.Close()\n os.Remove(\"config_test.json\")\n os.Rename(\"_config_test.json\", \"config_test.json\")\n\n <-loaded\n\n // But data should still be changed\n if config.StringKey != \"I'm Coolest!\" {\n t.Errorf(\"load#4 expected StringKey to be \\\"I'm Coolest!\\\", got %v\",\n config.StringKey)\n }\n\n // StopWatching test\n c.StopWatching()\n f, _ = os.Create(\"_config_test.json\")\n f.WriteString(\"{\\n \\\"string_key\\\": \\\"I'm Coolest!\\\"\\n}\\n\")\n f.Close()\n os.Remove(\"config_test.json\")\n os.Rename(\"_config_test.json\", \"config_test.json\")\n\n <-time.After(1 * time.Millisecond)\n\n os.Remove(\"config_test.json\")\n if numCalls != 3 {\n t.Errorf(\n \"Expected 3 calls for OnLoad, but got %d\",\n numCalls,\n )\n }\n finished <- true\n}", "func (c *ComponentLogController) processLogConfig() {\n\tconfigPath := \"service/voltha/config/\"\n\tlogPath := \"/loglevel\"\n\t//call MonitorForConfigChange for componentNameConfig\n\t//get ConfigChangeEvent Channel for componentName\n\tchangeInComponentNameConfigEvent, _ := c.componentNameConfig.MonitorForConfigChange()\n\n\t//call MonitorForConfigChange for global\n\t//get ConfigChangeEvent Channel for global\n\tchangeInglobalConfigEvent, _ := c.globalConfig.MonitorForConfigChange()\n\n\tchangeEvent := &ConfigChangeEvent{}\n\tconfigEvent := &ConfigChangeEvent{}\n\n\t//process the events for componentName and global config\n\tfor {\n\t\tselect {\n\t\tcase configEvent = <-changeInglobalConfigEvent:\n\n\t\tcase configEvent = <-changeInComponentNameConfigEvent:\n\n\t\t}\n\t\tchangeEvent = configEvent\n\t\ttime.Sleep(5 * time.Second)\n\n\t\t//if the eventType is Put call updateLogConfig for componentName or global config\n\t\tif changeEvent.ChangeType == 0 {\n\t\t\tcomponent := getComponentName(changeEvent.Key, configPath, logPath)\n\t\t\tpackageName, logLevel := getEventChangeData(changeEvent.Value)\n\t\t\tc.updateLogConfig(packageName, logLevel, component)\n\n\t\t\t//loadAndApplyLogConfig\n\t\t\tc.loadAndApplyLogConfig()\n\t\t}\n\n\t}\n\n\t//if the eventType is Delete call propagateLogConfigForClear\n\t//need to discuss on loading after delete\n\n}", "func TestConfigReloadNoConfigFile(t *testing.T) {\n\tserver := New(&Options{NoSigs: true})\n\tloaded := server.ConfigTime()\n\tif server.Reload() == nil {\n\t\tt.Fatal(\"Expected Reload to return an error\")\n\t}\n\tif reloaded := server.ConfigTime(); reloaded != loaded {\n\t\tt.Fatalf(\"ConfigTime is incorrect.\\nexpected: %s\\ngot: %s\", loaded, reloaded)\n\t}\n}", "func (dw *DirWatcher) onContentChange(node *Node) {\n\tvar (\n\t\tlogp = \"onContentChange\"\n\t)\n\n\tf, err := os.Open(node.SysPath)\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\tfis, err := f.Readdir(0)\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\treturn\n\t}\n\n\terr = f.Close()\n\tif err != nil {\n\t\tlog.Printf(\"%s: %s\", logp, err)\n\t}\n\n\t// Find deleted files in directory.\n\tfor _, child := range node.Childs {\n\t\tif child == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfound := false\n\t\tfor _, newInfo := range fis {\n\t\t\tif child.Name() == newInfo.Name() {\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\tcontinue\n\t\t}\n\t\tdw.unmapSubdirs(child)\n\t}\n\n\t// Find new files in directory.\n\tfor _, newInfo := range fis {\n\t\tfound := false\n\t\tfor _, child := range node.Childs {\n\t\t\tif newInfo.Name() == child.Name() {\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\tcontinue\n\t\t}\n\n\t\tnewChild, err := dw.fs.AddChild(node, newInfo)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\t\tcontinue\n\t\t}\n\t\tif newChild == nil {\n\t\t\t// a node is excluded.\n\t\t\tcontinue\n\t\t}\n\n\t\tns := NodeState{\n\t\t\tNode: *newChild,\n\t\t\tState: FileStateCreated,\n\t\t}\n\n\t\tif newChild.IsDir() {\n\t\t\tdw.dirsLocker.Lock()\n\t\t\tdw.dirs[newChild.Path] = newChild\n\t\t\tdw.dirsLocker.Unlock()\n\n\t\t\tdw.mapSubdirs(newChild)\n\t\t\tdw.onContentChange(newChild)\n\t\t} else {\n\t\t\t// Start watching the file for modification.\n\t\t\t_, err = newWatcher(node, newInfo, dw.Delay, dw.qFileChanges)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"%s: %s\", logp, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tselect {\n\t\tcase dw.qchanges <- ns:\n\t\tdefault:\n\t\t}\n\t}\n}", "func configLocalFilesystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {\n\tbaseLogPaht := path.Join(logPath, logFileName)\n\twriter, err := rotatelogs.New(\n\t\tbaseLogPaht+\".%Y%m%d%H%M.log\",\n\t\trotatelogs.WithLinkName(baseLogPaht), // 生成软链,指向最新日志文件\n\t\trotatelogs.WithMaxAge(maxAge), // 文件最大保存时间\n\t\trotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔\n\t)\n\tif err != nil {\n\t\tlog.Errorf(\"config local file system logger error. %+v\", errors.WithStack(err))\n\t}\n\tlfHook := lfshook.NewHook(lfshook.WriterMap{\n\t\tlog.DebugLevel: writer, // 为不同级别设置不同的输出目的\n\t\tlog.InfoLevel: writer,\n\t\tlog.WarnLevel: writer,\n\t\tlog.ErrorLevel: writer,\n\t\tlog.FatalLevel: writer,\n\t\tlog.PanicLevel: writer,\n\t}, &log.JSONFormatter{})\n\tlog.AddHook(lfHook)\n}", "func handleCHGHOST(c *Client, e Event) {\n\tif len(e.Params) != 2 {\n\t\treturn\n\t}\n\n\tc.state.Lock()\n\tuser := c.state.lookupUser(e.Source.Name)\n\tif user != nil {\n\t\tuser.Ident = e.Params[0]\n\t\tuser.Host = e.Params[1]\n\t}\n\tc.state.Unlock()\n\tc.state.notify(c, UPDATE_STATE)\n}", "func syncCPInfoFromFS(rootDir string, cpInfo *checkpointInfo) {\n\tlogger.Debugf(\"Starting checkpoint=%s\", cpInfo)\n\t//Checks if the file suffix of where the last block was written exists\n\tfilePath := deriveBlockfilePath(rootDir, cpInfo.latestFileChunkSuffixNum)\n\texists, size, err := util.FileExists(filePath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error in checking whether file [%s] exists: %s\", filePath, err))\n\t}\n\tlogger.Debugf(\"status of file [%s]: exists=[%t], size=[%d]\", filePath, exists, size)\n\t//Test is !exists because when file number is first used the file does not exist yet\n\t//checks that the file exists and that the size of the file is what is stored in cpinfo\n\t//status of file [/tmp/tests/ledger/blkstorage/fsblkstorage/blocks/blockfile_000000]: exists=[false], size=[0]\n\tif !exists || int(size) == cpInfo.latestFileChunksize {\n\t\t// check point info is in sync with the file on disk\n\t\treturn\n\t}\n\t//Scan the file system to verify that the checkpoint info stored in db is correct\n\t_, endOffsetLastBlock, numBlocks, err := scanForLastCompleteBlock(\n\t\trootDir, cpInfo.latestFileChunkSuffixNum, int64(cpInfo.latestFileChunksize))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not open current file for detecting last block in the file: %s\", err))\n\t}\n\tcpInfo.latestFileChunksize = int(endOffsetLastBlock)\n\tif numBlocks == 0 {\n\t\treturn\n\t}\n\t//Updates the checkpoint info for the actual last block number stored and it's end location\n\tif cpInfo.isChainEmpty {\n\t\tcpInfo.lastBlockNumber = uint64(numBlocks - 1)\n\t} else {\n\t\tcpInfo.lastBlockNumber += uint64(numBlocks)\n\t}\n\tcpInfo.isChainEmpty = false\n\tlogger.Debugf(\"Checkpoint after updates by scanning the last file segment:%s\", cpInfo)\n}", "func ClientSync(client RPCClient) {\n\tfiles, err := ioutil.ReadDir(client.BaseDir)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\tif _,err := os.Stat(client.BaseDir + \"/index.txt\"); os.IsNotExist(err) {\n\t\tf,_ := os.Create(client.BaseDir + \"/index.txt\")\n\t\tf.Close()\n\t}\n\n\t//Getting Local Index\n\tindex_file, err := os.Open(client.BaseDir + \"/index.txt\")\n\treader := bufio.NewReader(index_file)\n\ttemp_FileMetaMap := make(map[string]FileMetaData)\n\n\tfor{\n\t\tvar isPrefix bool\n\t\tvar line string\n\t\tvar l []byte\n\t\tfor {\n\t\t\tl,isPrefix,err = reader.ReadLine()\n\t\t//\tlog.Printf(string(l))\n\t\t\tline = line + string(l)\n\t\t\tif !isPrefix {\n\t\t\t\tbreak\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\tif line != \"\" {\n\t//\t\tlog.Print(line)\n\t\t\tvar new_File_Meta_Data FileMetaData\n\t\t\tnew_File_Meta_Data = handleIndex(string(line))\n\t\t\ttemp_FileMetaMap[new_File_Meta_Data.Filename] = new_File_Meta_Data\n\t\t}\n\t\tif err == io.EOF{\n\t\t\tbreak\n\t\t}\n\t}\n\tindex_file.Close()\n\t//Getting Remote Index\n\tremote_FileMetaMap := make(map[string]FileMetaData)\n\tvar success bool\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\tPrintMetaMap(remote_FileMetaMap)\n\t//Sorting Local Index\n\t//Client, files, \n\t//Handle Deleted Files\n\tHandle_Deleted_File(client, temp_FileMetaMap, files)\n\n\tLocal_Mod_FileMetaMap,Local_new_FileMetaMap,Local_No_Mod_FileMetaMap := CheckForNewChangedFile(client,files, temp_FileMetaMap)\n\tfor index,element := range Local_new_FileMetaMap {\n\t\t//Case 1 : new file was created locally that WAS NOT on the server\n\t//\tlog.Print(\"New File\")\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: new file was created locally but it WAS on the server\n\t\t\tif Local_new_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_new_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Update Remote File\n\t\t\t\tUpdateRemote(client, Local_new_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_No_Mod_FileMetaMap {\n\t//\tlog.Print(\"No Mod\")\n\t\t//Case 1 : if local no modification file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modification file WAS on the server\n\t//\t\tlog.Print(\"CLIENT - REMOTE VERSION : \", remote_FileMetaMap[index].Version)\n\t\t\tif Local_No_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_Mod_FileMetaMap {\n\t//\tlog.Print(\"Mod\")\n\t\t//Case 1 : if local modified file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t//\t\tlog.Print(\"NOT IN SERVER\")\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modified file WAS on the server\n\t//\t\tlog.Print(\"IN SERVER\")\n\t\t\tif Local_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t//\t\t\tlog.Print(\"SERVER VERSION IS HIGHER\")\n\t\t\t\t//Lost the race\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_Mod_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Check if file is the same.\n\t\t\t\t//Don't touch if it is\n\t\t\t\t//Update Remote File, version += 1\n\t//\t\t\tlog.Print(\"VERSION ARE EQUAL\")\n\t\t\t\tUpdateRemote(client, Local_Mod_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\t// Need to handle file that's in remote, but not in local.\n\t// Above accounts for all the updates, no changes and new file\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\n\tfor _,element := range remote_FileMetaMap {\n\t\tUpdateLocal(client, element)\n\t}\n\tPrintMetaMap(remote_FileMetaMap)\n\tUpdateIndex(client,remote_FileMetaMap)\n\t//Check for deleted files\n\treturn\n}", "func (cc *CollectdConfig) ConfigFilePath() string {\n\treturn filepath.Join(cc.InstanceConfigDir(), \"collectd.conf\")\n}", "func (srv *DataBrokerServer) OnConfigChange(cfg *config.Config) {\n\tsrv.UpdateConfig(srv.getOptions(cfg)...)\n}", "func (d *Discovery) watchFiles() {\n\tif d.watcher == nil {\n\t\tpanic(\"no watcher configured\")\n\t}\n\tfor _, p := range d.paths {\n\t\tif dir, _ := filepath.Split(p); dir != \"\" {\n\t\t\tp = dir\n\t\t} else {\n\t\t\tp = \"./\"\n\t\t}\n\t\tif err := d.watcher.Add(p); err != nil {\n\t\t\tlevel.Error(d.logger).Log(\"msg\", \"Error adding file watch\", \"path\", p, \"err\", err)\n\t\t}\n\t}\n}", "func init() {\n\t//config\n\tiniconf, err := config.NewConfig(\"ini\", \"config.ini\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t//serverinit\n\tserverip = iniconf.String(\"Server::ip\")\n\tif serverip == \"\" {\n\t\tserverip = \"0.0.0.0\"\n\t}\n\tserverport, _ = iniconf.Int(\"Server::port\")\n\tif serverport == 0 || serverport < 0 || serverport > 65535 {\n\t\tserverport = 3064\n\t}\n\tcache, _ = iniconf.Int(\"Server::cache\")\n\tif cache == 0 || cache < 0 || cache > 3000000 {\n\t\tcache = 100000\n\t}\n\tfilecount, _ = iniconf.Int(\"Server::filecount\")\n\tif filecount == 0 {\n\t\tfilecount = 10000\n\t}\n\tfiletimespan, _ = iniconf.Int(\"Server::filetimespan\")\n\tif filetimespan == 0 {\n\t\tfiletimespan = 15\n\t}\n\tdatachan = make(chan SyslogInfo, cache)\n\twritedata = make(chan string, cache)\n\tthreadnum, _ = iniconf.Int(\"Server::threadnum\")\n\tif threadnum == 0 || threadnum < 0 || threadnum > 30000 {\n\t\tthreadnum = 10\n\t}\n\tprofileserver = iniconf.String(\"Server::profileserver\")\n\t//serverinit finish\n\t//log init\n\tlogdir, err := os.Stat(\"log\")\n\tif err != nil {\n\t\terr = os.Mkdir(\"log\", 0777)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tif logdir.IsDir() == false {\n\t\t\terr = os.Mkdir(\"log\", 0777)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\tlogname := iniconf.String(\"Log::logname\")\n\tif len(logname) == 0 {\n\t\tlogname = \"log/server.log\"\n\t} else {\n\t\tlogname = \"log/\" + logname\n\t}\n\n\tlogsize, _ := iniconf.Int(\"Log::maxsize\")\n\tif logsize == 0 {\n\t\tlogsize = 500 * 1024 * 1024\n\t} else {\n\t\tlogsize = logsize * 1024 * 1024\n\t}\n\tlogsaveday, _ := iniconf.Int(\"Log::maxdays\")\n\tif logsaveday == 0 {\n\t\tlogsaveday = 7\n\t}\n\tloglevel, _ := iniconf.Int(\"Log::debug\")\n\tif loglevel == 0 || loglevel < 0 || loglevel > 4 {\n\t\tloglevel = 1\n\t}\n\tcacheprint, _ = iniconf.Int(\"Log::cacheprint\")\n\tif cacheprint == 0 || cacheprint < 0 {\n\t\tcacheprint = 10\n\t}\n\tlogflag = iniconf.String(\"Log::logdetail\")\n\tlogfile = logs.NewLogger(10000)\n\tlogfile.SetLevel(loglevel)\n\tlogstr := fmt.Sprintf(`{\"filename\":\"%s\",\"maxsize\":%d,\"maxdays\":%d}`, logname, logsize, logsaveday)\n\tlogfile.SetLogger(\"file\", logstr)\n\tlogdetail = logs.NewLogger(10000)\n\tlogdetail.SetLevel(1)\n\tlogname = \"log/logdetail.log\"\n\tlogstr = fmt.Sprintf(`{\"filename\":\"%s\",\"maxsize\":%d,\"maxdays\":%d}`, logname, logsize, logsaveday)\n\tlogdetail.SetLogger(\"file\", logstr)\n\tuserinfo = make(map[string]SessionInfo)\n\t//loginit finish\n\t//dbinit\n\tdbhost := iniconf.String(\"Db::dbhost\")\n\tdbport := iniconf.String(\"Db::dbport\")\n\tdbuser := iniconf.String(\"Db::dbuser\")\n\tdbpassword := iniconf.String(\"Db::dbpassword\")\n\tdbname := iniconf.String(\"Db::dbname\")\n\tdsn := dbuser + \":\" + dbpassword + \"@tcp(\" + dbhost + \":\" + dbport + \")/\" + dbname + \"?charset=utf8&loc=Asia%2FShanghai\"\n\tdb, err = sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdb.SetMaxIdleConns(500)\n\tdb.SetMaxOpenConns(500)\n\tvar dbisok = make(chan bool, 0)\n\tgo func() {\n\t\tvar isok bool\n\t\tfor i := 0; i < 5; i++ {\n\t\t\tfmt.Println(\"start to pin\")\n\t\t\terr = db.Ping()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Db connect error,rety 10 seconds after, now rety %d count\\n\", i+1)\n\t\t\t\ttime.Sleep(time.Second * 1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisok = true\n\t\t}\n\t\tdbisok <- isok\n\t}()\n\tisok := <-dbisok\n\tif isok == false {\n\t\tfmt.Println(\"Db not connect,please check db!\")\n\t\tos.Exit(2)\n\t} else {\n\t\tfmt.Println(\"Db connect.\")\n\t}\n\n\t//dbinit finish\n\t//execinit\n\texecsql = iniconf.String(\"Exec::sql\")\n\texecsql = FormatSql(execsql)\n\tstmt, err = db.Prepare(execsql)\n\tif err != nil {\n\t\tlogfile.Info(\"Prepare err:%s|[%s]\", execsql, err.Error())\n\t\tos.Exit(1)\n\t}\n\txmlnode, err = LoadXmlNode(\"./nat-gen.xml\")\n\n\tfmt.Println(\"**************\")\n\tfor _, v := range xmlnode {\n\t\tfmt.Println(v)\n\t}\n\tfmt.Println(\"**************\")\n\tif err != nil {\n\t\tfmt.Println(\"load nat-gen.xml err.\")\n\t\tos.Exit(2)\n\t}\n\t//useattr = regexp.MustCompile(`{.*?}`).FindAllString(execsql, -1)\n\t//execinit\n\n\tnatconfig = new(autoconfig.AutoConfig)\n\n}", "func Synchronize(path, remote string) error {\n\tlog.Printf(\"Polling for changes to %s\\n\", remote)\n\terr := DownloadFile(tempFile, remote)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to download %s\\n\", remote)\n\t\treturn err\n\t}\n\tlog.Printf(\"Successfully downloaded %s\\n\", remote)\n\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tlog.Printf(\"%s does not exist, using %s\", path, remote)\n\t\tinput, err := ioutil.ReadFile(tempFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = ioutil.WriteFile(path, input, permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"%s written\\n\", path)\n\t\treturn nil\n\t}\n\n\tchecksum, err := getMD5(tempFile)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to get checksum of %s\\n\", tempFile)\n\t\treturn err\n\t}\n\tkeysChecksum, err := getMD5(path)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to get checksum of %s\\n\", path)\n\t\treturn err\n\t}\n\tif bytes.Equal(checksum[:], keysChecksum[:]) {\n\t\tlog.Println(\"Checksums match, no changes necessary\")\n\t\treturn nil\n\t}\n\tlog.Printf(\"Changes detected, overwriting %s\\n\", path)\n\tinput, err := ioutil.ReadFile(tempFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(path, input, permissions)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"%s overwritten\\n\", path)\n\treturn nil\n}", "func (cfg *Config) Sync() (err error) {\n\tif !filepath.IsAbs(cfg.ConfigPath) {\n\t\tcfg.ConfigPath, err = filepath.Abs(cfg.ConfigPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcfg.UpdatedAt = time.Now().UTC()\n\tvar d []byte\n\td, err = yaml.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"writing to:\", cfg.ConfigPath)\n\treturn ioutil.WriteFile(cfg.ConfigPath, d, 0600)\n}", "func (ipvsc *ipvsControllerController) sync(key interface{}) error {\n\tipvsc.reloadRateLimiter.Accept()\n\n\tns, name, err := parseNsName(ipvsc.configMapName)\n\tif err != nil {\n\t\tglog.Warningf(\"%v\", err)\n\t\treturn err\n\t}\n\n\tcfgMap, err := ipvsc.getConfigMap(ns, name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected error searching configmap %v: %v\", ipvsc.configMapName, err)\n\t}\n\n\tsvc := ipvsc.getServices(cfgMap)\n\n\terr = ipvsc.keepalived.WriteCfg(svc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.V(2).Infof(\"services: %v\", svc)\n\n\tmd5, err := checksum(keepalivedCfg)\n\tif err == nil && md5 == ipvsc.ruMD5 {\n\t\treturn nil\n\t}\n\n\tipvsc.ruMD5 = md5\n\terr = ipvsc.keepalived.Reload()\n\tif err != nil {\n\t\tglog.Errorf(\"error reloading keepalived: %v\", err)\n\t}\n\n\treturn nil\n}", "func (r *Reporter) OnConfigChange(ctx context.Context, cfg *config.Config) {\n\tif r.cancel != nil {\n\t\tr.cancel()\n\t}\n\n\tservices, err := getReportedServices(cfg)\n\tif err != nil {\n\t\tlog.Warn(ctx).Err(err).Msg(\"metrics announce to service registry is disabled\")\n\t}\n\n\tsharedKey, err := cfg.Options.GetSharedKey()\n\tif err != nil {\n\t\tlog.Error(ctx).Err(err).Msg(\"decoding shared key\")\n\t\treturn\n\t}\n\n\tregistryConn, err := r.outboundGRPCConnection.Get(ctx, &grpc.OutboundOptions{\n\t\tOutboundPort: cfg.OutboundPort,\n\t\tInstallationID: cfg.Options.InstallationID,\n\t\tServiceName: cfg.Options.Services,\n\t\tSignedJWTKey: sharedKey,\n\t})\n\tif err != nil {\n\t\tlog.Error(ctx).Err(err).Msg(\"connecting to registry\")\n\t\treturn\n\t}\n\n\tif len(services) > 0 {\n\t\tctx, cancel := context.WithCancel(context.TODO())\n\t\tgo runReporter(ctx, pb.NewRegistryClient(registryConn), services)\n\t\tr.cancel = cancel\n\t}\n}", "func main() {\n\t// args without bin name\n\tif len(os.Args) == 1 {\n\t\t_, _ = fmt.Fprint(os.Stderr, \"no file specified to tail\")\n\t\tos.Exit(1)\n\t}\n\targs := os.Args[1:]\n\n\tvar fname string\n\tvar lcount int\n\n\t// check if a line count is provided\n\tif len(args) == 2 {\n\t\tlcount = extractLineCount(args[0])\n\t\tfname = args[1]\n\t} else {\n\t\tlcount = 0\n\t\tfname = args[0]\n\t}\n\n\tfname, err := filepath.Abs(fname)\n\thandleErrorAndExit(err, \"error while converting filenames\")\n\n\t// check if file exists\n\tf, err := os.Open(fname)\n\t// close the handler later\n\tdefer f.Close()\n\thandleErrorAndExit(err, fmt.Sprintf(\"file not found: %s\", fname))\n\n\t// if a line count is provided, rewind cursor\n\t// the file should be read from the end, backwards\n\t// TODO: handle f == nil\n\tlog.Println(\"tailing last lines\")\n\tf = seekBackwardsToLineCount(lcount, f)\n\n\tlog.Println(\"creating inotify event\")\n\t// TODO: apparently syscall is deprecated, use sys pkg later\n\tfd, err := syscall.InotifyInit()\n\thandleErrorAndExit(err, fmt.Sprintf(\"error while registering inotify: %s\", fname))\n\n\tlog.Println(\"adding watch\")\n\twd, err := syscall.InotifyAddWatch(fd, fname, syscall.IN_MOVE_SELF)\n\thandleErrorAndExit(err, fmt.Sprintf(\"error while adding an inotify watch: %s\", fname))\n\n\tdefer func() {\n\t\tsyscall.InotifyRmWatch(fd, uint32(wd))\n\t}()\n\n\tvar com chan string\n\n\tgo func() {\n\t\tfor {\n\t\t\tlog.Println(\"overwatch\")\n\t\t\tcheckInotifyEvents(fd, com)\n\t\t}\n\t}()\n\n\t// wait for new lines to appear\n\t//reader := bufio.NewReader(f)\n\t// TODO: this forloop fucks shit up, need to use a better method\n\t//for {\n\t//\tline, err := reader.ReadString('\\n')\n\t//\tif err != nil {\n\t//\t\tif err == io.EOF {\n\t//\t\t\t// TODO: sleep for a while? check when perf testing\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\n\t//\t\t_, _ = fmt.Fprintf(os.Stderr, \"error while reading file: %s\", err)\n\t//\t\tbreak\n\t//\t}\n\t//\n\t//\t_, _ = fmt.Fprint(os.Stdout, line)\n\t//}\n}", "func TestSources_e2e_local_spec_change(t *testing.T) {\n\tmutations := []struct {\n\t\tcomment string\n\t\tsource string\n\t\twantChanged bool\n\t}{\n\t\t{\n\t\t\tcomment: \"init\",\n\t\t\tsource: \"testdata/step1\",\n\t\t\twantChanged: true,\n\t\t},\n\t\t{\n\t\t\tcomment: \"new content\",\n\t\t\tsource: \"testdata/step2\",\n\t\t\twantChanged: true,\n\t\t},\n\t\t{\n\t\t\tcomment: \"same content, no change expected\",\n\t\t\tsource: \"testdata/step2\",\n\t\t\twantChanged: false,\n\t\t},\n\t}\n\n\tname := \"clusterxyz\"\n\n\tss := testNewSources(t)\n\tdefer testRemoveSources(t, ss)\n\n\tfor _, mutation := range mutations {\n\t\t// create spec that will change each step.\n\t\tspec := v1.SourceSpec{\n\t\t\tType: \"local\",\n\t\t\tURL: mutation.source,\n\t\t}\n\n\t\terr := ss.Register(nsn, name, spec)\n\t\tif !assert.NoError(t, err, \"Register\") {\n\t\t\treturn\n\t\t}\n\n\t\terr = ss.FetchAll()\n\t\tif !assert.NoError(t, err, \"FetchAll\") {\n\t\t\treturn\n\t\t}\n\n\t\tgotChanged, err := ss.Get(nsn, name)\n\t\tif !assert.NoError(t, err, \"Get\") {\n\t\t\treturn\n\t\t}\n\n\t\tassert.Equal(t, mutation.wantChanged, gotChanged, \"<changed> at mutation '%s'\", mutation.comment)\n\t}\n\n\tassert.FileExists(t, filepath.Join(ss.RootPath, \"workspace\", nsn.Namespace, nsn.Name, name, \"content\", \"file2.txt\"))\n\n\t// currently the workspace directories aren't pruned, that's why file1.txt still exists.\n\tassert.FileExists(t, filepath.Join(ss.RootPath, \"workspace\", nsn.Namespace, nsn.Name, name, \"content\", \"file1.txt\"))\n}", "func (l *Logger) handleFile(path string, info os.FileInfo, err error) error {\n\tif info.IsDir() {\n\t\treturn nil\n\t}\n\tif !strings.HasPrefix(info.Name(), l.filePrefix+\"-\") {\n\t\treturn nil\n\t}\n\tif !strings.HasSuffix(info.Name(), \".log\") {\n\t\treturn nil\n\t}\n\tlidx := strings.LastIndex(info.Name(), \".log\")\n\ttstring := info.Name()[len(l.filePrefix)+1 : lidx]\n\tglog.WithField(\"log_ts\", tstring).Debug(\"Found log.\")\n\n\t// Handle if we find the current log file.\n\tif tstring == \"current\" {\n\t\treturn nil\n\t}\n\n\tts, err := strconv.ParseInt(tstring, 16, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlf := new(logFile)\n\tlf.endTs = ts\n\tlf.path = path\n\tl.list = append(l.list, lf)\n\n\tl.updateLastLogTs(lf.endTs)\n\treturn nil\n}", "func setupFileConfiguration(t *testing.T, configContent string) string {\n\tfile, err := ioutil.TempFile(\"\", \"ecs-test\")\n\trequire.NoError(t, err, \"creating temp file for configuration failed\")\n\n\t_, err = file.Write([]byte(configContent))\n\trequire.NoError(t, err, \"writing configuration to file failed\")\n\n\treturn file.Name()\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 (f *FileList) ConfigGit() {\n\tpaw.Logger.Debug()\n\n\tf.git = NewGitStatus(f.root)\n\tgs := f.git.GetStatus()\n\tif f.git.NoGit || len(f.store) < 1 || gs == nil {\n\t\treturn\n\t}\n\n\t// 1. check: if dir is GitIgnored, then marks all subfiles with GitIgnored.\n\tfor _, dir := range f.dirs {\n\t\tif len(f.store[dir]) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tfm := f.store[dir]\n\t\tfd := fm[0]\n\t\tdrp := fd.RelPath\n\t\tisMarkIgnored := false\n\t\tisUntracked := false\n\t\tif xy, ok := gs[drp]; ok {\n\t\t\tif isXY(xy, GitIgnored) {\n\t\t\t\tisMarkIgnored = true\n\t\t\t}\n\t\t\tif isXY(xy, GitUntracked) {\n\t\t\t\tisUntracked = true\n\t\t\t}\n\t\t}\n\t\tif isMarkIgnored || isUntracked {\n\t\t\tfor _, file := range fm[1:] {\n\t\t\t\trp := file.RelPath\n\t\t\t\t// 1. continue...\n\t\t\t\tgs[rp] = &GitFileStatus{\n\t\t\t\t\tStaging: gs[drp].Staging,\n\t\t\t\t\tWorktree: gs[drp].Worktree,\n\t\t\t\t\tExtra: file.BaseName,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// 2. if any of subfiles of dir (including root) has any change of git status, set GitChanged to dir\n\tfor _, dir := range f.dirs {\n\t\tfiles := f.GetFiles(dir)\n\t\tif files == nil || len(files) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tfd := files[0]\n\t\txs, ys := f.getSubXYs(files[1:], gs)\n\t\tif len(xs) > 0 || len(ys) > 0 {\n\t\t\trp := fd.RelPath\n\t\t\tgs[rp] = &GitFileStatus{\n\t\t\t\tStaging: getSC(xs),\n\t\t\t\tWorktree: getSC(ys),\n\t\t\t\tExtra: fd.BaseName + \"/\",\n\t\t\t}\n\t\t}\n\t}\n\n\tf.git.Dump(\"ConfigGit: modified\")\n}", "func (c *Config) HubConfigFile() string {\n\treturn filepath.Join(c.ConfigPath(), \"hub.yml\")\n}", "func (k *kubelet) configFile() (string, error) {\n\tconfig := &kubeletconfig.KubeletConfiguration{\n\t\tTypeMeta: v1.TypeMeta{\n\t\t\tKind: \"KubeletConfiguration\",\n\t\t\tAPIVersion: kubeletconfig.SchemeGroupVersion.String(),\n\t\t},\n\t\t// Enables TLS certificate rotation, which is good from security point of view.\n\t\tRotateCertificates: true,\n\t\t// Request HTTPS server certs from API as well, so kubelet does not generate self-signed certificates.\n\t\tServerTLSBootstrap: true,\n\t\t// If Docker is configured to use systemd as a cgroup driver and Docker is used as container\n\t\t// runtime, this needs to be set to match Docker.\n\t\t// TODO pull that information dynamically based on what container runtime is configured.\n\t\tCgroupDriver: k.config.CgroupDriver,\n\t\t// Address where kubelet should listen on.\n\t\tAddress: k.config.Address,\n\t\t// Disable healht port for now, since we don't use it.\n\t\t// TODO check how to use it and re-enable it.\n\t\tHealthzPort: &[]int32{0}[0],\n\t\t// Set up cluster domain. Without this, there is no 'search' field in /etc/resolv.conf in containers, so\n\t\t// short-names resolution like mysvc.myns.svc does not work.\n\t\tClusterDomain: \"cluster.local\",\n\t\t// Authenticate clients using CA file.\n\t\tAuthentication: kubeletconfig.KubeletAuthentication{\n\t\t\tX509: kubeletconfig.KubeletX509Authentication{\n\t\t\t\tClientCAFile: \"/etc/kubernetes/pki/ca.crt\",\n\t\t\t},\n\t\t},\n\n\t\t// This defines where should pods cgroups be created, like /kubepods and /kubepods/burstable.\n\t\t// Also when specified, it suppresses a lot message about it.\n\t\tCgroupRoot: \"/\",\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'system-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with SystemReservedCgroup.\n\t\tSystemReserved: k.config.SystemReserved,\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'kube-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with KubeReservedCgroup.\n\t\tKubeReserved: k.config.KubeReserved,\n\n\t\tClusterDNS: k.config.ClusterDNSIPs,\n\n\t\tHairpinMode: k.config.HairpinMode,\n\t}\n\n\tkubelet, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"serializing to YAML: %w\", err)\n\t}\n\n\treturn string(kubelet), nil\n}", "func (sc *SafeConfig) ReloadConfig(confFile string) (err error) {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar c = &Config{}\n\tf, err := os.Open(confFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Reading config file: %s\", err)\n\t}\n\tdefer f.Close()\n\n\tdecoder := yaml.NewDecoder(f)\n\tif err = decoder.Decode(c); err != nil {\n\t\treturn fmt.Errorf(\"Parsing config file: %s\", err)\n\t}\n\n\t// Validate and Filter config\n\ttargets := c.Targets[:0]\n\tvar targetNames []string\n\n\tfor _, t := range c.Targets {\n\t\ttargetNames = append(targetNames, t.Name)\n\t\tfound, _ := regexp.MatchString(\"^ICMP|MTR|ICMP+MTR|TCP|HTTPGet$\", t.Type)\n\t\tif found == false {\n\t\t\treturn fmt.Errorf(\"Target '%s' has unknown check type '%s' must be one of (ICMP|MTR|ICMP+MTR|TCP|HTTPGet)\", t.Name, t.Type)\n\t\t}\n\n\t\t// Filter out the targets that are not assigned to the running host, if the `probe` is not specified don't filter\n\t\tif t.Probe == nil {\n\t\t\ttargets = append(targets, t)\n\t\t} else {\n\t\t\tfor _, p := range t.Probe {\n\t\t\t\tif p == hostname {\n\t\t\t\t\ttargets = append(targets, t)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remap the filtered targets\n\tc.Targets = targets\n\n\tif _, err = common.HasListDuplicates(targetNames); err != nil {\n\t\treturn fmt.Errorf(\"Parsing config file: %s\", err)\n\t}\n\n\t// Config precheck\n\tif c.MTR.MaxHops < 0 || c.MTR.MaxHops > 65500 {\n\t\treturn fmt.Errorf(\"mtr.max-hops must be between 0 and 65500\")\n\t}\n\tif c.MTR.Count < 0 || c.MTR.Count > 65500 {\n\t\treturn fmt.Errorf(\"mtr.count must be between 0 and 65500\")\n\t}\n\n\tsc.Lock()\n\tsc.Cfg = c\n\tsc.Unlock()\n\n\treturn nil\n}", "func (l *Notifier) Changed(c *config.KdnConfig, msg string) error {\n\tc.Logger.Infof(\"Changed: %s\", msg)\n\treturn nil\n}", "func (config *Config) evaluateConcertoConfigFile(c *cli.Context) error {\n\tlog.Debug(\"evaluateConcertoConfigFile\")\n\tcurrUser, err := config.evaluateCurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif configFile := c.String(\"concerto-config\"); configFile != \"\" {\n\n\t\tlog.Debug(\"Concerto configuration file location taken from env/args\")\n\t\tconfig.ConfFile = configFile\n\n\t} else {\n\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tif config.CurrentUserIsAdmin && (config.BrownfieldToken != \"\" || (config.CommandPollingToken != \"\" && config.ServerID != \"\") || FileExists(windowsServerConfigFile)) {\n\t\t\t\tlog.Debugf(\"Current user is administrator, setting config file as %s\", windowsServerConfigFile)\n\t\t\t\tconfig.ConfFile = windowsServerConfigFile\n\t\t\t} else {\n\t\t\t\t// User mode Windows\n\t\t\t\tlog.Debugf(\"Current user is regular user: %s\", currUser.Username)\n\t\t\t\tconfig.ConfFile = filepath.Join(currUser.HomeDir, \".concerto/client.xml\")\n\t\t\t}\n\t\t} else {\n\t\t\t// Server mode *nix\n\t\t\tif config.CurrentUserIsAdmin && (config.BrownfieldToken != \"\" || (config.CommandPollingToken != \"\" && config.ServerID != \"\") || FileExists(nixServerConfigFile)) {\n\t\t\t\tconfig.ConfFile = nixServerConfigFile\n\t\t\t} else {\n\t\t\t\t// User mode *nix\n\t\t\t\tconfig.ConfFile = filepath.Join(currUser.HomeDir, \".concerto/client.xml\")\n\t\t\t}\n\t\t}\n\t}\n\tconfig.ConfLocation = path.Dir(config.ConfFile)\n\treturn nil\n}", "func configWatcherHandler(logger *zap.SugaredLogger, configMap *corev1.ConfigMap) {\n\t// Set the package variable to indicate that the test watcher was called\n\tsetWatchedMap(configMap)\n}", "func (suite *EventLogTestSuite) WriteConfigCheck(currentLogFile string) {\n\tsuite.EventLog.init()\n\tinputFiles := []string{\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-01\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-02\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-03\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-04\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-05\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-06\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-07\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-08\",\n\t\tsuite.EventLog.eventLogName + suite.EventLog.fileDelimiter + \"2020-03-09\",\n\t}\n\tdefer func() {\n\t\tfor _, fileName := range inputFiles {\n\t\t\tos.Remove(filepath.Join(suite.EventLog.eventLogPath, fileName))\n\t\t}\n\t\tos.Remove(currentLogFile)\n\t}()\n\n\tfor _, fileName := range inputFiles {\n\t\tsuite.EventLog.fileSystem.AppendToFile(filepath.Join(suite.EventLog.eventLogPath, fileName), \"Test content\", 0600)\n\t}\n\tcontent := \"test\"\n\tsuite.EventLog.loadEvent(AgentUpdateResultMessage, \"2.0.0.2\", content)\n\tsuite.EventLog.rotateEventLog()\n\tcurrentLogCount := len(suite.EventLog.getFilesWithMatchDatePattern())\n\tassert.Equal(suite.T(), currentLogCount, suite.EventLog.noOfHistoryFiles)\n}", "func Test_FsWatcher_Add_OnFileCreation(t *testing.T) {\n\t// create the project directory\n\tpath, err := ioutil.TempDir(\"\", \"tagger-tests\")\n\tassert.Nil(t, err)\n\tdefer os.RemoveAll(path)\n\n\twatcher := NewFsWatcher([]string{}, \"TAGS\")\n\tdefer watcher.Close()\n\terr = watcher.Add(path)\n\tassert.Nil(t, err)\n\n\t// fire!\n\tTouchFile(t, filepath.Join(path, \"test_file\")).Close()\n\n\tassert.NotNil(t, <-watcher.Events())\n}", "func (s *BasevhdlListener) EnterFile_open_information(ctx *File_open_informationContext) {}", "func (cfg *BaseConfig) SetConfigFile(file string) {\n\tcfg.ConfigFile = file\n}", "func (d *Director) runCheckConfigWatcher(ctx context.Context) {\n\tllog := d.Log.WithField(\"method\", \"runCheckConfigWatcher\")\n\n\tllog.Debug(\"Starting...\")\n\n\twatcher := d.DalClient.NewWatcher(\"monitor/\", true)\n\n\t// No need for a looper here since we can control the loop via the context\n\tfor {\n\t\t// safety valve\n\t\tif !d.amDirector() {\n\t\t\tllog.Warning(\"Not active director - stopping\")\n\t\t\tbreak\n\t\t}\n\n\t\t// watch check config entries\n\t\tresp, err := watcher.Next(ctx)\n\t\tif err != nil && err.Error() == \"context canceled\" {\n\t\t\tllog.Warning(\"Received a notice to shutdown\")\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tllog.WithField(\"err\", err).Error(\"Unexpected error\")\n\n\t\t\td.OverwatchChan <- &overwatch.Message{\n\t\t\t\tError: fmt.Errorf(\"Unexpected watcher error: %v\", err),\n\t\t\t\tSource: fmt.Sprintf(\"%v.runCheckConfigWatcher\", d.Identifier),\n\t\t\t\tErrorType: overwatch.ETCD_WATCHER_ERROR,\n\t\t\t}\n\n\t\t\t// Let overwatch determine if it should shut things down or not\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.ignorableWatcherEvent(resp) {\n\t\t\tllog.WithField(\"key\", resp.Node.Key).Debug(\"Received ignorable watcher event\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := d.handleCheckConfigChange(resp); err != nil {\n\t\t\tllog.WithFields(log.Fields{\n\t\t\t\t\"key\": resp.Node.Key,\n\t\t\t\t\"err\": err,\n\t\t\t}).Error(\"Unable to process config change for given key\")\n\t\t}\n\t}\n\n\tllog.Debug(\"Exiting...\")\n}", "func (cli *FakeDatabaseClient) RecoverConfigFile(ctx context.Context, in *dbdpb.RecoverConfigFileRequest, opts ...grpc.CallOption) (*dbdpb.RecoverConfigFileResponse, error) {\n\tpanic(\"implement me\")\n}", "func (f *Fs) ChangeNotify(notifyFunc func(string, fs.EntryType), pollIntervalChan <-chan time.Duration) {\n\tdo := f.Fs.Features().ChangeNotify\n\tif do == nil {\n\t\treturn\n\t}\n\twrappedNotifyFunc := func(path string, entryType fs.EntryType) {\n\t\tfs.Logf(f, \"path %q entryType %d\", path, entryType)\n\t\tvar (\n\t\t\twrappedPath string\n\t\t)\n\t\tswitch entryType {\n\t\tcase fs.EntryDirectory:\n\t\t\twrappedPath = path\n\t\tcase fs.EntryObject:\n\t\t\t// Note: All we really need to do to monitor the object is to check whether the metadata changed,\n\t\t\t// as the metadata contains the hash. This will work unless there's a hash collision and the sizes stay the same.\n\t\t\twrappedPath = generateMetadataName(path)\n\t\tdefault:\n\t\t\tfs.Errorf(path, \"press ChangeNotify: ignoring unknown EntryType %d\", entryType)\n\t\t\treturn\n\t\t}\n\t\tnotifyFunc(wrappedPath, entryType)\n\t}\n\tdo(wrappedNotifyFunc, pollIntervalChan)\n}", "func FileSync(f *os.File,) error", "func (deb *DebPkg) MarkConfigFile(dest string) error {\n\treturn deb.control.markConfigFile(dest)\n}", "func recupStructWithConfigFile(file string, debugFile string, debugLog bool) (config Config) {\n\n\t// check if file exists\n\te, err := os.Stat(file)\n\tif err != nil {\n\t\tfmt.Println(\"config file not found\")\n\t\tutils.StopApp()\n\t}\n\tDebugPrint(debugFile, debugLog, \"DEBUG: \", \"File opened : \"+e.Name())\n\n\t// open the file\n\tf, _ := os.Open(file)\n\tdefer f.Close()\n\n\t// read the file contents\n\tbyteValue, _ := ioutil.ReadAll(f)\n\n\t// unmarshal the file's content and save to config variable\n\tjson.Unmarshal(byteValue, &config)\n\n\treturn\n}", "func Run(conf *Conf, processors []FileTailProcessor, analyzer ClientAnalyzer, finishEvent chan<- bool) {\n\ttickerInterval := time.Duration(conf.IntervalSecs)\n\tif tickerInterval == 0 {\n\t\tlog.Warn().Msgf(\"intervalSecs for tail mode not set, using default %ds\", defaultTickerIntervalSecs)\n\t\ttickerInterval = time.Duration(defaultTickerIntervalSecs)\n\n\t} else {\n\t\tlog.Info().Msgf(\"configured to check for file changes every %d second(s)\", tickerInterval)\n\t}\n\tticker := time.NewTicker(tickerInterval * time.Second)\n\tquitChan := make(chan bool, 10)\n\tsyscallChan := make(chan os.Signal, 10)\n\tsignal.Notify(syscallChan, os.Interrupt)\n\tsignal.Notify(syscallChan, syscall.SIGTERM)\n\tworklog := NewWorklog(conf.WorklogPath)\n\tvar readers []*FileTailReader\n\terr := worklog.Init()\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"\")\n\t\tquitChan <- true\n\n\t} else {\n\t\treaders, err = initReaders(processors, worklog)\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"\")\n\t\t\tquitChan <- true\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(len(readers))\n\t\t\tfor _, reader := range readers {\n\t\t\t\tgo func(rdr *FileTailReader) {\n\t\t\t\t\tactionChan, writer := rdr.Processor().OnCheckStart()\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tfor action := range actionChan {\n\t\t\t\t\t\t\tswitch action := action.(type) {\n\t\t\t\t\t\t\tcase save.ConfirmMsg:\n\t\t\t\t\t\t\t\tif action.Error != nil {\n\t\t\t\t\t\t\t\t\tlog.Error().Err(action.Error).Msg(\"Failed to write data to one of target databases\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tworklog.UpdateFileInfo(action.FilePath, action.Position)\n\t\t\t\t\t\t\tcase save.IgnoredItemMsg:\n\t\t\t\t\t\t\t\tworklog.UpdateFileInfo(action.FilePath, action.Position)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\twg.Done()\n\t\t\t\t\t}()\n\t\t\t\t\tprevPos := worklog.GetData(rdr.processor.FilePath())\n\t\t\t\t\trdr.ApplyNewContent(rdr.Processor(), writer, prevPos)\n\t\t\t\t\trdr.Processor().OnCheckStop(writer)\n\t\t\t\t}(reader)\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\t// all processors are done for this checking period, now let's store bot candidates\n\t\t\t// and reset bot candidates (IP request statistics are not affected)\n\t\t\tanalyzer.StoreBotCandidates()\n\t\t\tanalyzer.ResetBotCandidates()\n\n\t\tcase quit := <-quitChan:\n\t\t\tif quit {\n\t\t\t\tticker.Stop()\n\t\t\t\tfor _, processor := range processors {\n\t\t\t\t\tprocessor.OnQuit()\n\t\t\t\t}\n\t\t\t\tworklog.Close()\n\t\t\t\tfinishEvent <- true\n\t\t\t}\n\t\tcase <-syscallChan:\n\t\t\tlog.Warn().Msg(\"Caught signal, exiting...\")\n\t\t\tticker.Stop()\n\t\t\tfor _, reader := range readers {\n\t\t\t\treader.Processor().OnQuit()\n\t\t\t}\n\t\t\tworklog.Close()\n\t\t\tfinishEvent <- true\n\t\t}\n\t}\n}", "func (f *Fs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryType), ch <-chan time.Duration) {\n\tvar uChans []chan time.Duration\n\n\tfor _, u := range f.upstreams {\n\t\tu := u\n\t\tif do := u.f.Features().ChangeNotify; do != nil {\n\t\t\tch := make(chan time.Duration)\n\t\t\tuChans = append(uChans, ch)\n\t\t\twrappedNotifyFunc := func(path string, entryType fs.EntryType) {\n\t\t\t\tnewPath, err := u.pathAdjustment.do(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfs.Logf(f, \"ChangeNotify: unable to process %q: %s\", path, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfs.Debugf(f, \"ChangeNotify: path %q entryType %d\", newPath, entryType)\n\t\t\t\tnotifyFunc(newPath, entryType)\n\t\t\t}\n\t\t\tdo(ctx, wrappedNotifyFunc, ch)\n\t\t}\n\t}\n\n\tgo func() {\n\t\tfor i := range ch {\n\t\t\tfor _, c := range uChans {\n\t\t\t\tc <- i\n\t\t\t}\n\t\t}\n\t\tfor _, c := range uChans {\n\t\t\tclose(c)\n\t\t}\n\t}()\n}", "func (tf *factory) useFile(source *sources.LogSource) bool {\n\t// The user configuration consulted is different depending on what we are\n\t// logging. Note that we assume that by the time we have gotten a source\n\t// from AD, it is clear what we are logging. The `Wait` here should return\n\t// quickly.\n\tlogWhat := tf.cop.Wait(context.Background())\n\n\tswitch logWhat {\n\tcase containersorpods.LogContainers:\n\t\t// docker_container_use_file is a suggestion\n\t\tif !coreConfig.Datadog.GetBool(\"logs_config.docker_container_use_file\") {\n\t\t\treturn false\n\t\t}\n\n\t\t// docker_container_force_use_file is a requirement\n\t\tif coreConfig.Datadog.GetBool(\"logs_config.docker_container_force_use_file\") {\n\t\t\treturn true\n\t\t}\n\n\t\t// if file was suggested, but this source has a registry entry with a\n\t\t// docker socket path, use socket.\n\t\tif source.Config.Identifier != \"\" {\n\t\t\tregistryID := fmt.Sprintf(\"%s:%s\", source.Config.Type, source.Config.Identifier)\n\t\t\tif tf.registry.GetOffset(registryID) != \"\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\n\tcase containersorpods.LogPods:\n\t\treturn coreConfig.Datadog.GetBool(\"logs_config.k8s_container_use_file\")\n\n\tdefault:\n\t\t// if this occurs, then sources have been arriving before the\n\t\t// container interfaces to them are ready. Something is wrong.\n\t\tlog.Warnf(\"LogWhat = %s; not ready to log containers\", logWhat.String())\n\t\treturn false\n\t}\n}", "func TestConfigReloadRotateFiles(t *testing.T) {\n\tserver, _, config := runReloadServerWithConfig(t, \"./configs/reload/file_rotate.conf\")\n\tdefer func() {\n\t\tremoveFile(t, \"log1.txt\")\n\t\tremoveFile(t, \"nats-server1.pid\")\n\t}()\n\tdefer server.Shutdown()\n\n\t// Configure the logger to enable actual logging\n\topts := server.getOpts()\n\topts.NoLog = false\n\tserver.ConfigureLogger()\n\n\t// Load a config that renames the files.\n\tchangeCurrentConfigContent(t, config, \"./configs/reload/file_rotate1.conf\")\n\tif err := server.Reload(); err != nil {\n\t\tt.Fatalf(\"Error reloading config: %v\", err)\n\t}\n\n\t// Make sure the new files exist.\n\tif _, err := os.Stat(\"log1.txt\"); os.IsNotExist(err) {\n\t\tt.Fatalf(\"Error reloading config, no new file: %v\", err)\n\t}\n\tif _, err := os.Stat(\"nats-server1.pid\"); os.IsNotExist(err) {\n\t\tt.Fatalf(\"Error reloading config, no new file: %v\", err)\n\t}\n\n\t// Check that old file can be renamed.\n\tif err := os.Rename(\"log.txt\", \"log_old.txt\"); err != nil {\n\t\tt.Fatalf(\"Error reloading config, cannot rename file: %v\", err)\n\t}\n\tif err := os.Rename(\"nats-server.pid\", \"nats-server_old.pid\"); err != nil {\n\t\tt.Fatalf(\"Error reloading config, cannot rename file: %v\", err)\n\t}\n\n\t// Check that the old files can be removed after rename.\n\tremoveFile(t, \"log_old.txt\")\n\tremoveFile(t, \"nats-server_old.pid\")\n}", "func onDatabaseConfig(cf *CLIConf) error {\n\ttc, err := makeClient(cf, false)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tprofile, err := tc.ProfileStatus()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tdatabase, err := pickActiveDatabase(cf)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\trequires := getDBLocalProxyRequirement(tc, database)\n\t// \"tsh db config\" prints out instructions for native clients to connect to\n\t// the remote proxy directly. Return errors here when direct connection\n\t// does NOT work (e.g. when ALPN local proxy is required).\n\tif requires.localProxy {\n\t\tmsg := formatDbCmdUnsupported(cf, database, requires.localProxyReasons...)\n\t\treturn trace.BadParameter(msg)\n\t}\n\n\thost, port := tc.DatabaseProxyHostPort(*database)\n\trootCluster, err := tc.RootClusterName(cf.Context)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tformat := strings.ToLower(cf.Format)\n\tswitch format {\n\tcase dbFormatCommand:\n\t\tcmd, err := dbcmd.NewCmdBuilder(tc, profile, database, rootCluster,\n\t\t\tdbcmd.WithPrintFormat(),\n\t\t\tdbcmd.WithLogger(log),\n\t\t).GetConnectCommand()\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tfmt.Println(strings.Join(cmd.Env, \" \"), cmd.Path, strings.Join(cmd.Args[1:], \" \"))\n\tcase dbFormatJSON, dbFormatYAML:\n\t\tconfigInfo := &dbConfigInfo{\n\t\t\tdatabase.ServiceName, host, port, database.Username,\n\t\t\tdatabase.Database, profile.CACertPathForCluster(rootCluster),\n\t\t\tprofile.DatabaseCertPathForCluster(tc.SiteName, database.ServiceName),\n\t\t\tprofile.KeyPath(),\n\t\t}\n\t\tout, err := serializeDatabaseConfig(configInfo, format)\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tfmt.Println(out)\n\tdefault:\n\t\tfmt.Printf(`Name: %v\nHost: %v\nPort: %v\nUser: %v\nDatabase: %v\nCA: %v\nCert: %v\nKey: %v\n`,\n\t\t\tdatabase.ServiceName, host, port, database.Username,\n\t\t\tdatabase.Database, profile.CACertPathForCluster(rootCluster),\n\t\t\tprofile.DatabaseCertPathForCluster(tc.SiteName, database.ServiceName), profile.KeyPath())\n\t}\n\treturn nil\n}", "func ReadAndUpdateGCFile(pub pubsub.Publication) {\n\tkey := \"global\"\n\titem, err := pub.Get(key)\n\tif err == nil {\n\t\tgc := item.(types.GlobalConfig)\n\t\t// Any new fields which need defaults/mins applied?\n\t\tchanged := false\n\t\tupdated := types.ApplyGlobalConfig(gc)\n\t\tif !cmp.Equal(gc, updated) {\n\t\t\tlog.Infof(\"EnsureGCFile: updated with defaults %v\",\n\t\t\t\tcmp.Diff(gc, updated))\n\t\t\tchanged = true\n\t\t}\n\t\tsane := types.EnforceGlobalConfigMinimums(updated)\n\t\tif !cmp.Equal(updated, sane) {\n\t\t\tlog.Infof(\"EnsureGCFile: enforced minimums %v\",\n\t\t\t\tcmp.Diff(updated, sane))\n\t\t\tchanged = true\n\t\t}\n\t\tgc = sane\n\t\tif changed {\n\t\t\terr := pub.Publish(key, gc)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Publish for globalConfig failed: %s\",\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Warn(\"No globalConfig in /persist; creating it with defaults\")\n\t\terr := pub.Publish(key, types.GlobalConfigDefaults)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Publish for globalConfig failed %s\\n\",\n\t\t\t\terr)\n\t\t}\n\t}\n\t// Make sure we have a correct symlink from /var/tmp/zededa so\n\t// others can subscribe from there\n\tinfo, err := os.Lstat(symlinkDir)\n\tif err == nil {\n\t\tif (info.Mode() & os.ModeSymlink) != 0 {\n\t\t\treturn\n\t\t}\n\t\tlog.Warnf(\"Removing old %s\", symlinkDir)\n\t\tif err := os.RemoveAll(symlinkDir); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif err := os.Symlink(globalConfigDir, symlinkDir); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func configDiffs(base string) (map[string]struct{}, error) {\n\tbase, err := filepath.Abs(base)\n\tif !strings.HasSuffix(base, string(filepath.Separator)) {\n\t\tbase += string(filepath.Separator)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runCmd(base, \"git\", \"rev-parse\", \"--show-toplevel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgitroot := strings.Trim(string(out), \"\\n\")\n\tlog.Infof(\"config git root %s\", gitroot)\n\n\tresults := map[string]struct{}{}\n\tout, err = runCmd(base, \"git\", \"status\", \"--porcelain\", \"-uall\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif !statusPattern.MatchString(line) {\n\t\t\tcontinue\n\t\t}\n\t\tpath := filepath.Join(gitroot, line[3:])\n\t\tif !strings.HasPrefix(path, base) {\n\t\t\tcontinue\n\t\t}\n\t\tresults[path[len(base):]] = struct{}{}\n\t}\n\treturn results, nil\n}", "func initializeConfigFile() Configuration {\n\t// check if ~/.kube/kubectl exists if not create it\n\t// log.Print(\"[DEBUG] checking ~/.kube/kubectl\")\n\thome, err := CreateKubectlHome()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// if env var does not exists try to read from ~/.kube/kubectl/config\n\tconfig := fmt.Sprintf(\"%v/config\", home)\n\tif _, err := os.Stat(config); os.IsNotExist(err) {\n\t\t_, err := os.Create(config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tseed, seedErr := json.MarshalIndent(SeedData(), \"\", \" \")\n\t\tif seedErr != nil {\n\t\t\tpanic(seedErr)\n\t\t}\n\t\tlog.Print(\"[DEBUG] writing file ~/.kube/kubectl/config\")\n\t\tnoWriteErr := ioutil.WriteFile(config, seed, 0666)\n\t\tif noWriteErr != nil {\n\t\t\tpanic(noWriteErr)\n\t\t}\n\t}\n\t// log.Print(\"[DEBUG] File ~/.kube/kubectl/config exists now reading it....\")\n\t// config file is already exists at this point (created above or already exists) read it now\n\tconfigFile, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get configFile:: %v\", configFile)\n\t\tpanic(err)\n\t}\n\tdata := Configuration{}\n\tjsonErr := json.Unmarshal([]byte(configFile), &data)\n\tif jsonErr != nil {\n\t\tpanic(jsonErr)\n\t}\n\treturn data\n}", "func checkLogPath(filename string) {\n\tfd, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"LoadConfiguration: Error: Could not open %q for reading: %s\\n\", filename, err)\n\t\tos.Exit(1)\n\t}\n\n\t//read xml file\n\tcontents, err := ioutil.ReadAll(fd)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"LoadConfiguration: Error: Could not read %q: %s\\n\", filename, err)\n\t\tos.Exit(1)\n\t}\n\n\txc := new(xmlLoggerConfig)\n\tif err := xml.Unmarshal(contents, xc); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"LoadConfiguration: Error: Could not parse XML configuration in %q: %s\\n\", filename, err)\n\t\tos.Exit(1)\n\t}\n\t//stdout kworker trace--new\n\t//parse xml file\n\tfor _, xmlfilt := range xc.Filter {\n\t\tif xmlfilt.Enabled == \"true\" {\n\t\t\t//获取 log.xml中的level\n\t\t\tif _, ok := logutils.LevelMap[xmlfilt.Level]; ok {\n\t\t\t\t//取出配置文件中最小的级别\n\t\t\t\tif logutils.LevelMap[xmlfilt.Level] < logutils.SortLevel {\n\t\t\t\t\tlogutils.SortLevel = logutils.LevelMap[xmlfilt.Level]\n\t\t\t\t\tlogutils.Level = xmlfilt.Level\n\t\t\t\t}\n\t\t\t}\n\t\t\tif xmlfilt.Tag != \"stdout\" {\n\t\t\t\t//init the file\n\t\t\t\tfor _, prop := range xmlfilt.Property {\n\t\t\t\t\tif prop.Name == \"filename\" {\n\t\t\t\t\t\tpaths := strings.Split(prop.Value, \"/\")\n\t\t\t\t\t\tif len(paths) > 1 {\n\t\t\t\t\t\t\tdir := strings.Join(paths[0:len(paths)-1], \"/\")\n\t\t\t\t\t\t\terr := os.MkdirAll(dir, 0755)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"LoadConfiguration: Error: Could not create directory %s, err:%s\\n\", dir, err)\n\t\t\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"LoadConfiguration: Error: log directory invalid %s, err:%s\\n\", prop.Value, err)\n\t\t\t\t\t\t\tos.Exit(1)\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}\n\t}\n\n}", "func (f *FetcherDefault) watchLocalFiles(ctx context.Context) {\n\tf.lock.Lock()\n\n\trepoChanged := false\n\tcancelWatchers := make(map[string]context.CancelFunc, len(f.cancelWatchers))\n\n\tlocalFiles, _ := splitLocalRemoteRepos(f.config.AccessRuleRepositories())\n\tfor _, fp := range localFiles {\n\t\tif cancel, ok := f.cancelWatchers[fp]; !ok {\n\t\t\t// watch all files we are not yet watching\n\t\t\trepoChanged = true\n\t\t\tctx, cancelWatchers[fp] = context.WithCancel(ctx)\n\t\t\tw, err := watcherx.WatchFile(ctx, fp, f.events)\n\t\t\tif err != nil {\n\t\t\t\tf.registry.Logger().WithError(err).WithField(\"file\", fp).Error(\"Unable to watch file, ignoring it.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// we force reading the files\n\t\t\tdone, err := w.DispatchNow()\n\t\t\tif err != nil {\n\t\t\t\tf.registry.Logger().WithError(err).WithField(\"file\", fp).Error(\"Unable to read file, ignoring it.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo func() { <-done }() // we do not need to wait here, but we need to clear the channel\n\t\t} else {\n\t\t\t// keep watching files we are already watching\n\t\t\tcancelWatchers[fp] = cancel\n\t\t}\n\t}\n\n\t// cancel watchers for files we are no longer watching\n\tfor fp, cancel := range f.cancelWatchers {\n\t\tif _, ok := cancelWatchers[fp]; !ok {\n\t\t\tf.registry.Logger().WithField(\"file\", fp).Info(\"Stopped watching access rule file.\")\n\t\t\trepoChanged = true\n\t\t\tcancel()\n\n\t\t\tdelete(f.cache, fp)\n\t\t}\n\t}\n\tf.cancelWatchers = cancelWatchers\n\n\tf.lock.Unlock() // release lock before processing events\n\n\tif repoChanged {\n\t\tf.registry.Logger().WithField(\"repos\", f.config.Get(configuration.AccessRuleRepositories)).Info(\"Detected access rule repository change, processing updates.\")\n\t\tif err := f.updateRulesFromCache(ctx); err != nil {\n\t\t\tf.registry.Logger().WithError(err).WithField(\"event_source\", \"local repo change\").Error(\"Unable to update access rules.\")\n\t\t}\n\t}\n}", "func main() {\n\thome := os.Getenv(\"HOME\")\n\t// fmt.Println(home)\n\tsep := string(os.PathSeparator)\n\t// f := \"/home/owen/.ssh/config\"\n\tf := fmt.Sprintf(\"%s%s.ssh%sconfig\", home, sep, sep)\n\t// fmt.Println(f)\n\tfmt.Println(\"configured host list\")\n\tcf, err := os.Open(f)\n\tif err != nil {\n\t\tlog.Fatal(\"file not found. \", err)\n\t}\n\tdefer cf.Close()\n\n\tr := bufio.NewReader(cf)\n\n\tvar s scanner.Scanner\n\ts.Init(r)\n\tvar prev string\n\tfor tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {\n\t\t// fmt.Printf(\"%s: [%s]\\n\", s.Position, s.TokenText())\n\t\ttxt := s.TokenText()\n\t\tif prev == \"Host\" {\n\t\t\tfmt.Println(txt)\n\t\t}\n\t\tprev = txt\n\t}\n}", "func NewConfigFile(path string) (self *ConfigFile, err error) {\n\tself = &ConfigFile{\n\t\tLocalSmartServer: \"127.0.0.1:1315\",\n\t\tLocalNormalServer: \"127.0.0.1:1316\",\n\t}\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(buf, self)\n\tif err != nil {\n\t\treturn\n\t}\n\tself.PrivateKey = os.ExpandEnv(self.PrivateKey)\n\tsort.Strings(self.BlockedList)\n\treturn\n}" ]
[ "0.64610916", "0.60868067", "0.59415656", "0.58568406", "0.57661414", "0.5655298", "0.5644092", "0.56246734", "0.55102056", "0.54824513", "0.53973293", "0.5292508", "0.51622623", "0.5124967", "0.5093944", "0.50582874", "0.50582874", "0.5034627", "0.5031129", "0.50048363", "0.496868", "0.49677205", "0.4961296", "0.4911993", "0.48938674", "0.48754972", "0.48752", "0.48556095", "0.48516715", "0.4848264", "0.48450124", "0.4837918", "0.48271433", "0.48269874", "0.48264366", "0.4825271", "0.48225126", "0.4818099", "0.48145816", "0.48142955", "0.48051745", "0.47986695", "0.47874734", "0.4771748", "0.47674933", "0.47629914", "0.4761994", "0.47602597", "0.47599068", "0.47537005", "0.47503358", "0.47425598", "0.4737661", "0.47215167", "0.4721287", "0.4714111", "0.47074914", "0.4705418", "0.47022328", "0.4690217", "0.46861845", "0.4677994", "0.46703136", "0.46681505", "0.46622258", "0.46621528", "0.465374", "0.46535757", "0.46488172", "0.46480358", "0.46458346", "0.46455324", "0.46335548", "0.4631254", "0.46274948", "0.46181732", "0.46151048", "0.46057883", "0.46033704", "0.45999396", "0.45975932", "0.45943156", "0.4593958", "0.45924923", "0.45915326", "0.45911786", "0.45910975", "0.4589193", "0.45860144", "0.45836642", "0.45803764", "0.45788693", "0.45784777", "0.4576421", "0.45717412", "0.45713288", "0.4566825", "0.45649323", "0.45537516", "0.45505464" ]
0.8317628
0
createContext creates a new context based on transactionId, actionId, actionName, threadId, threadName, ProcessName
func createContext(transactionID, actionID, actionName, threadID, threadName, ProcessName string) context.Context { ctx := context.Background() ctx = context.WithValue(ctx, common.TransactionID, transactionID) ctx = context.WithValue(ctx, common.ActionID, actionID) ctx = context.WithValue(ctx, common.ActionName, actionName) ctx = context.WithValue(ctx, common.ThreadID, threadID) ctx = context.WithValue(ctx, common.ThreadName, threadName) ctx = context.WithValue(ctx, common.ProcessName, ProcessName) return ctx }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createContext(fhandler *flowHandler) *faasflow.Context {\n\tcontext := faasflow.CreateContext(fhandler.id, \"\",\n\t\tflowName, fhandler.dataStore)\n\tcontext.Query, _ = url.ParseQuery(fhandler.query)\n\n\treturn context\n}", "func (c *Constructor) createScenarioContext(\n\tsender string,\n\tsenderValue *big.Int,\n\trecipient string,\n\trecipientValue *big.Int,\n\tchangeAddress string,\n\tchangeValue *big.Int,\n\tcoinIdentifier *types.CoinIdentifier,\n) (*scenario.Context, []*types.Operation, error) {\n\t// We create a deep copy of the scenaerio (and the change scenario)\n\t// to ensure we don't accidentally overwrite the loaded configuration\n\t// while hydrating values.\n\tscenarioOps := []*types.Operation{}\n\tif err := copier.Copy(&scenarioOps, c.scenario); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"%w: unable to copy scenario\", err)\n\t}\n\n\tif len(changeAddress) > 0 {\n\t\tchangeCopy := types.Operation{}\n\t\tif err := copier.Copy(&changeCopy, c.changeScenario); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"%w: unable to copy change intent\", err)\n\t\t}\n\n\t\tscenarioOps = append(scenarioOps, &changeCopy)\n\t}\n\n\treturn &scenario.Context{\n\t\tSender: sender,\n\t\tSenderValue: senderValue,\n\t\tRecipient: recipient,\n\t\tRecipientValue: recipientValue,\n\t\tCurrency: c.currency,\n\t\tCoinIdentifier: coinIdentifier,\n\t\tChangeAddress: changeAddress,\n\t\tChangeValue: changeValue,\n\t}, scenarioOps, nil\n}", "func CreateTestContext(c qhttp.Controller, r *http.Request) (context *qhttp.Context) {\n\tw := httptest.NewRecorder()\n\trouter := qhttp.CreateRouter(c)\n\tcontext = qhttp.CreateContext(w, r, router)\n\treturn context\n}", "func NewContext(trigger trigger.Type, bc blockchainer.Blockchainer, d dao.DAO,\n\tgetContract func(dao.DAO, util.Uint160) (*state.Contract, error), natives []Contract,\n\tblock *block.Block, tx *transaction.Transaction, log *zap.Logger) *Context {\n\tbaseExecFee := int64(DefaultBaseExecFee)\n\tdao := d.GetWrapped()\n\n\tif bc != nil && (block == nil || block.Index != 0) {\n\t\tbaseExecFee = bc.GetPolicer().GetBaseExecFee()\n\t}\n\treturn &Context{\n\t\tChain: bc,\n\t\tNetwork: uint32(bc.GetConfig().Magic),\n\t\tNatives: natives,\n\t\tTrigger: trigger,\n\t\tBlock: block,\n\t\tTx: tx,\n\t\tDAO: dao,\n\t\tLog: log,\n\t\tInvocations: make(map[util.Uint160]int),\n\t\tgetContract: getContract,\n\t\tbaseExecFee: baseExecFee,\n\t}\n}", "func CreateContext(masterKey, masterSalt []byte, profile string, ssrc uint32) (c *Context, err error) {\n\tif masterKeyLen := len(masterKey); masterKeyLen != keyLen {\n\t\treturn c, errors.Errorf(\"SRTP Master Key must be len %d, got %d\", masterKey, keyLen)\n\t} else if masterSaltLen := len(masterSalt); masterSaltLen != saltLen {\n\t\treturn c, errors.Errorf(\"SRTP Salt must be len %d, got %d\", saltLen, masterSaltLen)\n\t}\n\n\tc = &Context{\n\t\tmasterKey: masterKey,\n\t\tmasterSalt: masterSalt,\n\t\tssrc: ssrc,\n\t}\n\n\tif c.sessionKey, err = c.generateSessionKey(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.sessionSalt, err = c.generateSessionSalt(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.block, err = aes.NewCipher(c.sessionKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func createAppContext() {\n\t//init data access layer\n\trepo.InitRepo(\n\t\tos.Getenv(\"APP_CONNECTION_POOL_SIZE\"),\n\t\tos.Getenv(\"DB_PORT\"),\n\t\tos.Getenv(\"DB_HOST\"),\n\t\tos.Getenv(\"DB_USER\"),\n\t\tos.Getenv(\"DB_PASSWORD\"),\n\t\tos.Getenv(\"DB_NAME\"))\n\t//init services layer\n\tservice.InitService()\n\t//init HTTP API layer\n\tapi.InitHttp()\n}", "func makeContext(manager *Manager, params helpers.H) *Context {\n\tcontext := &Context{\n\t\tmanager: manager,\n\t\tparams: helpers.MakeDictionary(params),\n\t}\n\n\treturn context\n}", "func createContext(ctx context.Context, t uint64) (context.Context, context.CancelFunc) {\n\ttimeout := time.Duration(t) * time.Millisecond\n\treturn context.WithTimeout(ctx, timeout*time.Millisecond)\n}", "func NewContext(ctx context.Context, txn Transaction) context.Context {\n\treturn context.WithValue(ctx, contextKey, txn)\n}", "func createContext(t *testing.T, role browser.Role, lic bool) context.Context {\n\tt.Helper()\n\n\tu := &browser.User{\n\t\tRole: role,\n\t\tLicense: lic,\n\t}\n\treturn context.WithValue(context.Background(), browser.UserContextKey, u)\n}", "func makeContext(params helpers.H) *Context {\n\tcontext := &Context{\n\t\tparams: params,\n\t}\n\n\treturn context\n}", "func NewContext(ctx context.Context, txn Transaction) context.Context {\n\treturn context.WithValue(ctx, transactionKey, txn)\n}", "func (f *framework) createContext() context.Context {\n\treturn context.WithValue(context.Background(), epochKey, f.epoch)\n}", "func ContextCreate() (*Context, error) {\n\tcontext := newContext()\n\treturn context, nil\n}", "func CreateContext(hDc unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpCreateContext, 1, uintptr(hDc), 0, 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (app *BaseApp) NewContext(isCheckTx bool, header abci.Header) ctx.Context {\n\tif isCheckTx {\n\t\treturn ctx.NewContext(app.checkState.ms, header, true, app.Logger, app.registerMappers)\n\t}\n\treturn ctx.NewContext(app.deliverState.ms, header, false, app.Logger, app.registerMappers)\n}", "func NewContext(w http.ResponseWriter, r *http.Request) (*Context, error) {\n var s *Session\n var u *UserSession\n var err error\n\n s, err = GetSession(w, r)\n if err != nil {\n return nil, err\n }\n\n u, err = GetUserSession(w, r)\n if err != nil {\n return nil, err\n }\n\n data := setup(w, r, u, s)\n\n return &Context{\n W: w,\n R: r,\n Session: s,\n UserSession: u,\n Data: data,\n }, nil\n}", "func NewContext(ctx context.Context, t Trace) context.Context {\n\treturn context.WithValue(ctx, _ctxKey, t)\n}", "func newContext(config *Config) (*Context, error) {\n\tctx := &Context{Env: make(map[string]string)}\n\n\tfor _, envVarName := range config.Envvars {\n\t\tvalue := os.Getenv(envVarName)\n\t\tif value != \"\" {\n\t\t\t//log.Printf(\"Env var %s found with value '%s'\", envVarName, value)\n\t\t\tctx.Env[envVarName] = value\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Env var %s not defined!\", envVarName))\n\t\t}\n\t}\n\n\treturn ctx, nil\n}", "func CreateContext(appToken, servicePublicKey, clientSecretKey, updateToken string) (*Context, error) {\n\n\tif appToken == \"\" {\n\t\treturn nil, errors.New(\"app token is mandatory\")\n\t}\n\n\tskVersion, sk, err := ParseVersionAndContent(\"SK\", clientSecretKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid secret key\")\n\t}\n\n\tpubVersion, pubBytes, err := ParseVersionAndContent(\"PK\", servicePublicKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid public key\")\n\t}\n\n\tif skVersion != pubVersion {\n\t\treturn nil, errors.New(\"public and secret keys must have the same version\")\n\t}\n\n\tcurrentSk, currentPub := sk, pubBytes\n\tpheClient, err := phe.NewClient(currentPub, currentSk)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create PHE client\")\n\t}\n\n\tphes := make(map[uint32]*phe.Client)\n\tphes[pubVersion] = pheClient\n\n\ttoken, err := parseToken(updateToken)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not parse update tokens\")\n\t}\n\n\tcurrentVersion := pubVersion\n\n\tif token != nil {\n\t\tcurVer, err := processToken(token, phes, currentVersion, currentPub, currentSk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcurrentVersion = curVer\n\t}\n\n\treturn &Context{\n\t\tAppToken: appToken,\n\t\tPHEClients: phes,\n\t\tVersion: currentVersion,\n\t\tUpdateToken: token,\n\t}, nil\n}", "func NewContext(block *core.Block, engine db.DB, wb db.WriteBatch) Context {\n\treturn &DefaultContext{\n\t\tqueryEngine: engine,\n\t\twb: wb,\n\t\tblock: block,\n\t\tchannelID: block.Header.ChannelID,\n\t\tevmCtx: &evm.Context{\n\t\t\tBlockHeight: block.GetNumber(),\n\t\t\tBlockTime: block.Header.Time,\n\t\t\tDifficulty: 0,\n\t\t\tGasLimit: 10000000000,\n\t\t\tGasPrice: 0,\n\t\t\tCoinBase: nil,\n\t\t},\n\t\taccounts: make(map[string]*accountInfo),\n\t}\n}", "func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}", "func (p *AlertingProxy) createProxyContext(ctx *contextmodel.ReqContext, request *http.Request, response *response.NormalResponse) *contextmodel.ReqContext {\n\tcpy := *ctx\n\tcpyMCtx := *cpy.Context\n\tcpyMCtx.Resp = web.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{response})\n\tcpy.Context = &cpyMCtx\n\tcpy.Req = request\n\n\t// If RBAC is enabled, the actions are checked upstream and if the user gets here then it is allowed to do an action against a datasource.\n\t// Some data sources require legacy Editor role in order to perform mutating operations. In this case, we elevate permissions for the context that we\n\t// will provide downstream.\n\t// TODO (yuri) remove this after RBAC for plugins is implemented\n\tif !ctx.SignedInUser.HasRole(org.RoleEditor) {\n\t\tnewUser := *ctx.SignedInUser\n\t\tnewUser.OrgRole = org.RoleEditor\n\t\tcpy.SignedInUser = &newUser\n\t}\n\treturn &cpy\n}", "func ComputeCreateContext(source string, target string, class string) (string, error) {\n\treturn computeCreateContext(source, target, class)\n}", "func NewContext(denyNetworkAccess bool, format string, depth int) *Context {\n\tcontext, _ := NewContextWithCache(denyNetworkAccess, format, depth, MemoryCache)\n\treturn context\n}", "func threadCreate(c echo.Context) error {\n\tpprof.Handler(\"threadcreate\").ServeHTTP(c.Response().Writer, c.Request())\n\treturn nil\n}", "func NewContext(outputType ContextType, now time.Time, state *ApplicationState) *Context {\n\treturn &Context{\n\t\toutputType: outputType,\n\t\tcurrentTime: now,\n\t\tgasAccountant: NewNopGasAccountant(),\n\t\tstate: state,\n\t}\n}", "func NewContext(env map[string]string) *ContextImpl {\n\tcntx := &ContextImpl{\n\t\tenv: env,\n\t\ttest: make(map[string]string),\n\t\ttestNumber: 0,\n\t\tcorrelationId: \"\",\n\t}\n\tif cntx.env == nil {\n\t\tcntx.env = make(map[string]string)\n\t}\n\treturn cntx\n}", "func (app *BaseApp) NewContext(isCheckTx bool) sdk.Context {\n\treturn app.NewContextLegacy(isCheckTx, cmtproto.Header{})\n}", "func NewContext(z *Zion, w http.ResponseWriter, r *http.Request) *Context {\n\treturn &Context{\n\t\tzion: z,\n\t\twriter: w,\n\t\trequest: r,\n\t\turlParams: make(map[string]string),\n\t\textras: make(map[string]interface{}),\n\t}\n}", "func (c *canaryImpl) newActivityContext() context.Context {\n\tctx := context.WithValue(context.Background(), ctxKeyActivityRuntime, &activityContext{cadence: c.canaryClient})\n\tctx = context.WithValue(ctx, ctxKeyActivityArchivalRuntime, &activityContext{cadence: c.archivalClient})\n\tctx = context.WithValue(ctx, ctxKeyActivitySystemClient, &activityContext{cadence: c.systemClient})\n\treturn overrideWorkerOptions(ctx)\n}", "func CreateContextQueryLogRequest() (request *ContextQueryLogRequest) {\n\trequest = &ContextQueryLogRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"ContextQueryLog\", \"emr\", \"openAPI\")\n\treturn\n}", "func NewContext(ctx context.Context, l *Log) context.Context {\n\tctx = context.WithValue(ctx, logKey, l)\n\tctx = context.WithValue(ctx, currentStageKey, l.Root)\n\treturn ctx\n}", "func NewContext(wftmplGetter WorkflowTemplateNamespacedGetter, cwftmplGetter ClusterWorkflowTemplateGetter, tmplBase wfv1.TemplateHolder, workflow *wfv1.Workflow) *Context {\n\treturn &Context{\n\t\twftmplGetter: wftmplGetter,\n\t\tcwftmplGetter: cwftmplGetter,\n\t\ttmplBase: tmplBase,\n\t\tworkflow: workflow,\n\t\tlog: log.WithFields(logrus.Fields{}),\n\t}\n}", "func newContext(w http.ResponseWriter, r *http.Request) *Context {\n\treturn &Context{\n\t\tw: w,\n\t\tr: r,\n\t\tdata: nil,\n\t}\n}", "func NewContext() context.Context {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"utils.NewContext\",\n\t}\n\trequestID, err := uuid.NewV4()\n\tif err != nil {\n\t\tlog.WithFields(f).WithError(err).Warn(\"unable to generate a UUID for x-request-id\")\n\t\treturn context.Background()\n\t}\n\n\treturn context.WithValue(context.Background(), XREQUESTID, requestID.String()) // nolint\n}", "func newRuntimeContext(env string, logger *zap.Logger, scope tally.Scope, service workflowserviceclient.Interface) *RuntimeContext {\n\treturn &RuntimeContext{\n\t\tEnv: env,\n\t\tlogger: logger,\n\t\tmetrics: scope,\n\t\tservice: service,\n\t}\n}", "func makeContext(request *http.Request, responseWriter http.ResponseWriter, pathParams ParameterValueMap) *Context {\n\n\tvar context *Context = new(Context)\n\n\t// set the parameters\n\tcontext.Request = request\n\tcontext.ResponseWriter = responseWriter\n\tcontext.PathParams = pathParams\n\n\t// note the format\n\tcontext.Format = getFormatForRequest(request)\n\n\t// <temporary fix for app engine>\n\t// do we need to fix the cookies?\n\tif request.Header != nil {\n\t\tif request.Header[\"Cookie\"] != nil {\n\t\t\tif len(request.Header[\"Cookie\"]) > 0 {\n\t\t\t\tparseCookieHeader(request.Header[\"Cookie\"][0], request)\n\t\t\t}\n\t\t}\n\t}\n\t// </temporary fix for app engine>\n\n\t// return the new context\n\treturn context\n}", "func NewMigrationContext(ctx context.Context) context.Context {\n\treq := &http.Request{Host: \"localhost\"}\n\tparams := url.Values{}\n\tctx = goa.NewContext(ctx, nil, req, params)\n\t// set a random request ID for the context\n\tvar reqID string\n\tctx, reqID = client.ContextWithRequestID(ctx)\n\n\tlog.Debug(ctx, nil, \"Initialized the migration context with Request ID: %v\", reqID)\n\n\treturn ctx\n}", "func NewContext(ctx context.Context, msg string) context.Context {\n\treturn context.WithValue(ctx, logContextKey, msg)\n}", "func NewContext() *Context {\n\tatomicSequences := make([]atomicSequence, 0)\n\n\treturn &Context{\n\t\tatomicSequences: atomicSequences,\n\t}\n}", "func NewContext(fns ...SetContextFn) (ctx context.Context) {\n\tctx = context.TODO()\n\tctx = ApplyContext(ctx, fns...)\n\treturn\n}", "func NewCtx(\n\tservice string,\n\tc *config.Config,\n\tl log.Logger,\n\ts stats.Stats,\n\tsd disco.Agent,\n) Ctx {\n\t// Build background registry\n\treg := bg.NewReg(service, l, s)\n\n\tlf := []log.Field{\n\t\tlog.String(\"node\", c.Node),\n\t\tlog.String(\"version\", c.Version),\n\t\tlog.String(\"log_type\", \"A\"),\n\t}\n\n\tctx, cancelFunc := goc.WithCancel(goc.Background())\n\n\treturn &context{\n\t\tservice: service,\n\t\tappConfig: c,\n\t\tbgReg: reg,\n\t\tdisco: sd,\n\t\tc: ctx,\n\t\tcancelFunc: cancelFunc,\n\t\tl: l.AddCalldepth(1),\n\t\tlFields: lf,\n\t\tstats: s,\n\t}\n}", "func NewContext(o *project.Operator, name, path string) *Context {\n\treturn &Context{\n\t\tOperator: o,\n\t\tName: name,\n\t\tPath: path,\n\t}\n}", "func CreateContext(l, r *yaml.Node) *ChangeContext {\n\tctx := new(ChangeContext)\n\tif l != nil {\n\t\tctx.OriginalLine = &l.Line\n\t\tctx.OriginalColumn = &l.Column\n\t}\n\tif r != nil {\n\t\tctx.NewLine = &r.Line\n\t\tctx.NewColumn = &r.Column\n\t}\n\treturn ctx\n}", "func NewContext() Context {\n\treturn Context{Log: log.New(), Db: rootContext.Db}\n}", "func CreateContextWithTimeout(r *protoTypes.Request) (context.Context, context.CancelFunc) {\n\tctx := context.Background()\n\tcancel := *new(context.CancelFunc)\n\n\tif IsEven(r) {\n\n\t\tfmt.Println(\"Request\", r.Id, \"timeout is\", evenTimeout)\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(evenTimeout)*time.Second)\n\n\t} else {\n\n\t\tfmt.Println(\"Request\", r.Id, \"timeout is\", oddTimeout)\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(oddTimeout)*time.Second)\n\n\t}\n\tfmt.Println(\"Time.Now == \", time.Now())\n\treturn ctx, cancel\n}", "func newContext(wrapped context.Context, identifier int) Context {\n\treturn &contextImpl{wrapped, identifier, false, sync.Mutex{}}\n}", "func NewContext() *context {\n\treturn &context{\n\t\tstore: make(map[uint64]trace.Event),\n\t\tmutex: &sync.Mutex{},\n\t\tcounter: counter.NewCounter(0),\n\t}\n}", "func NewContext(ctx context.Context, tr Tracer) context.Context {\n\treturn trace.NewContext(ctx, tr)\n}", "func NewContext(w http.ResponseWriter, r *http.Request) *Context {\n\tc := Context{}\n\tc.w = &w\n\tc.r = r\n\tc.payload = platform.OutgoingWebhookPayloadFromForm(r.Body)\n\treturn &c\n}", "func (s *AppServer) new(w http.ResponseWriter, r *http.Request, params *AppParams, handlers []Middleware) *Context {\n\t// adjust request id\n\trequestId := r.Header.Get(s.requestId)\n\tif requestId == \"\" {\n\t\trequestId = NewObjectId().Hex()\n\n\t\t// inject request header with new request id\n\t\tr.Header.Set(s.requestId, requestId)\n\t}\n\tw.Header().Set(s.requestId, requestId)\n\n\tctx := s.pool.Get().(*Context)\n\tctx.Request = r\n\tctx.Response = &ctx.writer\n\tctx.Params = params\n\tctx.Logger = s.logger.New(requestId)\n\tctx.settings = nil\n\tctx.frozenSettings = nil\n\tctx.writer.reset(w)\n\tctx.handlers = handlers\n\tctx.index = -1\n\tctx.startedAt = time.Now()\n\tctx.downAfter = ctx.startedAt.Add(s.slowdown)\n\n\treturn ctx\n}", "func CreateTransportContext(ctx context.Context) (context.Context, context.CancelFunc) {\n\tcalc := tlectx.NewTimeoutCalculator()\n\tvar cancel context.CancelFunc\n\n\t_, newCtx := tlectx.GetOrCreateCorrelationFromContext(ctx, true)\n\tduration, deadline := calc.NextTimeoutFromContext(newCtx)\n\n\tnewCtx = tlectx.SetTimeout(newCtx, duration, deadline)\n\tnewCtx, cancel = context.WithDeadline(newCtx, deadline)\n\n\treturn newCtx, cancel\n}", "func (s *BasePlSqlParserListener) EnterCreate_context(ctx *Create_contextContext) {}", "func NewContext(user, password, address string) Context {\n\tvar ctx Context\n\tctx.User = user\n\tctx.Password = password\n\tctx.Address = address\n\treturn ctx\n}", "func NewContext(ctx context.Context, trace HandlerTrace) context.Context {\n\texisting := FromContext(ctx)\n\treturn context.WithValue(ctx, handlerTraceKey{}, HandlerTrace{\n\t\tRequestEvent: callbackCompose(existing.RequestEvent, trace.RequestEvent),\n\t\tResponseEvent: callbackCompose(existing.ResponseEvent, trace.ResponseEvent),\n\t})\n}", "func CreateLayerContext(hDc unsafe.Pointer, level unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpCreateLayerContext, 2, uintptr(hDc), uintptr(level), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func NewContext(retPc, nlocals int) *Context {\n\treturn &Context{returnPc: retPc, locals: make([]int, nlocals)}\n}", "func NewContext(\n\tcfg *config.Config,\n\tbuildVersion string,\n\tresolver hostname.ResolverChangeNotifier,\n\tlookup host.IDLookup,\n\tsampleMatchFn sampler.IncludeSampleMatchFn,\n) *context {\n\tctx, cancel := context2.WithCancel(context2.Background())\n\n\tvar agentKey atomic.Value\n\tagentKey.Store(\"\")\n\treturn &context{\n\t\tcfg: cfg,\n\t\tCtx: ctx,\n\t\tCancelFn: cancel,\n\t\tid: id.NewContext(ctx),\n\t\treconnecting: new(sync.Map),\n\t\tversion: buildVersion,\n\t\tservicePidLock: &sync.RWMutex{},\n\t\tservicePids: make(map[string]map[int]string),\n\t\tresolver: resolver,\n\t\tidLookup: lookup,\n\t\tshouldIncludeEvent: sampleMatchFn,\n\t\tagentKey: agentKey,\n\t}\n}", "func NewContext(ctx context.Context, cfg config.Config, log log15.Logger) (*Context, error) {\n\tif log == nil {\n\t\treturn nil, errors.New(\"log cannot be nil\")\n\t}\n\tc := &Context{\n\t\tContext: ctx,\n\t\tcfg: cfg,\n\t\tlog: log,\n\t\tapiKeychain: NewKeychain(),\n\t\twebKeychain: NewKeychain(),\n\t}\n\terr := c.registerKeychainFromConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading keys from config: %v\", err)\n\t}\n\tif cfg.Database.MaxOpenConns <= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid value for max open db conns %d\", cfg.Database.MaxOpenConns)\n\t}\n\tc.rateLimit = make(chan struct{}, cfg.Database.MaxOpenConns)\n\tfor i := 0; i < cfg.Database.MaxOpenConns; i++ {\n\t\tc.rateLimit <- struct{}{}\n\t}\n\treturn c, nil\n}", "func NewContext(r *http.Request, w http.ResponseWriter) Context {\n\treturn &ContextInstance{\n\t\tr: NewRequest(r),\n\t\tw: NewResponseWriter(w),\n\t\tvalues: map[ContextKey]interface{}{},\n\t\tstartTime: time.Now(),\n\t}\n}", "func NewContext() {\n\tif messageQueue != nil {\n\t\treturn\n\t}\n\n\tmessageQueue = make(chan *Message, messageQueueLength)\n\tgo processMessageQueue()\n}", "func NewContext(discord *discordgo.Session, guild *discordgo.Guild, textChannel *discordgo.Channel,\n\tuser *discordgo.User, message *discordgo.MessageCreate, cmdHandler *CommandHandler, config Configuration) *Context {\n\tctx := new(Context)\n\tctx.Discord = discord\n\tctx.Guild = guild\n\tctx.TextChannel = textChannel\n\tctx.User = user\n\tctx.Message = message\n\tctx.CmdHandler = cmdHandler\n\tctx.Config = config\n\n\treturn ctx\n}", "func NewContext() (c *Context) {\n\tc = new(Context)\n\tc.Ctx, c.Cancel = context.WithCancel(context.Background())\n\t// don't block if DB and NATS terminated with an error together\n\tc.Err = make(chan error, 2)\n\treturn\n}", "func NewContext(r *http.Request) Context {\n\tac := appengine.NewContext(r)\n\tid := requestID(appengine.RequestID(ac))\n\n\tctxs.RLock()\n\tc, ok := ctxs.m[id]\n\tctxs.RUnlock()\n\n\tif ok {\n\t\treturn c\n\t}\n\n\tc = Context{\n\t\tContext: ac,\n\t\tR: r,\n\t\tcounters: map[string]change{},\n\t\treported: false,\n\t}\n\tctxs.Lock()\n\tctxs.m[id] = c\n\tctxs.Unlock()\n\treturn c\n}", "func newWebContext(r *http.Request, args ToKeyValuer, api string) context.Context {\n\targsMap := args.ToKeyValue()\n\tbucket := argsMap.Bucket()\n\tobject := argsMap.Object()\n\tprefix := argsMap.Prefix()\n\n\tif prefix != \"\" {\n\t\tobject = prefix\n\t}\n\treqInfo := &logger.ReqInfo{\n\t\tDeploymentID: globalDeploymentID,\n\t\tRemoteHost: handlers.GetSourceIP(r),\n\t\tHost: getHostName(r),\n\t\tUserAgent: r.UserAgent(),\n\t\tAPI: api,\n\t\tBucketName: bucket,\n\t\tObjectName: object,\n\t}\n\treturn logger.SetReqInfo(context.Background(), reqInfo)\n}", "func NewLogContext(id uint32, log *LogModule) *LogContext {\r\n\tif id == 0{\r\n\t\tid = atomic.AddUint32(&logID, 1)\r\n\t}\r\n\treturn &LogContext{id, log, log}\r\n}", "func NewProcessContextByCfg(cfg ProcessConfig) *Context {\n\tif cfg.DBFile == \"\" {\n\t\tcfg.DBFile = TmpFile()\n\t}\n\tsm, err := drmaa2os.NewDefaultSessionManager(cfg.DBFile)\n\treturn &Context{\n\t\tSM: sm,\n\t\tDefaultTemplate: cfg.DefaultTemplate,\n\t\tCtxCreationErr: err}\n}", "func NewContextLog(logger zerolog.Logger) []Middleware {\n\tvar mw []Middleware\n\tmw = append(mw, hlog.NewHandler(logger))\n\t// Install some provided extra handler to set some request's context fields.\n\t// Thanks to those handler, all our logs will come with some pre-populated fields.\n\tmw = append(mw, hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {\n\t\thlog.FromRequest(r).Info().\n\t\t\tStr(\"method\", r.Method).\n\t\t\tStr(\"url\", r.URL.String()).\n\t\t\tInt(\"status\", status).\n\t\t\tInt(\"size\", size).\n\t\t\tDur(\"duration\", duration).\n\t\t\tMsg(\"\")\n\t}))\n\tmw = append(mw, hlog.RemoteAddrHandler(\"ip\"))\n\tmw = append(mw, hlog.UserAgentHandler(\"user_agent\"))\n\tmw = append(mw, hlog.RefererHandler(\"referer\"))\n\tmw = append(mw, hlog.RequestIDHandler(\"req_id\", \"Request-Id\"))\n\treturn mw\n}", "func createOriginContext(ruleFile, groupName string) context.Context {\n\treturn promql.NewOriginContext(context.TODO(), map[string]interface{}{\n\t\t\"ruleGroup\": map[string]string{\n\t\t\t\"file\": ruleFile,\n\t\t\t\"name\": groupName,\n\t\t},\n\t})\n}", "func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) {\n\tcontract, err := bindContext(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil\n}", "func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) {\n\tcontract, err := bindContext(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil\n}", "func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) {\n\tcontract, err := bindContext(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil\n}", "func NewContext(address common.Address, backend bind.ContractBackend) (*Context, error) {\n\tcontract, err := bindContext(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Context{ContextCaller: ContextCaller{contract: contract}, ContextTransactor: ContextTransactor{contract: contract}, ContextFilterer: ContextFilterer{contract: contract}}, nil\n}", "func NewContext(l *LARS) *Ctx {\n\n\tc := &Ctx{\n\t\tparams: make(Params, l.mostParams),\n\t}\n\n\tc.response = newResponse(nil, c)\n\n\treturn c\n}", "func newProcessContext(workdir string, stdin io.Reader, stdout, stderr io.Writer) *processContext {\n\treturn &processContext{\n\t\tworkdir: workdir,\n\t\tenv: os.Environ(),\n\t\tstdin: stdin,\n\t\tstdout: stdout,\n\t\tstderr: stderr,\n\t\toutlog: log.New(stdout, \"\", 0),\n\t\terrlog: log.New(stderr, \"gocdk: \", 0),\n\t}\n}", "func NewCreateMessageContext(ctx context.Context, r *http.Request, service *goa.Service) (*CreateMessageContext, error) {\n\tvar err error\n\tresp := goa.ContextResponse(ctx)\n\tresp.Service = service\n\treq := goa.ContextRequest(ctx)\n\treq.Request = r\n\trctx := CreateMessageContext{Context: ctx, ResponseData: resp, RequestData: req}\n\treturn &rctx, err\n}", "func NewContext(c context.Context, dbg func() bool) Context {\n\treturn &ctx{Context: c, dbg: dbg}\n}", "func NewContext(r *http.Request, w http.ResponseWriter, ps httprouter.Params) Context {\n\treturn newContext(r, w, ps)\n}", "func makeContext(ctx *context, path *string, headers, queryParams map[string][]string, pathParams map[string]string, sourceIP string, rawBody *string) {\n\theaders, rawCookies := filterHeaders(headers)\n\tcookies := parseCookies(rawCookies)\n\tbody := parseBody(headers, rawBody)\n\t*ctx = context{\n\t\trequestSourceIP: sourceIP,\n\t\trequestRawURI: path,\n\t\trequestHeaders: headers,\n\t\trequestCookies: cookies,\n\t\trequestQuery: queryParams,\n\t\trequestPathParams: pathParams,\n\t\trequestBody: body,\n\t}\n}", "func New(parent context.Context, id, language string) *Context {\n\treturn &Context{\n\t\tID: id,\n\t\tLanguage: language,\n\t\tContext: context.WithValue(parent, ContextIDKey, id),\n\t}\n}", "func NewContext(\n\tsession *discordgo.Session,\n\tmessage *discordgo.Message,\n\tchannel *discordgo.Channel,\n\tguild *discordgo.Guild,\n\targs []string,\n) Context {\n\treturn Context{\n\t\tSession: session,\n\t\tState: session.State,\n\t\tMessage: message,\n\t\tAuthor: message.Author,\n\t\tChannel: channel,\n\t\tGuild: guild,\n\t\tArgs: args,\n\t}\n}", "func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) {\n\tcontract, err := bindContext(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContextTransactor{contract: contract}, nil\n}", "func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) {\n\tcontract, err := bindContext(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContextTransactor{contract: contract}, nil\n}", "func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) {\n\tcontract, err := bindContext(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContextTransactor{contract: contract}, nil\n}", "func NewContextTransactor(address common.Address, transactor bind.ContractTransactor) (*ContextTransactor, error) {\n\tcontract, err := bindContext(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContextTransactor{contract: contract}, nil\n}", "func NewContext(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, timingKey, &[]buildapi.StageInfo{})\n}", "func (c *Client) CreateVersionContext(ctx context.Context, projectIDOrKey interface{}, input *CreateVersionInput) (*Version, error) {\n\tu := fmt.Sprintf(\"/api/v2/projects/%v/versions\", projectIDOrKey)\n\n\treq, err := c.NewRequest(\"POST\", u, input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tversion := new(Version)\n\tif err := c.Do(ctx, req, &version); err != nil {\n\t\treturn nil, err\n\t}\n\treturn version, nil\n}", "func createEncryptionContext(msgMeta *pb.MessageMetadata) *EncryptionContext {\n\tencCtx := EncryptionContext{\n\t\tAlgorithm: msgMeta.GetEncryptionAlgo(),\n\t\tParam: msgMeta.GetEncryptionParam(),\n\t\tUncompressedSize: int(msgMeta.GetUncompressedSize()),\n\t\tBatchSize: int(msgMeta.GetNumMessagesInBatch()),\n\t}\n\n\tif msgMeta.Compression != nil {\n\t\tencCtx.CompressionType = CompressionType(*msgMeta.Compression)\n\t}\n\n\tkeyMap := map[string]EncryptionKey{}\n\tfor _, k := range msgMeta.GetEncryptionKeys() {\n\t\tmetaMap := map[string]string{}\n\t\tfor _, m := range k.GetMetadata() {\n\t\t\tmetaMap[*m.Key] = *m.Value\n\t\t}\n\n\t\tkeyMap[*k.Key] = EncryptionKey{\n\t\t\tKeyValue: k.GetValue(),\n\t\t\tMetadata: metaMap,\n\t\t}\n\t}\n\n\tencCtx.Keys = keyMap\n\treturn &encCtx\n}", "func NewProcessContext() *Context {\n\treturn NewProcessContextByCfg(ProcessConfig{\n\t\tDBFile: \"\",\n\t\tDefaultTemplate: drmaa2interface.JobTemplate{}})\n}", "func createContext() (bool, string) {\n\tif s.Settings.BearerToken && s.Settings.BearerTokenPath == \"\" {\n\t\tlog.Println(\"INFO: creating kube context with bearer token from K8S service account.\")\n\t\ts.Settings.BearerTokenPath = \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\t} else if s.Settings.BearerToken && s.Settings.BearerTokenPath != \"\" {\n\t\tlog.Println(\"INFO: creating kube context with bearer token from \" + s.Settings.BearerTokenPath)\n\t} else if s.Settings.Password == \"\" || s.Settings.Username == \"\" || s.Settings.ClusterURI == \"\" {\n\t\treturn false, \"ERROR: missing information to create context [ \" + s.Settings.KubeContext + \" ] \" +\n\t\t\t\"you are either missing PASSWORD, USERNAME or CLUSTERURI in the Settings section of your desired state file.\"\n\t} else if !s.Settings.BearerToken && (s.Certificates == nil || s.Certificates[\"caCrt\"] == \"\" || s.Certificates[\"caKey\"] == \"\") {\n\t\treturn false, \"ERROR: missing information to create context [ \" + s.Settings.KubeContext + \" ] \" +\n\t\t\t\"you are either missing caCrt or caKey or both in the Certifications section of your desired state file.\"\n\t} else if s.Settings.BearerToken && (s.Certificates == nil || s.Certificates[\"caCrt\"] == \"\") {\n\t\treturn false, \"ERROR: missing information to create context [ \" + s.Settings.KubeContext + \" ] \" +\n\t\t\t\"caCrt is missing in the Certifications section of your desired state file.\"\n\t}\n\n\t// set certs locations (relative filepath, GCS bucket, AWS bucket)\n\tcaCrt := s.Certificates[\"caCrt\"]\n\tcaKey := s.Certificates[\"caKey\"]\n\tcaClient := s.Certificates[\"caClient\"]\n\n\t// download certs and keys\n\t// GCS bucket+file format should be: gs://bucket-name/dir.../filename.ext\n\t// S3 bucket+file format should be: s3://bucket-name/dir.../filename.ext\n\n\t// CA cert\n\tif caCrt != \"\" {\n\n\t\tcaCrt = downloadFile(caCrt, \"ca.crt\")\n\n\t}\n\n\t// CA key\n\tif caKey != \"\" {\n\n\t\tcaKey = downloadFile(caKey, \"ca.key\")\n\n\t}\n\n\t// client certificate\n\tif caClient != \"\" {\n\n\t\tcaClient = downloadFile(caClient, \"client.crt\")\n\n\t}\n\n\t// bearer token\n\ttokenPath := \"bearer.token\"\n\tif s.Settings.BearerToken && s.Settings.BearerTokenPath != \"\" {\n\t\tdownloadFile(s.Settings.BearerTokenPath, tokenPath)\n\t}\n\n\t// connecting to the cluster\n\tsetCredentialsCmd := \"\"\n\tif s.Settings.BearerToken {\n\t\ttoken := readFile(tokenPath)\n\t\tif s.Settings.Username == \"\" {\n\t\t\ts.Settings.Username = \"helmsman\"\n\t\t}\n\t\tsetCredentialsCmd = \"kubectl config set-credentials \" + s.Settings.Username + \" --token=\" + token\n\t} else {\n\t\tsetCredentialsCmd = \"kubectl config set-credentials \" + s.Settings.Username + \" --username=\" + s.Settings.Username +\n\t\t\t\" --password=\" + s.Settings.Password + \" --client-key=\" + caKey\n\t\tif caClient != \"\" {\n\t\t\tsetCredentialsCmd = setCredentialsCmd + \" --client-certificate=\" + caClient\n\t\t}\n\t}\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", setCredentialsCmd},\n\t\tDescription: \"creating kubectl context - setting credentials.\",\n\t}\n\n\tif exitCode, err := cmd.exec(debug, verbose); exitCode != 0 {\n\t\treturn false, \"ERROR: failed to create context [ \" + s.Settings.KubeContext + \" ]: \" + err\n\t}\n\n\tcmd = command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl config set-cluster \" + s.Settings.KubeContext + \" --server=\" + s.Settings.ClusterURI +\n\t\t\t\" --certificate-authority=\" + caCrt},\n\t\tDescription: \"creating kubectl context - setting cluster.\",\n\t}\n\n\tif exitCode, err := cmd.exec(debug, verbose); exitCode != 0 {\n\t\treturn false, \"ERROR: failed to create context [ \" + s.Settings.KubeContext + \" ]: \" + err\n\t}\n\n\tcmd = command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl config set-context \" + s.Settings.KubeContext + \" --cluster=\" + s.Settings.KubeContext +\n\t\t\t\" --user=\" + s.Settings.Username},\n\t\tDescription: \"creating kubectl context - setting context.\",\n\t}\n\n\tif exitCode, err := cmd.exec(debug, verbose); exitCode != 0 {\n\t\treturn false, \"ERROR: failed to create context [ \" + s.Settings.KubeContext + \" ]: \" + err\n\t}\n\n\tif setKubeContext(s.Settings.KubeContext) {\n\t\treturn true, \"\"\n\t}\n\n\treturn false, \"ERROR: something went wrong while setting the kube context to the newly created one.\"\n}", "func (p *TestPackage) CreateContext(filename string) *gosec.Context {\n\tif err := p.Build(); err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\n\tfor _, pkg := range p.build.pkgs {\n\t\tfor _, file := range pkg.Syntax {\n\t\t\tpkgFile := pkg.Fset.File(file.Pos()).Name()\n\t\t\tstrip := fmt.Sprintf(\"%s%c\", p.Path, os.PathSeparator)\n\t\t\tpkgFile = strings.TrimPrefix(pkgFile, strip)\n\t\t\tif pkgFile == filename {\n\t\t\t\tctx := &gosec.Context{\n\t\t\t\t\tFileSet: pkg.Fset,\n\t\t\t\t\tRoot: file,\n\t\t\t\t\tConfig: gosec.NewConfig(),\n\t\t\t\t\tInfo: pkg.TypesInfo,\n\t\t\t\t\tPkg: pkg.Types,\n\t\t\t\t\tImports: gosec.NewImportTracker(),\n\t\t\t\t\tPassedValues: make(map[string]interface{}),\n\t\t\t\t}\n\t\t\t\tctx.Imports.TrackPackages(ctx.Pkg.Imports()...)\n\t\t\t\treturn ctx\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func NewContext(id *ID, message string, root *json.Root) *Context {\n\treturn &Context{\n\t\tid: id,\n\t\tmessage: message,\n\t\troot: root,\n\t}\n}", "func contextGenerate() context.Context {\n\tctx := context.Background()\n\tif useTestNet {\n\t\tctx = context.WithValue(ctx, testNetKey(\"testnet\"), useTestNet)\n\t}\n\treturn ctx\n}", "func RpnCreateCtx(xbiz *XBusiness, rid int64, d1, d2 *time.Time, m *[]AcctRule, amount, pf float64) RpnCtx {\n\tvar rpnCtx RpnCtx\n\trpnCtx.xbiz = xbiz\n\trpnCtx.m = m\n\trpnCtx.d1 = d1\n\trpnCtx.d2 = d2\n\trpnCtx.rid = rid\n\trpnCtx.stack = make([]float64, 0)\n\trpnCtx.pf = pf\n\trpnCtx.amount = amount\n\trpnCtx.GSRset = false\n\treturn rpnCtx\n}", "func newCONTEXT() *_CONTEXT {\n\tvar c *_CONTEXT\n\tbuf := make([]byte, unsafe.Sizeof(*c)+15)\n\treturn (*_CONTEXT)(unsafe.Pointer((uintptr(unsafe.Pointer(&buf[15]))) &^ 15))\n}", "func newAppContext(ctx Context, m *Module) Context {\n\treturn &appContext{\n\t\tContext: ctx,\n\t\tchain: *m,\n\t\tindex: -1,\n\t}\n}", "func NewContext() *Context {\n\tenv := make(map[string]string)\n\tfor _, i := range os.Environ() {\n\t\tsep := strings.Index(i, \"=\")\n\t\tenv[i[0:sep]] = i[sep+1:]\n\t}\n\treturn &Context{env}\n}", "func NewContext(dir string, config *opt.Options, dataCount uint64) (*Context, error) {\n\tstorages, err := initStorages(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif dataCount > math.MaxUint32 {\n\t\treturn nil, errors.ErrContextOverflow\n\t}\n\n\tcontext := &Context{\n\t\tconfig: config,\n\t\tsp: nil,\n\t\tstorages: storages,\n\t\tlock: sync.RWMutex{},\n\t}\n\n\tcontext.SetStoragePointer(uint32(dataCount))\n\tfmt.Println(\"Create YTFS content success, current sp = \", context.sp)\n\treturn context, nil\n}", "func NewContext(req *events.APIGatewayProxyRequest) *Context {\n\trequest := NewRequest(req)\n\tresponse := NewResponse()\n\n\treturn &Context{request, response}\n}" ]
[ "0.6263343", "0.61419773", "0.5849903", "0.58492774", "0.5811859", "0.5775802", "0.5727892", "0.5718235", "0.5710522", "0.568639", "0.56555706", "0.56526494", "0.56184673", "0.5586914", "0.5569361", "0.5552532", "0.5536888", "0.55319023", "0.5531659", "0.5525962", "0.552445", "0.5517379", "0.5500213", "0.5473289", "0.54595023", "0.5448805", "0.54299086", "0.5418755", "0.54144037", "0.54135054", "0.5386874", "0.53854084", "0.5382047", "0.5374173", "0.53686106", "0.53604627", "0.5352535", "0.53509426", "0.53491753", "0.5334546", "0.5315203", "0.53070354", "0.5306939", "0.52987075", "0.529848", "0.52963424", "0.52949494", "0.5288433", "0.5286149", "0.5286142", "0.52751917", "0.52633846", "0.5261934", "0.5260211", "0.52573484", "0.5252466", "0.525045", "0.5231373", "0.522092", "0.5214548", "0.5202405", "0.5201473", "0.5199455", "0.51955676", "0.5192973", "0.51887476", "0.5179441", "0.51745373", "0.51712054", "0.51648355", "0.5162245", "0.5162245", "0.5162245", "0.5162245", "0.51532894", "0.5141786", "0.5141604", "0.5133537", "0.51297665", "0.51240104", "0.51200056", "0.5114261", "0.5112167", "0.5112167", "0.5112167", "0.5112167", "0.511006", "0.5105865", "0.50980604", "0.50971675", "0.509525", "0.50932044", "0.50918376", "0.5091778", "0.50897557", "0.5087491", "0.50800574", "0.50751114", "0.5071707", "0.50705236" ]
0.81415343
0
main function that will create the client.
func main() { //predef of 4 languages languages[0] = "english" languages[1] = "日本語" languages[2] = "deutsch" languages[3] = "svenska" //starting client client() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\terr := clientMain()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\terr := runClient()\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\n\treturn\n}", "func mainClient() {\n\tfmt.Println(\"Starting Tramservice client\")\n\tclient := new(tramservice.Client)\n\terr := client.Init(ServerAddress)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error connecting to server.\")\n\t}\n}", "func mainClient(ctx *cli.Context) error {\n\tcheckClientSyntax(ctx)\n\taddr := \":\" + strconv.Itoa(warpServerDefaultPort)\n\tswitch ctx.NArg() {\n\tcase 1:\n\t\taddr = ctx.Args()[0]\n\t\tif !strings.Contains(addr, \":\") {\n\t\t\taddr += \":\" + strconv.Itoa(warpServerDefaultPort)\n\t\t}\n\tcase 0:\n\tdefault:\n\t\tfatal(errInvalidArgument(), \"Too many parameters\")\n\t}\n\thttp.HandleFunc(\"/ws\", serveWs)\n\tconsole.Infoln(\"Listening on\", addr)\n\tfatalIf(probe.NewError(http.ListenAndServe(addr, nil)), \"Unable to start client\")\n\treturn nil\n}", "func main() {\n\t// Build a Calico client.\n\tlog.Info(\"Creating Calico client\")\n\tcfg, err := client.LoadClientConfig(\"\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error loading config: %s\", err))\n\t}\n\tc, err := backend.NewClient(*cfg)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error creating client: %s\", err))\n\t}\n\tlog.Info(\"Ensuring datastore is initialized\")\n\terr = c.EnsureInitialized()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error initializing datastore: %s\", err))\n\t}\n\tlog.Info(\"Datastore is initialized\")\n\n\t// Make sure we have a global cluster ID set.\n\tlog.Info(\"Ensuring a cluster guid is set\")\n\tensureClusterGuid(c)\n}", "func main() {\n\n\tvar logger *simple.Logger\n\n\tif os.Getenv(\"LOG_LEVEL\") == \"\" {\n\t\tlogger = &simple.Logger{Level: \"info\"}\n\t} else {\n\t\tlogger = &simple.Logger{Level: os.Getenv(\"LOG_LEVEL\")}\n\t}\n\terr := validator.ValidateEnvars(logger)\n\tif err != nil {\n\t\tos.Exit(-1)\n\t}\n\n\t// setup our client connectors (message producer)\n\tconn := connectors.NewClientConnectors(logger)\n\n\t// call the start server function\n\tlogger.Info(\"Starting server on port \" + os.Getenv(\"SERVER_PORT\"))\n\tstartHttpServer(conn)\n}", "func main() {\n\tfmt.Println(\"Client.go\");\n}", "func ClientMain(player Player) {\n\taddr := DefaultServerAddress\n\tif len(os.Args) > 1 {\n\t\tport, err := strconv.Atoi(os.Args[1])\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"invalid value for port: %q\", os.Args[1])\n\t\t}\n\t\taddr = &net.TCPAddr{\n\t\t\tIP: net.IPv4(127, 0, 0, 1),\n\t\t\tPort: port,\n\t\t}\n\t}\n\tvar state BasicState\n\tclient, err := OpenClient(addr, player, &state)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot connect to server: %s\", err)\n\t\tos.Exit(1)\n\t}\n\tclient.DebugTo = os.Stderr\n\terr = client.Run()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error while running: %s\", err)\n\t\tos.Exit(2)\n\t}\n}", "func init() {\n\tdefaultClient = New(\"\")\n}", "func main() {\n\n\t//init api\n\tserver.Init()\n}", "func main() {\n\t// load environment settings for environment\n\terr := config.ReadConfig(\"config/config.yml\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Load client *service.Client\n\ts := services.NewClient()\n\n\t// load Usecase with client and services\n\tu := usecase.NewUsecase(s)\n\n\t// load controller using usecases\n\tc := controller.NewController(u)\n\n\t// router using controller\n\trouter.NewRouter(c)\n}", "func main() {\n\t// load config and construct the server shared environment\n\tcfg := common.LoadConfig()\n\tlog := services.NewLogger(cfg)\n\n\t// create repository\n\trepo, err := repository.NewRepository(cfg, log)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not create application data repository. Terminating!\")\n\t}\n\n\t// setup GraphQL API handler\n\thttp.Handle(\"/api\", handlers.ApiHandler(cfg, repo, log))\n\n\t// show the server opening info and start the server with DefaultServeMux\n\tlog.Infof(\"Welcome to Fantom Rocks API server on [%s]\", cfg.BindAddr)\n\tlog.Fatal(http.ListenAndServe(cfg.BindAddr, nil))\n}", "func main() {\n\tserver.New().Start()\n}", "func TestNewClient(t *testing.T) {\n\taddress := testListener(t, nil)\n\t_, err := NewClient(address, NewConfig())\n\tassert.Nil(t, err)\n}", "func createclient(conn net.Conn) {\n\n\tlog.Printf(\"createclient: remote connection from: %v\", conn.RemoteAddr())\n\n\tname, err := readInput(conn, \"Please Enter Name: \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twriteFormattedMsg(conn, \"Welcome \"+name)\n\n\t//initialize client struct\n\tclient := &client{\n\t\tMessage: make(chan string),\n\t\tConn: conn,\n\t\tName: name,\n\t\tRoom: \"\",\n\t}\n\n\tlog.Printf(\"new client created: %v %v\", client.Conn.RemoteAddr(), client.Name)\n\n\t//spin off separate send, receive\n\tgo client.send()\n\tgo client.receive()\n\n\t//print help\n\twriteFormattedMsg(conn, help)\n}", "func main() {\n\tlog.Println(\"Starting\")\n\n\t// Client pool\n\tclientPool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tlog.Println(\"New HTTP client\")\n\t\t\tptr := &http.Transport{}\n\t\t\tpclient := &http.Client{Transport: ptr}\n\t\t\treturn pclient\n\t\t},\n\t}\n\n\t// Webserver\n\tif debug {\n\t\thttp.Handle(\"/\", http.FileServer(http.Dir(\".\"))) // Testing only\n\t}\n\thttp.Handle(\"/proxy\", websocket.Handler(socketHandler)) // Handler\n\n\t/*http.HandleFunc(\"/echo\", func(w http.ResponseWriter, req *http.Request) {\n\t\ts := websocket.Server{Handler: websocket.Handler(EchoServer)}\n\t\ts.ServeHTTP(w, req)\n\t})*/\n\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", port), nil)\n\tif err != nil {\n\t\tpanic(\"ListenAndServe: \" + err.Error())\n\t}\n\tlog.Println(\"Shutting down\")\n}", "func init() {\n\tconfig = tendermint_test.ResetConfig(\"rpc_test_client_test\")\n\tchainID = config.GetString(\"chain_id\")\n\trpcAddr = config.GetString(\"rpc_laddr\")\n\tgrpcAddr = config.GetString(\"grpc_laddr\")\n\trequestAddr = rpcAddr\n\twebsocketAddr = rpcAddr\n\twebsocketEndpoint = \"/websocket\"\n\n\tclientURI = client.NewClientURI(requestAddr)\n\tclientJSON = client.NewClientJSONRPC(requestAddr)\n\tclientGRPC = core_grpc.StartGRPCClient(grpcAddr)\n\n\t// TODO: change consensus/state.go timeouts to be shorter\n\n\t// start a node\n\tready := make(chan struct{})\n\tgo newNode(ready)\n\t<-ready\n}", "func main() {\n\tctx := context.Background()\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\t// New server multiplexer\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\n\t// Our gRPC host address\n\tconn := os.Getenv(\"SERVICE_ADDRESS\")\n\tapiAddress := os.Getenv(\"API_ADDRESS\")\n\n\tlog.Printf(\"Connecting to gRPC server on: %s\\n\", conn)\n\tlog.Printf(\"Starting API on: %s\\n\", apiAddress)\n\n\t// Register the handler to an endpoint\n\terr := gw.RegisterUserServiceHandlerFromEndpoint(ctx, mux, conn, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Return a server instance\n\thttp.ListenAndServe(apiAddress, mux)\n}", "func Main(client *http.Client, opts Options) (err error) {\n\t// Load brigades.json\n\tbrigadeMap, err := loadBrigades(opts.Brigades, client)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Create other objects required by the Create function\n\tvar prevVehicles map[string]*Vehicle\n\tapi := VehicleAPI{Key: opts.Apikey, Client: client}\n\n\t// Call Create\n\t_, err = Create(api, brigadeMap, prevVehicles, opts)\n\treturn\n}", "func main() {\n\tclientset, err := NewClientSet()\n\tif err != nil {\n\t\tlog.Fatalf(\"clientset failed to load: %v\", err)\n\t}\n\n\tc := NewController(clientset)\n\n\tstop := make(chan struct{})\n\tdefer close(stop)\n\n\tif err = c.Run(1, stop); err != nil {\n\t\tlog.Fatalf(\"Error running controller: %s\", err.Error())\n\t}\n}", "func runClient(dialString string) {\n\tclient, err := client.New(dialString)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot create gRPC client to %s. %v\", dialString, err)\n\t}\n\tfor {\n\t\ttime.Sleep(10 * time.Second)\n\t\t_, err = client.Hello(context.Background(), &emptypb.Empty{})\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error saying hello. %+v\", err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(\"Hello was successful\")\n\t}\n}", "func main() {\n\t// creds with server crt\n\tcreds, err := credentials.NewClientTLSFromFile(\n\t\t\"tls/server.crt\", \"server.grpc.io\",\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//conn, err := grpc.Dial(\"192.168.1.9:1234\")\n\tconn, err := grpc.Dial(\"localhost:1234\", grpc.WithTransportCredentials(creds))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\tclient := pb.NewHelloServiceClient(conn)\n\treply, err := client.Hello(context.Background(), &pb.String{Value: \"hello\"})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(reply.GetValue())\n}", "func startClient(subj string) {\n\n\tid := uuid.New()\n\tlog.Println(id)\n\tnc.Publish(subj, []byte(id+\" Sun \"+strconv.Itoa(1)))\n\tnc.Publish(subj, []byte(id+\" Rain \"+strconv.Itoa(2)))\n\tnc.Publish(subj, []byte(id+\" Fog \"+strconv.Itoa(3)))\n\tnc.Publish(subj, []byte(id+\" Cloudy \"+strconv.Itoa(4)))\n\tfmt.Println(\"v:\")\n}", "func Main() int {\n\tlog.SetFormatter(&log.JSONFormatter{})\n\n\tlog.Print(\"Loading client config\")\n\tconfig := getConfig()\n\n\tlog.Print(\"Loading client\")\n\tapiClient, err := apixv1beta1client.NewForConfig(config)\n\terrExit(\"Failed to create client\", err)\n\n\tcheckCRDExists(apiClient)\n\tlog.Print(\"Found output CRD\")\n\n\tcs, err := kubernetes.NewForConfig(config)\n\terrExit(\"Failed to create core clientset\", err)\n\n\tlog.Print(\"Creating logging operator client\")\n\tlc, err := logclient.NewForConfig(config)\n\terrExit(\"Failed to create logging operator client\", err)\n\n\tlog.Print(\"Creating Output CRs\")\n\tcreateCrs(cs.CoreV1(), lc)\n\n\tlog.Print(\"Done!\")\n\treturn 0\n}", "func ClientLaunch() {\n\n\tfmt.Println(\"Launching Client!\")\n\ttime.Sleep(500)\n\tfmt.Println(\"--- Ctrl+C or type 'exit' to close server ---\")\n\t// client.Launch()\n\n\tclient := client.NewClient()\n\tclient.Run()\n\n}", "func main() {\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tflag.Parse()\n\n\trestConfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tc := service.New(restConfig)\n\tc.Run(genericapiserver.SetupSignalContext(), 1)\n}", "func main() {\n\tvar (\n\t\thostname string\n\t\tid string\n name string\n client string\n\t\tcache *infra.Cache\n\t\tserver *infra.Server\n\t\tconsole *infra.Console\n\t)\n\n\tflag.Parse()\n\n\tcache = infra.NewCache()\n\n\thostname = *localAddress + \":\" + *localPort\n client = *clientAddress\n\n\t// If an id isn't provided, we use the hostname instead\n\tif *instanceId != \"\" {\n\t\tid = *instanceId\n\t} else {\n\t\tid = hostname\n\t}\n \n if *carrierName != \"\" {\n name = *carrierName\n } else if *ringAddress != \"\" {\n name = *ringAddress\n } else {\n name = hostname\n }\n \n server = infra.NewServer(id, name, hostname, client, cache)\n\tconsole = infra.NewConsole(cache, server)\n\n\t// Spawn goroutines to handle both interfaces\n\tgo server.Run(*ringAddress)\n\tgo console.Run()\n\n\t// Wait fo the server to finish\n\t<-server.Done()\n}", "func setupClient() *Client {\n\treturn &Client{\n\t\terr: make(chan error),\n\t\trequest: make(chan []byte, maxConCurrentMessages),\n\t\tresults: &sync.Map{},\n\t\tresultMessenger: &sync.Map{},\n\t\tlogger: logging.NewNilLogger(),\n\t\tgremlinVersion: \"3\",\n\t}\n}", "func main() {\n\tgo func() { log.Fatal(echoServer()) }()\n\n\terr := clientMain()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func NewClient(config *sdk.Config, credential *auth.Credential) *Client {\n\tvar handler sdk.RequestHandler = func(c *sdk.Client, req request.Common) (request.Common, error) {\n\t\terr := req.SetProjectId(PickResourceID(req.GetProjectId()))\n\t\treturn req, err\n\t}\n\tvar (\n\t\tuaccountClient = *uaccount.NewClient(config, credential)\n\t\tuhostClient = *uhost.NewClient(config, credential)\n\t\tunetClient = *unet.NewClient(config, credential)\n\t\tvpcClient = *vpc.NewClient(config, credential)\n\t\tudpnClient = *udpn.NewClient(config, credential)\n\t\tpathxClient = *pathx.NewClient(config, credential)\n\t\tudiskClient = *udisk.NewClient(config, credential)\n\t\tulbClient = *ulb.NewClient(config, credential)\n\t\tudbClient = *udb.NewClient(config, credential)\n\t\tumemClient = *umem.NewClient(config, credential)\n\t\tuphostClient = *uphost.NewClient(config, credential)\n\t\tpuhostClient = *puhost.NewClient(config, credential)\n\t\tpudbClient = *pudb.NewClient(config, credential)\n\t\tpumemClient = *pumem.NewClient(config, credential)\n\t\tppathxClient = *ppathx.NewClient(config, credential)\n\t)\n\n\tuaccountClient.Client.AddRequestHandler(handler)\n\tuhostClient.Client.AddRequestHandler(handler)\n\tunetClient.Client.AddRequestHandler(handler)\n\tvpcClient.Client.AddRequestHandler(handler)\n\tudpnClient.Client.AddRequestHandler(handler)\n\tpathxClient.Client.AddRequestHandler(handler)\n\tudiskClient.Client.AddRequestHandler(handler)\n\tulbClient.Client.AddRequestHandler(handler)\n\tudbClient.Client.AddRequestHandler(handler)\n\tumemClient.Client.AddRequestHandler(handler)\n\tuphostClient.Client.AddRequestHandler(handler)\n\tpuhostClient.Client.AddRequestHandler(handler)\n\tpudbClient.Client.AddRequestHandler(handler)\n\tpumemClient.Client.AddRequestHandler(handler)\n\tppathxClient.Client.AddRequestHandler(handler)\n\n\treturn &Client{\n\t\tuaccountClient,\n\t\tuhostClient,\n\t\tunetClient,\n\t\tvpcClient,\n\t\tudpnClient,\n\t\tpathxClient,\n\t\tudiskClient,\n\t\tulbClient,\n\t\tudbClient,\n\t\tumemClient,\n\t\tuphostClient,\n\t\tpuhostClient,\n\t\tpudbClient,\n\t\tpumemClient,\n\t\tppathxClient,\n\t}\n}", "func initClient(c *cli.Context) (err error) {\n\tif client, err = v1.New(c.String(\"endpoint\")); err != nil {\n\t\treturn cli.Exit(err, 1)\n\t}\n\treturn nil\n}", "func main() {\n\tfmt.Println(\"HelloWorld!\")\n\tclient, err := api.NewClient(api.DefaultConfig())\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to create api client %s\", err))\n\t}\n\n\t//--------- HTTP api test\n\n\tRunHttp()\n\n\t//------------------ List mebers\n\tfor {\n\t\tlistMembers(client)\n\t\tfmt.Println(\"--------------\")\n\t\ttime.Sleep(time.Second * 3)\n\t}\n\n\t// Leader election\n\n\tkeyboard := charChannel()\n\tvar lsession *LeaderSession = nil\n\tfor {\n\t\tif err != nil || lsession == nil {\n\t\t\tfmt.Println(\"Reinit connection\")\n\t\t\tlsession, err = MakeLeaderElectionSession(client)\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(DefaultMonitorRetryTime)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tselect {\n\t\tcase isLeader := <-lsession.statusChannel:\n\t\t\tfmt.Println(\"I am leader\", isLeader)\n\t\tcase err = <-lsession.errorChannel:\n\t\t\tfmt.Println(fmt.Sprintf(\"Error recived %s\", err))\n\t\tcase ch := <-keyboard:\n\t\t\tif ch == 'q' || ch == 'Q' {\n\t\t\t\tfmt.Println(\"Exit requested\")\n\t\t\t\tlsession.Cancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func main() {\n\tif len(os.Args) < 3 {\n\t\tfmt.Printf(\"wrong parameters\\nUsage: %s host port\\n\", os.Args[0])\n\t\tos.Exit(2)\n\t}\n\n\tmsg, err := client.Dial(os.Args[1], os.Args[2])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n\tfmt.Println(*msg)\n}", "func main() {\n\t// create a listener on TCP port 7777\n\tlis, err := net.Listen(\"tcp\", \":7777\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\t// create a server instance\n\ts := api.Server{}\n\n\t// create the TLS creds\n\tcreds, err := credentials.NewServerTLSFromFile(\"cert/server.crt\", \"cert/server.key\")\n\tif err != nil {\n\t\tlog.Fatalf(\"could not load TLS keys: %s\", err)\n\t}\n\n\t// add credentials to the gRPC options\n\topts := []grpc.ServerOption{grpc.Creds(creds)}\n\n\t// create a gRPC server object\n\tgrpcServer := grpc.NewServer(opts...)\n\n\t// attach the Ping service to the server\n\tapi.RegisterPingServer(grpcServer, &s)\n\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func StartClient(port string) {\n\tfmt.Println(\"StartClient\")\n}", "func newClient(conn net.Conn, server *server) *client {\n\tc := &client{conn: conn, server: server}\n\tgo c.run()\n\treturn c\n}", "func main() {\n\tc := dig.New()\n\n\t_ = c.Provide(config.New)\n\n\t_ = c.Provide(logger.New)\n\n\t_ = c.Provide(func(cfg *config.Config) (statuspb.GrpcStarterClient, error) {\n\t\tconn, err := grpc.Dial(cfg.GRPCStarterAddress, grpc.WithInsecure())\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t// defer conn.Close()\n\t\treturn statuspb.NewGrpcStarterClient(conn), nil\n\t})\n\n\t_ = c.Provide(handlers.New)\n\t_ = c.Provide(router.New)\n\n\terr := c.Invoke(func(cfg *config.Config, r router.Router, l *zap.SugaredLogger) error {\n\t\tdefer l.Sync()\n\t\treturn r.Serve(cfg.Port)\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn\n}", "func main() {\n\n\t// Initialise a controller\n\tvar control = controller.Controller{\n\t\tNodes: make(map[string]*utils.Node),\n\t\tServices: make(map[string]*utils.Service),\n\t\tPods: make(map[string]*utils.Pod),\n\t\tClient: state.GetClientOutOfCluster(),\n\t\tTriggers: triggers.Triggers,\n\t\tFuzzyQueue: make(chan *utils.Event, 100),\n\t\tTimeline: make([]*utils.Event, 0),\n\t}\n\n\tgo control.Run()\n\n\ts := server.Server{Control: &control}\n\ts.Run()\n\n}", "func newClient() (client *Client) {\n\n\tclient = new(Client)\n\n\tid := <-uuidBuilder\n\tclient.Id = id.String()\n\tclient.subscriptions = make(map[string]bool)\n\n\tclients[client.Id] = client\n\n\tlog.WithField(\"clientID\", id.String()).Info(\"Created new Client\")\n\treturn\n}", "func main() {\n\ttrn := terrain.New()\n\n\tctx := message.NewClientContext()\n\tctx.Terrain = trn\n\tctx.Clock = clock.NewService()\n\n\thdlr := handler.New(ctx)\n\n\ttlsConfig, err := crypto.GetClientTlsConfig()\n\tif err != nil {\n\t\tlog.Println(\"WARN: could not load TLS config\")\n\t}\n\n\tvar c net.Conn\n\tif tlsConfig != nil {\n\t\tc, err = tls.Dial(\"tcp\", \"127.0.0.1:9999\", tlsConfig)\n\t} else {\n\t\tc, err = net.Dial(\"tcp\", \"127.0.0.1:9999\")\n\t}\n\n\tif err != nil {\n\t\tpanic(\"Dial: \" + err.Error())\n\t}\n\n\treader := bufio.NewReader(c)\n\tclientIO := &message.IO{\n\t\tReader: reader,\n\t\tWriter: c,\n\t}\n\n\tgo hdlr.Listen(clientIO)\n\n\t/*err = builder.SendPing(clientIO.Writer)\n\tif err != nil {\n\t\tpanic(\"SendPing: \" + err.Error())\n\t}*/\n\n\terr = builder.SendLogin(clientIO.Writer, \"root\", \"root\")\n\tif err != nil {\n\t\tpanic(\"SendLogin: \" + err.Error())\n\t}\n\n\tfor {\n\t}\n\n\t/*err = builder.SendChatSend(clientIO.Writer, \"Hello World!\")\n\tif err != nil {\n\t\tpanic(\"SendChatSend: \" + err.Error())\n\t}*/\n\n\t/*err = c.Close()\n\tif err != nil {\n\t\tpanic(\"Close: \" + err.Error())\n\t}*/\n}", "func main() {\n\t// Construct a new \"server\"; its methods are HTTP endpoints.\n\tserver, err := newServer()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Construct a router which binds URLs + HTTP verbs to methods of server.\n\trouter := httprouter.New()\n\trouter.POST(\"/v1/events\", server.createEvent)\n\trouter.GET(\"/v1/ltv\", server.getLTV)\n\n\t// Listen and serve HTTP traffic on port 3000.\n\tif err := http.ListenAndServe(\":3000\", router); err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\t//establish connection to the primary replica\n\t//connect to server\n\tconn_main_replica, err := net.Dial(\"tcp\", \"localhost:8084\")\n\tdefer conn_main_replica.Close()\n\tif err != nil {\n\t\tpanic(\"Failed connect to conn_main_replica\\n\")\n\t}\n\n\t//load user list for faster access to a list of current users\n\tload_user_list()\n\thandle_requests(conn_main_replica)\n}", "func newClient(address string) (c *client, err error) {\n\tif address, err = Host(address); err != nil {\n\t\treturn\n\t}\n\tc = new(client)\n\tif c.client, err = rpc.Dial(\"tcp\", address); err != nil {\n\t\treturn nil, err\n\t}\n\tc.address = address\n\treturn\n}", "func main() {\n\t// create new connection\n\tclient := newClient()\n\t// set value\n\terr := hSetValue(client)\n\tif err != nil {\n\t\tfmt.Println(\"Error at set value\", err)\n\t}\n}", "func main() {\n\tp, err := proxy.SOCKS5(\"tcp\", \"localhost:8080\", nil, proxy.Direct)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tclient := disgord.New(disgord.Config{\n\t\tBotToken: os.Getenv(\"DISCORD_TOKEN\"),\n\t\tProxy: p, // Anything satisfying the proxy.Dialer interface will work\n\t})\n\tdefer client.Gateway().StayConnectedUntilInterrupted()\n}", "func setupClient() *Client {\n\treturn &Client{\n\t\tlogger: NewNilLogger(),\n\t\tpredicateKey: predicateKeyDefault,\n\t\ttemplate: templateDefault,\n\t\tmaxWorkerCount: maxWorkers,\n\t}\n}", "func main() {\n\t// Make websocket\n\tlog.Println(\"Starting sync server\")\n\n\t// TODO: Use command line flag credentials.\n\tclient, err := db.NewClient(\"localhost:28015\")\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't initialize database: \", err.Error())\n\t}\n\tdefer client.Close()\n\n\trouter := sync.NewServer(client)\n\n\t// Make web server\n\tn := negroni.Classic()\n\tn.UseHandler(router)\n\tn.Run(\":8000\")\n}", "func main() {\n\n\tlog.SetVerbose(log.DEBUG)\n\n\tdefer func() {\n\t\tif r := recover(); nil != r {\n\t\t\tlog.Error(\"%v\", r)\n\t\t}\n\t}()\n\n\t// parse command line args\n\tvar configFile = flag.String(\"conf\", \"conf.json\", \"configuration file\")\n\tflag.Parse()\n\n\tlog.Info(\"Initializing broker with options from %s.\", *configFile)\n\n\t// init configuration\n\tconfig, err := config.Init(*configFile)\n\tcheckError(err)\n\n\tlog.Info(\"Options read were: %v\", config)\n\n\tport, err := strconv.Atoi(config.Get(\"port\", PORT))\n\tcheckError(err)\n\n\tlog.SetPrefix(fmt.Sprintf(\"broker@%d: \", port))\n\n\tbroker, err = brokerimpl.New(config)\n\tcheckError(err)\n\n\tlistenHttp(port)\n\n}", "func setup() Client {\n\tvar (\n\t\tclient Client\n\t\tendPoints EndPoints\n\t\tuserCredentials UserCredentials\n\t\temail string\n\t\tid, secret string\n\t)\n\n\temail = os.Getenv(\"DISCORD_EMAIL\")\n\tid = os.Getenv(\"DISCORD_CLIENT_ID\")\n\tsecret = os.Getenv(\"DISCORD_SECRET\")\n\n\tclient = Client{}\n\tclient.ID, _ = strconv.Atoi(id)\n\tclient.Secret = secret\n\n\tendPoints = EndPoints{}\n\tendPoints.BaseURL = os.Getenv(\"DISCORD_API_URL\")\n\tendPoints.UsersEP = \"/users\"\n\n\tuserCredentials = UserCredentials{}\n\tuserCredentials.Email = email\n\n\tclient.EndPoints = endPoints\n\tclient.UserLogin = userCredentials\n\n\tfmt.Println(client)\n\treturn client\n}", "func main() {\n\taddr := \"localhost:8080\"\n\tclientPublicFilepath := \"../data/client.public.pem\"\n\tprivateFilepath := \"../data/server.private.pem\"\n\tpublicFilepath := \"../data/server.public.pem\"\n\n\t// Generate a self-signed certificate\n\tkeyPair := cert.GenerateRSAKeyOrDie()\n\t_, certBytes := cert.GenerateRootCertOrDie(keyPair, []string{\"localhost\", \"127.0.0.1\"})\n\tcert.WritePrivateKeyAsPEM(keyPair, privateFilepath)\n\tcert.WriteCertAsPEM(certBytes, publicFilepath)\n\n\t// RPC server\n\trpcServer := grpc.NewServer(createGrpcOptions(publicFilepath, privateFilepath)...)\n\trafia.RegisterFarewellerServer(rpcServer, &Farewell{})\n\trafia.RegisterGreeterServer(rpcServer, &Greet{})\n\n\t// Http Server\n\thttpServer := http.NewServeMux()\n\thttpServer.Handle(\"/statusz\", &Statusz{})\n\n\ts := http.Server{\n\t\tAddr: addr,\n\t\tHandler: grpcHandlerFunc(rpcServer, httpServer),\n\t\tTLSConfig: createTLSConfig(clientPublicFilepath),\n\t}\n\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"Serving on %s\\n\", lis.Addr().String())\n\tif err := s.ServeTLS(lis, publicFilepath, privateFilepath); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func StartClient(config *config.ClientConfig, userAgent string) {\n\tlog.Infof(\"Initializing client\")\n\n\t// Check if the config is valid\n\terr := validateConfig(config)\n\n\tif err != nil {\n\t\tlog.Warnf(\"Configuration error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Infof(\"Configuring connection to %s for gRPC operations\", config.GetDialAddr())\n\n\t// Configure connection\n\tconn, err := grpc.Dial(config.GetDialAddr(), grpc.WithInsecure(), grpc.WithUserAgent(userAgent+\";\")) // TODO: Not run insecure\n\n\tif err != nil {\n\t\tlog.Warnf(\"Could not configure connection to host: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer conn.Close()\n\n\t// Create client from connection\n\tclient := api.NewCertificateIssuerClient(conn)\n\n\t// Test connection\n\t_, err = client.Ping(context.Background(), &api.PingRequest{Msg: \"ping\"})\n\n\tif err != nil {\n\t\tlog.Warnf(\"Could not test connection to %s: %v\", config.GetDialAddr(), err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Infof(\"Successfully pinged intercert host\")\n\n\t// Create storage for saving/loading certs\n\tcertStorage := NewCertStorage(config.GetCertStorage())\n\n\t// Configure cert workers\n\tfor w := 1; w <= runtime.NumCPU(); w++ {\n\t\tgo CertWorker(w, client, certStorage)\n\t}\n\n\t// Set up scheduled tasks\n\ttasks := configureTasks(config, certStorage)\n\n\t// Handle termination\n\tconfigureTermination(tasks)\n\n\tlog.Infof(\"Client running - ready to work!\")\n\n\t// Block forever\n\tselect {}\n}", "func newClient(opts *ClientOpts) (*Client, error) {\n\tbaseClient, err := newAPIClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tAPIClient: *baseClient,\n\t}\n\n\t// init base operator\n\tclient.Node = newNodeClient(client)\n\tclient.Namespace = newNameSpaceClient(client)\n\tclient.ConfigMap = newConfigMapClient(client)\n\tclient.Service = newServiceClient(client)\n\tclient.Pod = newPodClient(client)\n\tclient.ReplicationController = newReplicationControllerClient(client)\n\tclient.StatefulSet = newStatefulSetClient(client)\n\tclient.DaemonSet = newDaemonSetClient(client)\n\tclient.Deployment = newDeploymentClient(client)\n\tclient.ReplicaSet = newReplicaSetClient(client)\n\n\treturn client, nil\n}", "func initClient() {\n\tvar err error\n\tk, err = util.CreateClient(viper.GetString(\"host\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Can't connect to Kubernetes API:\", err)\n\t}\n}", "func main() {\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\tForceColors: true,\n\t\tFullTimestamp: true,\n\t})\n\tmlog := logrus.WithFields(logrus.Fields{\n\t\t\"component\": componentName,\n\t\t\"version\": env.Version(),\n\t})\n\n\tgrpc_logrus.ReplaceGrpcLogger(mlog.WithField(\"component\", componentName+\"_grpc\"))\n\tmlog.Infof(\"Starting %s\", componentName)\n\n\tgrpcServer, err := createGRPCServer(mlog)\n\tif err != nil {\n\t\tmlog.WithError(err).Fatal(\"failed to create grpc server\")\n\t}\n\t// Start go routines\n\tgo handleExitSignals(grpcServer, mlog)\n\tserveGRPC(env.ServiceAddr(), grpcServer, mlog)\n}", "func main() {\n\tcreds, err := credentials.NewClientTLSFromFile(\"certs1/server.crt\", \"\")\n\tif err != nil {\n\t\tlog.Fatalf(\"could not load tls cert: %s\", err)\n\t}\n\n\tauth := &Login{\n\t\tUsername:\"admin\",\n\t\tPassword:\"admin123\",\n\t}\n\tconn, err := grpc.Dial(\"localhost:4444\", grpc.WithTransportCredentials(creds),grpc.WithPerRPCCredentials(auth))\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect: %s\", err)\n\t}\n\tdefer conn.Close()\n\tc := pb.NewPingClient(conn)\n\tresponse, err := c.SayHello(context.Background(), &pb.PingMessage{Greeting: \"foo\"})\n\tif err != nil {\n\t\tlog.Fatalf(\"Error when calling SayHello: %s\", err)\n\t}\n\tlog.Printf(\"Response from server: %s\", response.Greeting)\n}", "func main() {\n\n\t// Prepare some dependencies:\n\tlogger := logrus.New()\n\tstorer := new(storageMocks.FakeStorer)\n\n\t// Program the storer mock to respond with _something_:\n\tstorer.CreateCruftReturns(\"12345\", nil)\n\tstorer.ReadCruftReturns(nil, storage.ErrNotFound)\n\n\t// Inject the dependencies into a new Handler:\n\thandler := serviceHandler.New(logger, storer)\n\n\t// Make a new GRPC Server (usually I would have this in a common / shared library, and pre-load it with middleware built from our logger / instrumenter / tracer interfaces):\n\tgrpcServer := grpc.NewServer()\n\n\t// Register our Handler and GRPC Server with our generated service-proto code:\n\tserviceProto.RegisterExampleServer(grpcServer, handler)\n\n\t// Listen for connections:\n\tlistener, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Unable to start GRPC server on TCP address %s\", listenAddress)\n\t}\n\n\t// Start the GRPC server:\n\tif err := grpcServer.Serve(listener); err != nil {\n\t\tlogger.Fatalf(\"Unable to start the GRPC server: %v\", err)\n\t}\n}", "func (d *MinioDriver) createClient(options map[string]string) error {\n\tvar secure bool\n\n\tserver, err := checkParam(\"server\", options)\n\tif err != nil {\n\t\tglog.Warning(\"missing server option\")\n\t\treturn err\n\t}\n\td.server = server\n\n\taccessKey, err := checkParam(\"accessKey\", options)\n\tif err != nil {\n\t\tglog.Warning(\"missing accessKey option\")\n\t\treturn err\n\t}\n\td.accessKey = accessKey\n\tsecretKey, err := checkParam(\"secretKey\", options)\n\tif err != nil {\n\t\tglog.Warning(\"missing secretKey option\")\n\t\treturn err\n\t}\n\td.secretKey = secretKey\n\t// TODO: remember to fix this, since the user could pass false and it would\n\t// become true.\n\t_, err = checkParam(\"secure\", options)\n\tif err == nil {\n\t\tglog.Warning(\"setting secure key true\")\n\t\tsecure = true\n\t}\n\n\tif d.c == nil {\n\t\td.c, err = client.NewMinioClient(server, accessKey, secretKey, \"\", secure)\n\t\tif err != nil {\n\t\t\tglog.Warningf(\"Failed to create new client\", err)\n\t\t\tglog.V(1).Infof(\"server: %s - accesKey: %s - secretKey: %s - secure: %s\", server, accessKey, secretKey, secure)\n\t\t\treturn err\n\t\t}\n\t}\n\t// TODO: implement reusability of a bucket by passing its name as a parameter.\n\tbucketName, err := checkParam(\"bucket\", options)\n\tif err != nil || bucketName == \"\" {\n\t\tif err = d.createBucket(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Create() *ConnectedClient {\n client := ConnectedClient {}\n\n client.ClientSecret = generateClientSecret();\n client.ClientToken = generateClientIdentifier();\n client.ClientName = generateClientName();\n client.VoteHistory = make([]Vote, 0);\n client.QueueHistory = make([]QueueEntry, 0);\n client.ConnectionTime = time.Now();\n client.LastCommunicated = time.Now();\n\n currentClients[client.ClientToken] = &client\n\n return &client\n}", "func RunClient(conf Conf, isCopy bool, isMove bool) {\n\tconn, err := net.DialTimeout(\"tcp\", conf.Connect, conf.Timeout)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Unable to connect to %v - Is a Piknik server running on that host?\",\n\t\t\tconf.Connect))\n\t}\n\tdefer conn.Close()\n\n\tconn.SetDeadline(time.Now().Add(conf.Timeout))\n\treader, writer := bufio.NewReader(conn), bufio.NewWriter(conn)\n\tclient := Client{\n\t\tconf: conf,\n\t\tconn: conn,\n\t\treader: reader,\n\t\twriter: writer,\n\t\tversion: DefaultClientVersion,\n\t}\n\tr := make([]byte, 32)\n\tif _, err = rand.Read(r); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\th0 := auth0(conf, client.version, r)\n\twriter.Write([]byte{client.version})\n\twriter.Write(r)\n\twriter.Write(h0)\n\tif err := writer.Flush(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trbuf := make([]byte, 65)\n\tif nbread, err := io.ReadFull(reader, rbuf); err != nil {\n\t\tif nbread < 2 {\n\t\t\tlog.Fatal(\"The server rejected the connection - Check that it is running the same Piknik version or retry later\")\n\t\t} else {\n\t\t\tlog.Fatal(\"The server doesn't support this protocol\")\n\t\t}\n\t}\n\tif serverVersion := rbuf[0]; serverVersion != client.version {\n\t\tlog.Fatal(fmt.Sprintf(\"Incompatible server version (client version: %v - server version: %v)\",\n\t\t\tclient.version, serverVersion))\n\t}\n\tr2 := rbuf[1:33]\n\th1 := rbuf[33:65]\n\twh1 := auth1(conf, client.version, h0, r2)\n\tif subtle.ConstantTimeCompare(wh1, h1) != 1 {\n\t\tlog.Fatal(\"Incorrect authentication code\")\n\t}\n\tif isCopy {\n\t\tclient.copyOperation(h1)\n\t} else {\n\t\tclient.pasteOperation(h1, isMove)\n\t}\n}", "func main() {\n\taddr := flag.String(\"addr\", \":8086\", \"address of destination service\")\n\tflag.Parse()\n\n\tclient, conn, err := newClient(*addr)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\tdefer conn.Close()\n\n\trsp, err := client.Endpoints(context.Background(), &discovery.EndpointsParams{})\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tmarshaler := jsonpb.Marshaler{EmitDefaults: true, Indent: \" \"}\n\terr = marshaler.Marshal(os.Stdout, rsp)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}", "func main() {\n\targs := os.Args[1:]\n\tcentralSystem := ocpp16.NewCentralSystem(nil, nil)\n\thandler := &CentralSystemHandler{chargePoints: map[string]*ChargePointState{}}\n\tcentralSystem.SetNewChargePointHandler(func(chargePointId string) {\n\t\thandler.chargePoints[chargePointId] = &ChargePointState{connectors: map[int]*ConnectorInfo{}, transactions: map[int]*TransactionInfo{}}\n\t\tlog.WithField(\"client\", chargePointId).Info(\"new charge point connected\")\n\t})\n\tcentralSystem.SetChargePointDisconnectedHandler(func(chargePointId string) {\n\t\tlog.WithField(\"client\", chargePointId).Info(\"charge point disconnected\")\n\t\tdelete(handler.chargePoints, chargePointId)\n\t})\n\tcentralSystem.SetCentralSystemCoreListener(handler)\n\tvar listenPort = defaultListenPort\n\tif len(args) > 0 {\n\t\tport, err := strconv.Atoi(args[0])\n\t\tif err != nil {\n\t\t\tlistenPort = port\n\t\t}\n\t}\n\tlog.Infof(\"starting central system on port %v\", listenPort)\n\tcentralSystem.Start(listenPort, \"/{ws}\")\n\tlog.Info(\"stopped central system\")\n}", "func main() {\n\tfmt.Println(\"Go Demo with net/http server\")\n\n\t// initialize empty itemStore\n\titemStore := store.InitializeStore()\n\tserver.StartRouter(itemStore)\n}", "func main() {\n\tgollery.CliAccess()\n}", "func main() {\n\tif runtime.GOOS != \"linux\" {\n\t\tfmt.Println(aurora.Red(\"Sorry mate, this is a Linux app\"))\n\t\treturn\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\te.Debug = true\n\te.Server.ReadTimeout = 1 * time.Minute\n\te.Server.WriteTimeout = 1 * time.Minute\n\n\tport := \"10591\"\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tport = os.Getenv(\"PORT\")\n\t}\n\n\t// Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\te.Use(middleware.CORS())\n\n\te.GET(\"info\", getInfo)\n\te.POST(\"upgrade\", doUpgrade)\n\n\t// Start the service\n\te.Logger.Fatal(e.Start(\":\" + port))\n}", "func main() {\n\tcalculix := serverCalculix.NewCalculix()\n\terr := rpc.Register(calculix)\n\tif err != nil {\n\t\tfmt.Println(\"Cannot register the calculix\")\n\t\treturn\n\t}\n\trpc.HandleHTTP()\n\tl, e := net.Listen(\"tcp\", \":1234\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\terr = http.Serve(l, nil)\n\tif err != nil {\n\t\tfmt.Println(\"Cannot serve the calculix\")\n\t\treturn\n\t}\n}", "func main() {\n\n\tc.InitConfig()\n\n\tdb.Connect()\n\n\te := echo.New()\n\n\tr.InitRoutes(e)\n\n\te.Use(middleware.CORSWithConfig(middleware.CORSConfig{\n\t\tAllowOrigins: []string{\"http://localhost:3000\"},\n\t\tAllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},\n\t}))\n\n\te.Use(middleware.RequestID())\n\te.Pre(middleware.RemoveTrailingSlash())\n\te.Use(middleware.Recover())\n\n\te.Logger.Fatal(e.Start(\":80\"))\n}", "func main() {\n\tlog.SetFlags(log.LstdFlags | log.Lmicroseconds)\n\tlog.Printf(\"My peers are %v\", os.Getenv(\"PEERS\"))\n\tlog.Printf(\"traffic is %v\", os.Getenv(\"TRAFFIC\"))\n\tpeers := []*node.Peer{}\n\tfor _, s := range strings.Split(os.Getenv(\"PEERS\"), \" \") {\n\t\tp := &node.Peer{\n\t\t\tHost: fmt.Sprintf(\"node-%s\", s),\n\t\t\tPort: s}\n\t\tpeers = append(peers, p)\n\t}\n\n\n\tvar traffic = false\n\tif os.Getenv(\"TRAFFIC\") == \"1\" {\n\t\ttraffic = true\n\t}\n\n\tclientNode = client.NewClient(fmt.Sprintf(\"node-%s\", os.Getenv(\"PORT\")), os.Getenv(\"PORT\"), peers, uiChannel, nodeChannel, traffic)\n\n\terr := clientNode.SetupRPC()\n\tif err != nil {\n\t\tlog.Fatal(\"RPC setup error:\", err)\n\t}\n\terr = clientNode.Peer()\n\tif err != nil {\n\t\tlog.Fatal(\"Peering error:\", err)\n\t}\n\n\tfs := http.FileServer(http.Dir(\"../public\"))\n\thttp.Handle(\"/\", fs)\n\n\thttp.HandleFunc(\"/ws\", handleConnections)\n\thttp.HandleFunc(\"/disconnect\", handleDisconnect)\n\thttp.HandleFunc(\"/connect\", handleConnect)\n\thttp.HandleFunc(\"/getID\", handleGetID)\n\tgo handleMessages()\n\n\tgo func() {\n\t\terr := http.ListenAndServe(HttpPort, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t\t}\n\t}()\n\n\tif traffic == true{\n\t\tclientNode.Start()\n\t}\n\n\tfor {\n\t\ttime.Sleep(time.Hour)\n\t}\n}", "func NewClient() (c *Client) {\n\tc = new(Client)\n\n\t//init Client\n\tc.settings = DefaultSettings\n\tc.Name = \"Steve\"\n\tc.Delegate = make(chan func() error)\n\n\tc.Wd = world.World{\n\t\tEntities: make(map[int32]entity.Entity),\n\t\tChunks: make(map[world.ChunkLoc]*world.Chunk),\n\t}\n\n\treturn\n}", "func MainClient(mon []MonContent) {\n\tfmt.Printf(\"time-init==%s = %s\\n\", strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10), time.RFC3339)\n\tcheckLocal, checkLocalPort := GetOutboundIP()\n\tfmt.Printf(\"LOCAL::%s\\n\", checkLocal.String()+\":\"+strconv.Itoa(checkLocalPort))\n\tif len(mon) > 0 {\n\t\tfor i := range mon {\n\t\t\tconn := Conn{IP: mon[i].IP, Port: mon[i].Port, Sq: mon[i].Send, Rq: mon[i].Recv}\n\t\t\t// for {\n\t\t\t// \tmess := <-sq\n\t\t\t// \tif len(mess) > 0 {\n\t\t\t// \t\tfmt.Printf(\"mosters::%s\\n\", mess)\n\t\t\t// \t\trq <- \"verywell\"\n\t\t\t// \t}\n\t\t\t// \ttime.Sleep(time.Millisecond * 300)\n\t\t\t// }\n\t\t\tconnection(conn)\n\t\t}\n\t}\n\n}", "func makeClient(cmd *cobra.Command, args []string) (*client.UISPAPI, error) {\n\thostname := viper.GetString(\"uisp.hostname\")\n\tscheme := viper.GetString(\"uisp.scheme\")\n\n\thttpc, err := httptransport.TLSClient(httptransport.TLSClientOptions{\n\t\tInsecureSkipVerify: viper.GetBool(\"uisp.skip-verify-tls\"),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := httptransport.NewWithClient(hostname, client.DefaultBasePath, []string{scheme}, httpc)\n\tr.SetDebug(viper.GetBool(\"uisp.debug\"))\n\n\tr.Consumers[\"application/json\"] = runtime.JSONConsumer()\n\n\tr.Producers[\"application/json\"] = runtime.JSONProducer()\n\n\tauth, err := makeAuthInfoWriterCustom(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.DefaultAuthentication = auth\n\n\tappCli := client.New(r, strfmt.Default)\n\tlogDebugf(\"Server url: %v://%v\", scheme, hostname)\n\treturn appCli, nil\n}", "func main() {\n\t// starting server\n\tcuxs.StartServer(engine.Router())\n}", "func makeLink(t *testing.T) (client *Client) {\n\t// start a server\n\tserver := NewServer()\n\terr := server.Register(new(StreamingArith))\n\tif err != nil {\n\t\tt.Fatal(\"Register failed\", err)\n\t}\n\n\t// listen and handle queries\n\tvar l net.Listener\n\tl, serverAddr = listenTCP()\n\tlog.Println(\"Test RPC server listening on\", serverAddr)\n\tgo server.Accept(l)\n\n\t// dial the client\n\tclient, err = Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\n\treturn\n}", "func NewClient(config *core.Config) (c *Client, err error) {\n\t// create client\n\tc = &Client{\n\t\tconfig: config,\n\t\tdone: make(chan bool, 2),\n\t}\n\n\t// create cipher\n\tif c.cipher, err = core.NewCipher(c.config.Cipher, c.config.Passwd); err != nil {\n\t\tlogln(\"core: failed to initialize cipher:\", err)\n\t\treturn\n\t}\n\n\t// create managed net\n\tif c.net, err = nat.NewNetFromCIDR(DefaultClientSubnet); err != nil {\n\t\tlogln(\"nat: failed to create managed subnet:\", err)\n\t\treturn\n\t}\n\n\t// assign a localIP\n\tif c.localIP, err = c.net.Take(); err != nil {\n\t\tlogln(\"nat: faield to assign a localIP:\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func init() {\n\t// use all cpus in the system for concurrency\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tlog.SetOutput(os.Stdout)\n\n\tflag.Parse()\n\n\tif *showUsage {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\n\tvar err error\n\tClient, err = as.NewClient(*Host, *Port)\n\tif err != nil {\n\t\tPanicOnError(err)\n\t}\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", \":9091\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tdao := database.CreateDAO(database.CreateConn())\n\tsvc := service.CreateService(dao)\n\n\tgrpcServer := grpc.NewServer()\n\n\t// attach the Ping service to the server\n\tpb.RegisterDBServer(grpcServer, &svc)\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %s\", err)\n\t}\n}", "func main() {\n\n\tgo func() {\n\t\tdataBase.ConnectDataBase()\n\t}()\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 7777))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\ts := controller.Server{}\n\tgrpcServer := grpc.NewServer()\n\tproto.RegisterAuthenticationServer(grpcServer, &s)\n\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %s\", err)\n\t}\n}", "func ExampleNewClient() {\n\t// initialize registrar\n\treg, err := dosaRenamed.NewRegistrar(\"test\", \"myteam.myservice\", cte1)\n\tif err != nil {\n\t\t// registration will fail if the object is tagged incorrectly\n\t\tfmt.Printf(\"NewRegistrar error: %s\", err)\n\t\treturn\n\t}\n\n\t// use a devnull connector for example purposes\n\tconn := devnull.NewConnector()\n\n\t// create the client using the registrar and connector\n\tclient := dosaRenamed.NewClient(reg, conn)\n\n\terr = client.Initialize(context.Background())\n\tif err != nil {\n\t\tfmt.Printf(\"Initialize error: %s\", err)\n\t\treturn\n\t}\n}", "func main() {\n\t// New Service\n\tservice := micro.NewService(\n\t\tmicro.Name(conf.AppConf.SrvName),\n\t\tmicro.Version(\"1\"),\n\t)\n\n\t// Initialise service\n\tservice.Init()\n\n\t// Initialise models\n\tmodels.Init(false)\n\n\t// Register Handler,each goroutine..\n\thandler.Init( service.Server() )\n\n\t// Register Struct as Subscriber\n\t// micro.RegisterSubscriber(\"go.micro.srv.template\", service.Server(), new(subscriber.Example))\n\t// micro.RegisterSubscriber(\"go.micro.srv.template\", service.Server(), subscriber.Handler)\n\n\t// Run service\n\tif err := service.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\t// get environment variables\n\tport := os.Getenv(portEnv)\n\t// default for port\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\tlog.Print(\"[Info][Main] Creating server...\")\n\ts, err := sessions.NewServer(\":\"+port, os.Getenv(redisAddressEnv),\n\t\tos.Getenv(gameServerImageEnv), deserialiseEnvMap(os.Getenv(gameNodeSelectorEnv)),\n\t\tos.Getenv(cpuLimitEnv))\n\n\tif err != nil {\n\t\tlog.Fatalf(\"[Error][Main] %+v\", err)\n\t}\n\n\tif err := s.Start(); err != nil {\n\t\tlog.Fatalf(\"[Error][Main] %+v\", err)\n\t}\n}", "func createClient() mqtt.Client {\n\topts := mqtt.NewClientOptions()\n\topts.AddBroker(\"tcp://io.adafruit.com:1883\")\n\topts.SetClientID(\"Demo\")\n\t// Username of Adafruit account -> For demo only\n\topts.SetUsername(\"CSE_BBC\")\n\t// Key of Adafruit account: Get from MyKey tab -> For demo only\n\topts.SetPassword(\"\")\n\topts.SetDefaultPublishHandler(messagePubHandler)\n\topts.OnConnect = connectHandler\n\topts.OnConnectionLost = connectLostHandler\n\treturn mqtt.NewClient(opts)\n}", "func client(){\n // Connect to the server through tcp/IP.\n\tconnection, err := net.Dial(\"tcp\", (\"127.0.0.1\" + \":\" + \"9090\"))\n\tupdateListener , listErr := net.Dial(\"tcp\", (\"127.0.0.1\" + \":\" + \"9091\"))\n\t// If connection failed crash.\n\tcheck(err)\n\tcheck(listErr)\n\t//Create separate thread for updating client.\n\tgo update(updateListener)\n\t//Configure the language.\n\tvalidateLang()\n\t//Time to log in to the account.\n\tloginSetUp(connection)\n\t//handling requests from usr\n\thandlingRequests(connection)\n}", "func main() {\n\tapi.Api = API.NewAPI(\n\t\t\"warehouse\", \"config/config.json\", routes, true)\n\n\tcontrollers.Sc = subChecker.NewSubChecker(api.Api.Config.GetEnv(\"HOST_SUB\"))\n\n\tdbConfig, err := api.Api.Config.GetSubcategoryFromFile(\"api\", \"db\")\n\tapi.Api.Logger.CheckErrFatal(err)\n\tapi.Api.Database = database.NewConnector(dbConfig, true, []interface{}{\n\t\tmodels.MusicEntity{},\n\t})\n\n\tapi.Api.Service.Start()\n\tapi.Api.Service.Stop()\n}", "func main() {\n\t// Get clients\n\tds, bucket := InitLibs()\n\t_, err := ds.Put(context.Background(), changesKey, &Changes{ChangesMade: true})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif shouldUpdate(ds) {\n\t\tusers, err := users(ds)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tprintUsers(users)\n\t\tif err := store(bucket, users); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t} else {\n\t\tlog.Println(\"No changes detected...\")\n\t}\n}", "func main() {\n\tlog.SetLevel(log.DebugLevel)\n\n\tif err := setupDB(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tserver, err := setupServer()\n\tif err != nil {\n\t\tlog.Fatal(\"error setting up server: \", err)\n\t}\n\n\tlog.Println(\"--- listening on \", server.Addr)\n\terr = server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Fatal(\"error starting server: \", err)\n\t}\n}", "func initClient(protocol string) {\n\tclientConf = GetDefaultClientConfig()\n\tif protocol == \"\" {\n\t\treturn\n\t}\n\n\t// load client config from rootConfig.Protocols\n\t// default use dubbo\n\tif config.GetApplicationConfig() == nil {\n\t\treturn\n\t}\n\tif config.GetRootConfig().Protocols == nil {\n\t\treturn\n\t}\n\n\tprotocolConf := config.GetRootConfig().Protocols[protocol]\n\tif protocolConf == nil {\n\t\tlogger.Info(\"use default getty client config\")\n\t\treturn\n\t} else {\n\t\t//client tls config\n\t\ttlsConfig := config.GetRootConfig().TLSConfig\n\t\tif tlsConfig != nil {\n\t\t\tclientConf.SSLEnabled = true\n\t\t\tclientConf.TLSBuilder = &getty.ClientTlsConfigBuilder{\n\t\t\t\tClientKeyCertChainPath: tlsConfig.TLSCertFile,\n\t\t\t\tClientPrivateKeyPath: tlsConfig.TLSKeyFile,\n\t\t\t\tClientTrustCertCollectionPath: tlsConfig.CACertFile,\n\t\t\t}\n\t\t}\n\t\t//getty params\n\t\tgettyClientConfig := protocolConf.Params\n\t\tif gettyClientConfig == nil {\n\t\t\tlogger.Debugf(\"gettyClientConfig is nil\")\n\t\t\treturn\n\t\t}\n\t\tgettyClientConfigBytes, err := yaml.Marshal(gettyClientConfig)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = yaml.Unmarshal(gettyClientConfigBytes, clientConf)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif err := clientConf.CheckValidity(); err != nil {\n\t\tlogger.Warnf(\"[CheckValidity] error: %v\", err)\n\t\treturn\n\t}\n\tsetClientGrPool()\n\n\trand.Seed(time.Now().UnixNano())\n}", "func NewClient(c *Config) *rapi.APIClient {\n\n\t// Configure the endpoint host\n\tapiHost := \"console.rumble.run\"\n\tif envHost := os.Getenv(\"RUMBLE_API_HOST\"); envHost != \"\" {\n\t\tapiHost = envHost\n\t}\n\tif c.Host != \"\" {\n\t\tapiHost = c.Host\n\t}\n\n\t// Configure the authorization header\n\theaders := make(map[string]string)\n\tapiKey := os.Getenv(\"RUMBLE_API_KEY\")\n\tif c.Key != \"\" {\n\t\tapiKey = c.Key\n\t}\n\tif apiKey != \"\" {\n\t\theaders[\"Authorization\"] = \"Bearer \" + apiKey\n\t}\n\n\t// Create the client\n\treturn rapi.NewAPIClient(&rapi.Configuration{\n\t\tHost: apiHost,\n\t\tBasePath: \"/api/v1.0\",\n\t\tScheme: \"https\",\n\t\tDefaultHeader: headers,\n\t})\n}", "func runClient(c *cli.Context) error {\n\tfmt.Printf(\"Nothing to do...\\n\\n\")\n\treturn nil\n}", "func main() {\n\tctlConf := parseEnvFlags()\n\tlogger.WithField(\"version\", pkg.Version).\n\t\tWithField(\"ctlConf\", ctlConf).Info(\"starting gameServer operator...\")\n\n\tif err := ctlConf.validate(); err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create controller from environment or flags\")\n\t}\n\n\tclientConf, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create in cluster config\")\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the kubernetes clientset\")\n\t}\n\n\textClient, err := extclientset.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the api extension clientset\")\n\t}\n\n\tagonesClient, err := versioned.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the agones api clientset\")\n\t}\n\n\thealth := healthcheck.NewHandler()\n\twh := webhooks.NewWebHook(ctlConf.CertFile, ctlConf.KeyFile)\n\tagonesInformerFactory := externalversions.NewSharedInformerFactory(agonesClient, defaultResync)\n\tkubeInformationFactory := informers.NewSharedInformerFactory(kubeClient, defaultResync)\n\n\tallocationMutex := &sync.Mutex{}\n\n\tgsController := gameservers.NewController(wh, health, allocationMutex,\n\t\tctlConf.MinPort, ctlConf.MaxPort, ctlConf.SidecarImage, ctlConf.AlwaysPullSidecar,\n\t\tctlConf.SidecarCPURequest, ctlConf.SidecarCPULimit,\n\t\tkubeClient, kubeInformationFactory, extClient, agonesClient, agonesInformerFactory)\n\tgsSetController := gameserversets.NewController(wh, health, allocationMutex,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfleetController := fleets.NewController(wh, health, kubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfaController := fleetallocation.NewController(wh, allocationMutex,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfasController := fleetautoscalers.NewController(wh, health,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\n\tstop := signals.NewStopChannel()\n\n\tkubeInformationFactory.Start(stop)\n\tagonesInformerFactory.Start(stop)\n\n\trs := []runner{\n\t\twh, gsController, gsSetController, fleetController, faController, fasController, healthServer{handler: health},\n\t}\n\tfor _, r := range rs {\n\t\tgo func(rr runner) {\n\t\t\tif runErr := rr.Run(workers, stop); runErr != nil {\n\t\t\t\tlogger.WithError(runErr).Fatalf(\"could not start runner: %s\", reflect.TypeOf(rr))\n\t\t\t}\n\t\t}(r)\n\t}\n\n\t<-stop\n\tlogger.Info(\"Shut down agones controllers\")\n}", "func main() {\n\tgwMux := runtime.NewServeMux()\n\tendPoint := \"localhost:8081\"\n\topt := []grpc.DialOption{grpc.WithTransportCredentials(helper.GetClientCreds())}\n\t// prod\n\tif err := pbfiles.RegisterProdServiceHandlerFromEndpoint(context.Background(), gwMux, endPoint, opt); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// order\n\tif err := pbfiles.RegisterOrderServiceHandlerFromEndpoint(context.Background(), gwMux, endPoint, opt); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttpServer := &http.Server{\n\t\tAddr: \":8080\",\n\t\tHandler: gwMux,\n\t}\n\n\tif err := httpServer.ListenAndServe(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tserver := server.NewHTTPServer()\n\tserver.Start(3000)\n}", "func main() {\n\tserverIP := os.Args[1]\n\tdataPath := os.Args[2]\n\n\tPublicIp = node.GeneratePublicIP()\n\tfmt.Println(\"The public IP is: [%s], DataPath is: %s\", ERR_COL+PublicIp+ERR_END, ERR_COL+dataPath+ERR_END)\n\t// Listener for clients -> cluster\n\tln1, _ := net.Listen(\"tcp\", PublicIp+\"0\")\n\n\t// Listener for server and other nodes\n\tln2, _ := net.Listen(\"tcp\", PublicIp+\"0\")\n\n\tInitializeDataStructs()\n\t// Open Filesystem on Disk\n\tnode.MountFiles(dataPath, WriteIdCh)\n\t// Open Peer to Peer RPC\n\tListenPeerRpc(ln2)\n\t// Connect to the Server\n\tnode.InitiateServerConnection(serverIP, PeerRpcAddr)\n\t// Open Cluster to App RPC\n\tListenClusterRpc(ln1)\n}", "func init() {\n\tmart.Register(&client{})\n}", "func main() {\n\tserver.StartUp(false)\n}", "func NewClient(list, create, show, update, delete_ goa.Endpoint) *Client {\n\treturn &Client{\n\t\tListEndpoint: list,\n\t\tCreateEndpoint: create,\n\t\tShowEndpoint: show,\n\t\tUpdateEndpoint: update,\n\t\tDeleteEndpoint: delete_,\n\t}\n}", "func main() {\n\t// Uses a new etcd Client Plugin for Service Discovery.\n\tregistry := etcdv3.NewRegistry()\n\n\t// A new Service is created.\n\tservice := micro.NewService(\n\t\tmicro.Name(\"nq.ContentPreloader\"),\n\t\tmicro.Version(\"latest\"),\n\t\tmicro.Registry(registry),\n\t)\n\n\tservice.Init()\n\t// Creates a new ContentPreloader.\n\tclient := contentpreloader.New(\n\t\tapi.NewQuizContentService(\"nq.QuizContentService\", service.Client()),\n\t)\n\n\tif client == nil {\n\t\tlog.Fatal(client)\n\t}\n\t// Initialize the 3 available Contents.\n\tclient.InitializeData(\"actors.json\")\n\tclient.InitializeData(\"musicians.json\")\n\tclient.InitializeData(\"scientists.json\")\n\n\t// Starts the Service.\n\tif err := service.Run(); err != nil {\n\t\tlogger.Fatal(err)\n\t}\n}", "func Test_main(t *testing.T) {\n\tfmt.Println(\"addr: \", *addr)\n\tfmt.Println(\"network: \", *network)\n\n\t//go run main in another go routine\n\t/*\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer conn.Close()\n\n\tclient := pb.NewEchoServiceClient(conn)\n\tsimpleMessage, err := client.Echo(context.Background(), &pb.SimpleMessage{Id: \"4567\"})\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tlog.Println(simpleMessage)\n\t}\n\t*/\n}", "func main() {\n\t/*address := \":9998\"\n\n\te := engine.New()\n\tctx := e.Context()\n\n\t// Generate a new terrain\n\tctx.Terrain.Generate()\n\n\tsrv := server.New(address, ctx)\n\tgo srv.Listen()\n\n\te.Start()*/\n}", "func main() {\n\tvar config *util.Config\n\n\tif len(os.Args) > 1 {\n\t\tconfig = util.NewConfig(os.Args[1])\n\t} else {\n\t\tconfig = util.NewConfig()\n\t}\n\n\tif config.Server == \"\" {\n\t\tlog.Fatal(\"Invalid configuration provided\")\n\t}\n\n\tbot := util.InitIRC(config)\n\tdb := util.InitDB(config)\n\trouter := handler.NewHandler(db, config).Router()\n\n\tquoteBot := quoteDB.NewQuoteBot(bot, db, config)\n\n\tsrv := &http.Server{\n\t\tHandler: handlers.CORS()(router),\n\t\tAddr: \":\" + config.WebUIPort,\n\t}\n\n\tdefer db.Close()\n\n\tevent.Initialise(quoteBot)\n\n\t// Run the web server\n\terr := srv.ListenAndServe()\n\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\t// Run the IRC bot\n\tquoteBot.IRC.Loop()\n}", "func createClient(options *Options) (c *Client) {\n\n\t// Create a client\n\tc = new(Client)\n\n\t// Set options (either default or user modified)\n\tif options == nil {\n\t\toptions = ClientDefaultOptions()\n\t}\n\n\t// dial is the net dialer for clientDefaultTransport\n\tdial := &net.Dialer{KeepAlive: options.DialerKeepAlive, Timeout: options.DialerTimeout}\n\n\t// clientDefaultTransport is the default transport struct for the HTTP client\n\tclientDefaultTransport := &http.Transport{\n\t\tDialContext: dial.DialContext,\n\t\tExpectContinueTimeout: options.TransportExpectContinueTimeout,\n\t\tIdleConnTimeout: options.TransportIdleTimeout,\n\t\tMaxIdleConns: options.TransportMaxIdleConnections,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSHandshakeTimeout: options.TransportTLSHandshakeTimeout,\n\t}\n\n\t// Determine the strategy for the http client (no retry enabled)\n\tif options.RequestRetryCount <= 0 {\n\t\tc.httpClient = httpclient.NewClient(\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\n\t\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\t\tTransport: clientDefaultTransport,\n\t\t\t\tTimeout: options.RequestTimeout,\n\t\t\t}),\n\t\t)\n\t} else { // Retry enabled\n\t\t// Create exponential back-off\n\t\tbackOff := heimdall.NewExponentialBackoff(\n\t\t\toptions.BackOffInitialTimeout,\n\t\t\toptions.BackOffMaxTimeout,\n\t\t\toptions.BackOffExponentFactor,\n\t\t\toptions.BackOffMaximumJitterInterval,\n\t\t)\n\n\t\tc.httpClient = httpclient.NewClient(\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\n\t\t\thttpclient.WithRetrier(heimdall.NewRetrier(backOff)),\n\t\t\thttpclient.WithRetryCount(options.RequestRetryCount),\n\t\t\thttpclient.WithHTTPClient(&http.Client{\n\t\t\t\tTransport: clientDefaultTransport,\n\t\t\t\tTimeout: options.RequestTimeout,\n\t\t\t}),\n\t\t)\n\t}\n\n\t// Create a last Request and parameters struct\n\tc.LastRequest = new(LastRequest)\n\tc.LastRequest.Error = new(Error)\n\tc.Parameters = &Parameters{\n\t\tUserAgent: options.UserAgent,\n\t}\n\treturn\n}", "func main() {\n\tfmt.Println(\"APPLICATION BEGIN\")\n\twebserver := new(service.Webserver)\n\tregisterConfig()\n\tregisterErrors()\n\tregisterAllApis()\n\tregisterInitFunc()\n\toverrideConfByEnvVariables()\n\twebserver.Start()\n}" ]
[ "0.7755232", "0.7747002", "0.77198035", "0.7177006", "0.7107686", "0.6922277", "0.68362284", "0.6815787", "0.6778457", "0.6763634", "0.67444175", "0.6730545", "0.66647184", "0.6656747", "0.6648715", "0.6639354", "0.66306657", "0.662526", "0.66167915", "0.6612979", "0.65890753", "0.6587331", "0.6561607", "0.6558874", "0.654738", "0.65444356", "0.6536379", "0.6531104", "0.6525623", "0.65121704", "0.6488428", "0.64853805", "0.6463982", "0.646387", "0.64613086", "0.6451834", "0.64045703", "0.6401433", "0.63874996", "0.6386908", "0.6383462", "0.6373399", "0.63706315", "0.6369703", "0.6347071", "0.6346996", "0.6346654", "0.6344823", "0.6334529", "0.6324951", "0.63237506", "0.6322736", "0.63142467", "0.62943", "0.6291193", "0.6290847", "0.6289696", "0.6289574", "0.62874514", "0.62845254", "0.6283576", "0.62776023", "0.6276092", "0.62707853", "0.6268528", "0.62672037", "0.6261443", "0.62613755", "0.6258405", "0.62516385", "0.62470376", "0.6236492", "0.62244046", "0.621853", "0.62180525", "0.6216591", "0.6215397", "0.62077326", "0.61975414", "0.6194334", "0.6186644", "0.61865497", "0.6182387", "0.6181292", "0.6179796", "0.61792946", "0.61788785", "0.61756575", "0.61687595", "0.61670214", "0.6163264", "0.61573493", "0.61564773", "0.6155276", "0.61455554", "0.6136322", "0.61328024", "0.61322117", "0.61210126", "0.61206293" ]
0.6335857
48
Easyer way to check error, exit program if error
func check(err error) { if (err != nil) { fmt.Println(err) os.Exit(1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func checkError(e error) {\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\tos.Exit(1)\n\t}\n}", "func checkError(msg string, err error, exit bool) {\n\tif err != nil {\n\t\tlog.Println(msg, err)\n\t\tif exit {\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n}", "func checkError(msg string, err error, exit bool) {\n\tif err != nil {\n\t\tlog.Println(msg, err)\n\t\tif exit {\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n}", "func check(e error) {\n\tif e != nil {\n\t\tfmt.Println(\"Error:\", e)\n\t\tos.Exit(1)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func checkError(err error) {\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Fatal error: %s\", err.Error())\n os.Exit(1)\n }\n}", "func checkError(reason string, err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"%s: %s\\n\", reason, err)\n\t\tos.Exit(1)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Fatal error \", err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\t// change it into other func\n\t\t//os.Exit(1)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Operation failed: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func exitWithError(err error) {\n\tfmt.Println(err)\n\tos.Exit(1)\n}", "func exitIfError(e error) {\n\tif e != nil {\n\t\tfmt.Printf(\"ERROR occured : %s\\n\", e)\n\t\tos.Exit(errorExitCode)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Fatal error \", err.Error())\n\t\tos.Exit(1)\n\t}\n}", "func CheckError(err error) {\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Error: \", err)\r\n\t\tos.Exit(0)\r\n\t}\r\n}", "func checkErr(err error) {\n if err != nil {\n fmt.Fprintf(os.Stderr, \"%s%s Sphynx%s: %v\\n\", CLR_RED, ERR_ICON, CLR_END, err)\n os.Exit(1)\n }\n}", "func exitIfError(e error) {\n\tif e != nil {\n\t\tfmt.Printf(\"ERROR occurred : %s\\n\", e)\n\t\tswitch e.(type) {\n\t\tcase *terrahelp.CryptoWrapError:\n\t\t\tos.Exit(cryptoWrapErrorExitCode)\n\t\tdefault:\n\t\t\tos.Exit(otherErrorExitCode)\n\t\t}\n\t}\n}", "func errorExit(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Error: \", err)\n\t\tos.Exit(0)\n\t}\n}", "func CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Error: \", err)\n\t\tos.Exit(0)\n\t}\n}", "func CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Error: \", err)\n\t\tos.Exit(0)\n\t}\n}", "func errFound(err error) {\n\tfmt.Println(\"ERROR: \", err)\n\tos.Exit(-1)\n}", "func Check(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Check(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func exitWithError(err error,exitCode int) {\n\n\tfmt.Println(err)\n\tos.Exit(exitCode)\n}", "func errorAndExit(err error) {\n\tgoui.Error(\"An unexpected error occurred:\", err.Error())\n\tos.Exit(1)\n}", "func checkResult(err error, caller string) {\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR at %s: %s\\n\", caller, err)\n\t\tos.Exit(-1)\n\t}\n}", "func check(e error, m string) {\n\tif e != nil {\n\t\tprintln(m)\n\t\tos.Exit(1)\n\t}\n}", "func errExit(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func CheckError(msg string, err error, exit bool) {\n\tif err != nil {\n\t\terrorLogger.Println(\"ERROR STR: \", msg)\n\t\terrorLogger.Println(\"ERROR: \", err)\n\t\tif exit {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}", "func checkForErrorsAndExit(err error) {\n\texitCode := defaultSuccessExitCode\n\tisDebugMode := os.Getenv(debugEnvironmentVarName) != \"\"\n\n\tif err != nil {\n\t\tif isDebugMode {\n\t\t\tlogging.GetLogger(\"\").WithError(err).Error(errors.PrintErrorWithStackTrace(err))\n\t\t} else {\n\t\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\\n\", errors.Unwrap(err))\n\t\t}\n\n\t\terrorWithExitCode, isErrorWithExitCode := err.(errors.ErrorWithExitCode)\n\t\tif isErrorWithExitCode {\n\t\t\texitCode = errorWithExitCode.ExitCode\n\t\t} else {\n\t\t\texitCode = defaultErrorExitCode\n\t\t}\n\t}\n\n\tos.Exit(exitCode)\n}", "func exitOnErr111(err error) {\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(111)\n\t}\n}", "func processError(message string, err error) {\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %v\", message, err)\n\t\tos.Exit(1)\n\t}\n}", "func exitOnErr(err error) {\n\tfmt.Printf(\"%s\\n\", err.Error())\n\tos.Exit(1)\n}", "func check(err error, fatal bool) {\n\tif err != nil {\n\t\tfmt.Printf(\"error: %s\\n\", err)\n\t\tif fatal {\n\t\t\tpanic(\"terminating due to error\")\n\t\t}\n\t}\n}", "func errorExit(exit_code int, err error) {\n\tfmt.Printf(\"Error: %v\\n\", err)\n\tos.Exit(exit_code)\n}", "func CheckError(action string, err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Error\", action, \"==>\", err)\n\t\tos.Exit(1)\n\t}\n}", "func ExitOnErr(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func fail(err error) {\n\tfmt.Println(\"match:\", err)\n\tos.Exit(1)\n}", "func handleErr(e error, msg string){\n\tif e != nil {\n\t\tfmt.Println(msg)\n\t\tos.Exit(0)\n\t}\n}", "func errExit(err error, l logrus.FieldLogger) {\n\tif l != nil {\n\t\tl.Fatal(err)\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n\n\tos.Exit(1)\n}", "func ExitErr(reason error) {\n\tfmt.Printf(\"ERROR: %v\\n\", reason)\n\tos.Exit(1)\n}", "func ExitIf(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Fatal error: \", err.Error())\n\t\tdebug.PrintStack()\n\t\tos.Exit(1)\n\t}\n}", "func ExitError(msg string, code uint64) {\n PrintString(msg);\n PrintChar(10); //Print new line ('\\n' = 10)\n Exit(code);\n}", "func dieIfError(err error) {\n\tif err != nil {\n\t\tglog.Fatalln(\"Fatal: \", err)\n\t}\n}", "func (res *result) checkExit(success bool) {\n\tres.t.Helper()\n\tif (res.exitcode == 0) != success {\n\t\tres.t.Errorf(\"%s: exited with code %d, want success: %t (%s)\",\n\t\t\tres.command, res.exitcode, success, res)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error: %s\", err.Error())\n\t}\n}", "func failureExit(err error) {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %v\\n\", err)\n\t}\n\tos.Exit(1)\n}", "func checkError(err error) error {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error \", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func checkError(err error) error {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error \", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func checkError(err error) error {\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error \", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func checkError(err error, msg string) {\n if err != nil {\n fmt.Printf(\"%s\\n\", msg)\n panic(err)\n }\n}", "func checkPrintErr(err CustError, w http.ResponseWriter) bool {\n\tif err.status != 0 {\n\t\thttp.Error(w, http.StatusText(err.status)+\" | Program error: \"+err.msg, err.status)\n\t\treturn true\n\t}\n\n\treturn false\n}", "func customErr(text string, e error) {\n\tif e != nil {\n\t\tfmt.Println(text, e)\n\t\tos.Exit(1)\n\t}\n}", "func checkError(err error) {\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n}", "func checkError(err error) {\n\tif err != nil {\t\t\n\t\tlog.Fatalf(\"%s\\n\", err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Fatalln(\"Unexpected error:\", r)\n\t\t}\n\t}()\n\tif errMain := run(); errMain != nil {\n\t\tlog.Fatalln(errMain)\n\t}\n}", "func OsExitIfErr(err error, format string, a ...interface{}) {\n\tif err != nil {\n\t\tLog(fmt.Sprintf(format, a...))\n\t\tLog(fmt.Sprintf(\"--- error: %v\\n\", err))\n\t\tos.Exit(1)\n\t}\n}", "func check(err error, message string) {\n\tif err != nil {\n\t\tpanic(err) // panic used if program has reach an unrecoverable state\n\t}\n\tfmt.Printf(\"%s\\n\", message)\n}", "func checkErr(err error) { // to keep code clean\n\tif err != nil {\n\t\tfmt.Println(err.Error()) // output the error\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func Catch(err error, _exit ...bool) {\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tif len(_exit) > 0 {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}", "func check_err(e error) {\n if e != nil {\n panic(e)\n }\n}", "func checkError(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func checkError(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func ExitError(msg string, err error) {\n\tfmt.Fprintf(os.Stderr, \"%s:\", os.Args[0])\n\n\tif msg != \"\" {\n\t\tfmt.Fprintf(os.Stderr, \" %s\", msg)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \":\")\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \" %s\", err)\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tos.Exit(1)\n}", "func main() {\n\tif err := mainErr(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func checkErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}", "func check(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tbuildMU.Lock()\n\tdefer buildMU.Unlock()\n\tbuild.Status = pb.Status_INFRA_FAILURE\n\tbuild.SummaryMarkdown = fmt.Sprintf(\"run_annotations failure: `%s`\", err)\n\tclient.WriteBuild(build)\n\tfmt.Fprintln(os.Stderr, err)\n\tos.Exit(1)\n}", "func CheckErr(err error) {\n\tswitch e := err.(type) {\n\tcase nil:\n\t\treturn // Don't fail if there's no error\n\tcase *ssh.ExitError: // In case of SSH errors, use the exit status of the remote command\n\t\tlogs.Logger.ExitCode = e.ExitStatus()\n\t}\n\n\tlog.Fatal(err)\n}", "func check(e error) {\r\n if e != nil {\r\n panic(e)\r\n }\r\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func FatalCheck(err error) {\n\tif err != nil {\n\t\tStackb(1, err)\n\t\tos.Exit(1)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func errHandler(err error) {\n\tlog.Fatal(err)\n\tos.Exit(1)\n}", "func (o Object) ErrNoExit(f string, a ...interface{}) {\n\to.PrintMsg(\"ERROR\", 2, f, a...)\n}", "func check(err error) {\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (o *Options) exitOnError(timedOut bool, err error) {\n\n\tif !o.Json {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\terrjson := Error{\n\t\t\tType: \"Unknown\",\n\t\t\tInfo: err.Error(),\n\t\t}\n\t\tif timedOut {\n\t\t\terrjson.Type = \"Timeout\"\n\t\t}\n\t\tjson.NewEncoder(os.Stderr).Encode(errjson)\n\t}\n\tos.Exit(-1)\n}", "func check(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tminiLog.fatal(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func check(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tif err := do(); err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func checkError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}" ]
[ "0.76099515", "0.7536181", "0.7536181", "0.75227296", "0.751925", "0.7471282", "0.7390577", "0.7370284", "0.73677313", "0.73093563", "0.7224056", "0.71785843", "0.715242", "0.71427566", "0.7041517", "0.69908535", "0.69642687", "0.69378734", "0.6865895", "0.6865895", "0.6865895", "0.6774716", "0.6725802", "0.6725802", "0.6664017", "0.6657441", "0.66546017", "0.66010606", "0.6544546", "0.64940983", "0.64348024", "0.6392183", "0.6385031", "0.63795984", "0.6372276", "0.6364036", "0.6274644", "0.62593997", "0.62562954", "0.6209372", "0.6201114", "0.61781013", "0.6157045", "0.6146764", "0.6117571", "0.61045074", "0.60808736", "0.6062346", "0.604829", "0.6043597", "0.6043597", "0.6043597", "0.6034358", "0.60093063", "0.60028636", "0.5973141", "0.5957709", "0.5929442", "0.5929442", "0.5929442", "0.5929442", "0.5929442", "0.5915034", "0.59132224", "0.59029716", "0.5870596", "0.58627677", "0.5854487", "0.5842457", "0.58415264", "0.58415264", "0.5840474", "0.5840474", "0.5840474", "0.5840474", "0.5840474", "0.5840474", "0.5834661", "0.5827492", "0.58257276", "0.5819546", "0.5817697", "0.5811043", "0.5810831", "0.581082", "0.58054066", "0.5803559", "0.5792175", "0.5785751", "0.5785751", "0.5774625", "0.57663584", "0.57663584", "0.57648534", "0.5763521", "0.5763521", "0.5755022", "0.5754182", "0.5754182", "0.5750137" ]
0.78341246
0
read input from Stdin,
func validateLang() { //print all lang options fmt.Println(intro) for _, lang := range languages { fmt.Println(lang) } //local lines that will hold all lines in the choosen lang file lines = make([]string,0) //l will be our predefined languages l := languages //infinit loop for reading user input language, loop ends if correct lang was choosen for { picked := strings.TrimSpace(userInput()) //read the input from Stdin, trim spaces //looping through our predefined languages for _,lang := range(l) { fmt.Println(lang) if (picked == lang) { //fmt.Println("Found language!", lang, picked) custlang = lang //variable to hold current lang for client lang = lang + ".txt" //append .txt because we are reading from files file, err := os.Open(lang) //open the given languge file check(err) //check if correct scanner := bufio.NewScanner(file) //scanning through the file for scanner.Scan() { lines = append(lines, scanner.Text()) //appending each line in the given langue file to lines } file.Close() //close the file check(scanner.Err()) //check for errors so nothing is left in the file to read break } } //check so we actually got something in len, if we have, we have successfully changed language if (len(lines) != 0) { break } else { fmt.Println(end) //print error msg } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StdinReader(input *ringbuffer.RingBuffer) {\n\tin := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tby, err := in.ReadByte()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tinput.Write([]byte{by})\n\t}\n}", "func (c *Cmd) Stdin(in io.Reader) *Cmd {\n\tc.stdin = in\n\treturn c\n}", "func readInput(in io.Reader) (string, error) {\n\tline, _, err := bufio.NewReader(in).ReadLine()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error while reading input\")\n\t}\n\treturn strings.TrimSpace(string(line)), nil\n}", "func readInput(conn net.Conn, qst string) (string, error) {\n\tconn.Write([]byte(qst))\n\ts, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\tlog.Printf(\"readinput: could not read input from stdin: %v from client %v\", err, conn.RemoteAddr().String())\n\t\treturn \"\", err\n\t}\n\ts = strings.Trim(s, \"\\r\\n\")\n\treturn s, nil\n}", "func (p *Process) Stdin() io.Reader {\n\treturn p.stdin\n}", "func readInput(path string) []byte {\n\tvar bytes []byte\n\tvar err error\n\n\tif path != \"\" {\n\t\tbytes, err = ioutil.ReadFile(path)\n\t} else {\n\t\tbytes, err = ioutil.ReadAll(os.Stdin)\n\t}\n\n\tapp.FatalIfError(err, \"unable to read input\")\n\treturn bytes\n}", "func readStdin(out chan<- []byte) {\n\t//* copies some data from Stdin into data. Note that File.Read blocks until it receives data\n\tfor {\n\t\tdata := make([]byte, 1024)\n\t\tl, _ := os.Stdin.Read(data)\n\t\tif l > 0 {\n\t\t\t//* sends the buffered data over the channel\n\t\t\tout <- data\n\t\t}\n\t}\n}", "func main() {\n\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Enter your name:\")\n\n\tname, _ := reader.ReadString('\\n')\n\tfmt.Print(\"Your name is \", name)\n\n}", "func readInput() (src string, err error) {\n\tin := os.Args\n\tsrc = in[1]\n\tif src == \"\" {\n\t\treturn src, errors.New(\"missing string to match\")\n\t}\n\treturn src, nil\n}", "func readInput(output string) (num int) {\n\tfor {\n\t\t// Create a new reader\n\t\tbuf := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(output + \"\\n\")\n\t\tsentence, err := buf.ReadString('\\n')\n\t\t// Check if error\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\t// remove newLine Char\n\t\t\tsentence = strings.TrimSuffix(sentence, \"\\n\")\n\t\t\t// Check if input is numeric\n\t\t\tif result, converted := isNumeric(sentence); result {\n\t\t\t\treturn converted\n\t\t\t}\n\t\t\tfmt.Println(string(errorInt))\n\t\t}\n\t}\n}", "func (p *Init) Stdin() io.Closer {\n\treturn p.stdin\n}", "func readInput(kind, defaultValue string) (string, error) {\n\tr := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"%s (%s): \", color.YellowString(\"Enter a value\"), kind)\n\ttext, err := r.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif text == \"\\n\" {\n\t\ttext = defaultValue\n\t\tfmt.Printf(\"%s%s (%s): %s\\n\", moveLineUp, color.YellowString(\"Enter a value\"), kind, text)\n\t}\n\tfmt.Println()\n\treturn text, nil\n}", "func readInput(inCh chan byte) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tinput := scanner.Bytes()\n\t\tfor _, c := range input {\n\t\t\tinCh <- c\n\t\t}\n\t}\n}", "func input() io.Reader {\n\tif isatty.IsTerminal(os.Stdin.Fd()) {\n\t\treturn strings.NewReader(\"{}\")\n\t}\n\n\treturn os.Stdin\n}", "func readstdin(reader *bufio.Reader) string {\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tlog.Fatalf(\"Error when reading input: %v\", err)\n\t}\n\treturn strings.TrimSpace(text)\n}", "func readData(input *string) ([]byte, error) {\n\tif *input == \"-\" {\n\t\tlog.Println(\"reading bytes from stdin\")\n\t\treturn ioutil.ReadAll(os.Stdin)\n\t} else {\n\t\tlog.Println(\"reading bytes from '\" + *input + \"'\")\n\t\treturn ioutil.ReadFile(*input)\n\t}\n}", "func (c *Config) Stdin() io.ReadCloser {\n\treturn c.stdin\n}", "func input() (io.Reader, error) {\n\targs := flag.Args()\n\tswitch len(args) {\n\tcase 0:\n\t\tfi, _ := os.Stdin.Stat()\n\t\tif (fi.Mode() & os.ModeCharDevice) != 0 {\n\t\t\tbreak\n\t\t}\n\t\treturn os.Stdin, nil\n\tcase 1:\n\t\treturn os.Open(args[0])\n\t}\n\treturn nil, errors.New(\"usage: etod [opts] <file> or cmd | etod\")\n}", "func (reader *testReader) Read(b []byte) (int, error) {\n\tfmt.Print(\"[IN] > \")\n\treturn os.Stdin.Read(b)\n}", "func ReadIn() string {\n\ttext, err := tryReadStdIn()\n\tif err == nil {\n\t\treturn strings.TrimSpace(text)\n\t}\n\tfmt.Printf(\"Error while reading stdin: %s\", err)\n\treturn \"\"\n}", "func getInput(trim bool) string {\n fi, err := os.Stdin.Stat()\n if err != nil {\n panic(err)\n }\n\n if fi.Mode() & os.ModeNamedPipe == 0 {\n fmt.Println(\"Nothing to draw\")\n os.Exit(0)\n }\n\n reader := bufio.NewReader(os.Stdin)\n var input []rune\n for {\n\t\tchunk, _, err := reader.ReadRune()\n\t\tif err != nil && err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tinput = append(input, chunk)\n\t}\n\n if trim {\n return strings.TrimSpace(string(input))\n }\n\n return string(input)\n}", "func readStdin() (count int, err error) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tvar p Policy\n\t\tline := []byte(strings.Trim(scanner.Text(), \"\\r\\n\"))\n\t\tfields := strings.Fields(string(line))\n\t\tminmax := strings.Split(fields[0], \"-\")\n\t\tp.min, err = strconv.Atoi(minmax[0])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tp.min -= 1\n\t\tp.max, err = strconv.Atoi(minmax[1])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tp.max -= 1\n\t\tp.char = fields[1][0]\n\t\tpassword := fields[2]\n\t\tif p.Complies(password) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn\n}", "func readInput() string {\r\n cmdString, err := reader.ReadString('\\n')\r\n check(err)\r\n\r\n return cmdString\r\n}", "func read(msg string) string {\n\tfmt.Print(msg)\n\tvar ret, _ = bufio.NewReader(os.Stdin).ReadString('\\n')\n\treturn ret\n}", "func readInput() string {\n\n\tvar input string\n\n\tf, _ := os.Open(\"input.txt\")\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\t\tif scanner.Text() != \"\" {\n\t\t\tinput = scanner.Text()\n\t\t}\n\t}\n\treturn input\n}", "func (client *Client) InputReader(c net.Conn) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Print(\"> \")\n\tfor scanner.Scan() {\n\t\targs := strings.Split(scanner.Text(), \" \")\n\t\tif args[0] == \"exit\" {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tresponse, err := client.processCommand(c, args[0], args[1:]...)\n\t\tparseResponse(response, err, defaultTag)\n\t\tif args[0] == \"subscribe\" {\n\t\t\tsubscribePattern(c, scanner)\n\t\t\tfmt.Printf(\"\\r%s\", defaultTag)\n\t\t}\n\t}\n\n\tif scanner.Err() != nil {\n\t\tfmt.Printf(\"%v\", scanner.Err())\n\t\tos.Exit(2)\n\t}\n}", "func readInputLoop(dt *discordterm.Client) {\n\trd := bufio.NewReader(os.Stdin)\n\n\tl, err := readline.NewEx(&readline.Config{\n\t\tPrompt: prompt,\n\t\tAutoComplete: completer,\n\t\tHistoryFile: filepath.Join(os.TempDir(), historyFile),\n\t\tHistorySearchFold: true,\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error creating readline:\", err)\n\t\treturn\n\t}\n\n\tvar standardReader bool\n\n\tfor {\n\t\tvar line string\n\t\tvar err error\n\n\t\tl.SetPrompt(createPrompt(dt))\n\n\t\tif !standardReader {\n\t\t\tline, err = l.Readline()\n\t\t\tif err != nil {\n\t\t\t\tstandardReader = true\n\t\t\t\tlog.Println(\"Error using readline package: switching to bufio reader: \", err)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Print(prompt)\n\t\t\tline, err = rd.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t// Read a line of input\n\n\t\t// Remove whitespace characters from line\n\t\tline = strings.TrimSpace(line)\n\n\t\terr = executeCommand(dt, line)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func initializeStdInInterface() {\n\t// To work with the standard input, we'll use the Go's bufio package that provides\n\t// and Scanner interface for reading newline delimited text.\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor {\n\t\t// Show the prompt each time we expect a text input\n\t\tfmt.Print(STDIN_PROMPT)\n\n\t\t// Scan for new text, this will hold until enter is pressed on the Std. In. or\n\t\t// if there is an error.\n\t\tscanner.Scan()\n\n\t\t// If there is an error while scanning, print it.\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the entire statement from the Scanner as a string.\n\t\tstmt := scanner.Text()\n\n\t\t// Process the statement to interact with the data storage, and get the output to be printed.\n\t\toutput, err := processStatement(stmt)\n\t\tif err == ERR_STMT_EMPTY {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\t// Print the output to the Std. out\n\t\tif output != \"\" {\n\t\t\tfmt.Println(output)\n\t\t}\n\t}\n}", "func main() {\r\n\tscanner := bufio.NewScanner(os.Stdin)\r\n\tfor scanner.Scan() {\r\n\t\tfmt.Println(scanner.Text())\r\n\t}\r\n\tif err := scanner.Err(); err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n}", "func readInput() (string, error) {\n\tbuffer := make([]byte, 100)\n\tcnt, err := os.Stdin.Read(buffer)\n\n\t// If error, return error and empty string\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// If the key press is esc\n\tif cnt == 1 && buffer[0] == 0x1b {\n\t\treturn \"ESC\", nil\n\t} else if cnt >= 3 {\n\t\tif buffer[0] == 0x1b && buffer[1] == '[' {\n\t\t\tswitch buffer[2] {\n\t\t\tcase 'A':\n\t\t\t\treturn \"UP\", nil\n\t\t\tcase 'B':\n\t\t\t\treturn \"DOWN\", nil\n\t\t\tcase 'C':\n\t\t\t\treturn \"RIGHT\", nil\n\t\t\tcase 'D':\n\t\t\t\treturn \"LEFT\", nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil // Nothing read in\n}", "func readData() {\n\tin = bufio.NewReader(os.Stdin)\n\t// reading n\n\tn, _, _, _, _ = readFive()\n\tp = readLineNumbs(n)\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 getInput(input chan string) {\n for {\n reader := bufio.NewReader(os.Stdin)\n d,_ := reader.ReadString('\\n')\n input <- d\n }\n}", "func readInput(message string) string {\r\n\tscanner := bufio.NewScanner(os.Stdin)\r\n\tfmt.Print(\"Value of \", message, \" not found. Please enter the value\\n\")\r\n\tscanner.Scan()\r\n\ttext := scanner.Text()\r\n\tfmt.Print(\"\\n Value of text is: \", text)\r\n\treturn text\r\n\r\n}", "func stdin(c chan<- string, mf string) {\n\tdefer close(c)\n\tscanner := bufio.NewScanner(os.Stdin)\n\tlog.Printf(\"Ready.\")\n\tfor scanner.Scan() {\n\t\tc <- mf + scanner.Text()\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatalf(\"Read error: %v\", err)\n\t}\n}", "func setInput(in *os.File) error {\n\treturn setStream(in, &C.rl_instream, \"r\", syscall.Stdin)\n}", "func (c *Cmd) StdinPipe() (io.WriteCloser, error)", "func input(cmd_chan chan string) {\n\tin := bufio.NewReader(os.Stdin)\n\n\tlog(\"\")\n\tfor {\n\t\tif cmd, err := in.ReadString('\\n'); err == nil && cmd != \"\\n\" {\n\t\t\tcmd_chan <- strings.Trim(cmd, \"\\n\")\n\t\t}\n\t\tlogPrompt()\n\t}\n}", "func Input(s bool, a ...interface{}) string {\n\tif s {\n\t\tfmt.Printf(\"\\a\")\n\t}\n\tfmt.Printf(\"%v\", a...)\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func GetFromStdin(params *GetFromStdinParams) *string {\n\tparamutil.SetDefaults(params, defaultParams)\n\n\tvalidationRegexp, _ := regexp.Compile(params.ValidationRegexPattern)\n\tinput := \"\"\n\n\tfor {\n\t\tfmt.Print(params.Question)\n\n\t\tif len(params.DefaultValue) > 0 {\n\t\t\tfmt.Print(\"\\n\")\n\t\t\tlog.WriteColored(\"Press ENTER to use: \"+params.DefaultValue, ct.Green)\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\n\t\tfor {\n\t\t\tfmt.Print(\"> \")\n\n\t\t\treader := bufio.NewReader(os.Stdin)\n\t\t\tnextLine := \"\"\n\n\t\t\tif params.IsPassword {\n\t\t\t\tinStreamFD := command.NewInStream(os.Stdin).FD()\n\t\t\t\toldState, err := term.SaveState(inStreamFD)\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\tterm.DisableEcho(inStreamFD, oldState)\n\t\t\t\tnextLine, _ = reader.ReadString('\\n')\n\t\t\t\tterm.RestoreTerminal(inStreamFD, oldState)\n\t\t\t} else {\n\t\t\t\tnextLine, _ = reader.ReadString('\\n')\n\t\t\t}\n\n\t\t\tnextLine = strings.Trim(nextLine, \"\\r\\n \")\n\n\t\t\tif strings.Compare(params.InputTerminationString, \"\\n\") == 0 {\n\t\t\t\t// Assign the input value to input var\n\t\t\t\tinput = nextLine\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tinput += nextLine + \"\\n\"\n\n\t\t\tif strings.HasSuffix(input, params.InputTerminationString+\"\\n\") {\n\t\t\t\tinput = strings.TrimSuffix(input, params.InputTerminationString+\"\\n\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif len(input) == 0 && len(params.DefaultValue) > 0 {\n\t\t\tinput = params.DefaultValue\n\t\t}\n\t\tif validationRegexp.MatchString(input) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Print(\"Input must match \" + params.ValidationRegexPattern + \"\\n\")\n\t\t\tinput = \"\"\n\t\t}\n\t}\n\tfmt.Println(\"\")\n\n\treturn &input\n}", "func ReadInput(printText string, defaultVal Default, validate func(value string) bool, invalidText string, retryOnInvalid bool) (string, error) {\n\tretry := true\n\tvalue := \"\"\n\treader := bufio.NewReader(os.Stdin)\n\ttext := fmt.Sprintf(\"%s: \", printText)\n\tif defaultVal.IsDefault {\n\t\ttext = fmt.Sprintf(\"%s: %s: \", printText, defaultVal.Value)\n\t}\n\n\tfor retry {\n\t\tfmt.Print(text)\n\t\tinputValue, err := reader.ReadString('\\n')\n\t\tvalue = strings.TrimSpace(inputValue)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif value == \"\" && defaultVal.IsDefault {\n\t\t\treturn defaultVal.Value, nil\n\t\t}\n\n\t\tisValid := validate(value)\n\n\t\tif !isValid {\n\t\t\tfmt.Println(invalidText)\n\t\t\tif !retryOnInvalid {\n\t\t\t\treturn value, errors.New(\"input validation failed\")\n\t\t\t}\n\t\t}\n\n\t\tretry = retryOnInvalid && !isValid\n\t}\n\n\treturn value, nil\n}", "func STDINReader() []rune {\n\treader := bufio.NewReader(os.Stdin)\n\n\tvar output []rune\n\n\tfor {\n\t\tinput, _, err := reader.ReadRune()\n\t\tif err != nil && err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\toutput = append(output, input)\n\t}\n\n\treturn output\n}", "func getInput() string {\n\tvar str string\n\tscanner := bufio.NewScanner(os.Stdin)\n\tif scanner.Scan() {\n\t\tstr = scanner.Text()\n\t}\n\n\treturn str\n}", "func ReadInput(args ...string) []string {\n\tvar scanner *bufio.Scanner\n\tif len(args) == 0 {\n\t\tfmt.Printf(\"Input:\\n\")\n\t\tscanner = bufio.NewScanner(os.Stdin)\n\t} else {\n\t\tf, err := os.Open(args[0])\n\t\tCheck(err, \"Couldn't open file: \"+args[0])\n\t\tscanner = bufio.NewScanner(f)\n\t}\n\n\tvar res []string\n\tfor scanner.Scan() {\n\t\t// s := strings.Trim(scanner.Text(), \" \\n\\t\")\n\t\ts := scanner.Text()\n\t\tif len(s) > 0 {\n\t\t\tres = append(res, s)\n\t\t}\n\t}\n\tCheck(scanner.Err(), \"Error reading input\")\n\treturn res\n}", "func ReadInput(path string) ([]byte, error) {\n\tvar inputFile *os.File\n\tif path == \"\" {\n\t\tstdinFileInfo, _ := os.Stdin.Stat()\n\t\tif (stdinFileInfo.Mode() & os.ModeNamedPipe) != 0 {\n\t\t\tinputFile = os.Stdin\n\t\t} else {\n\t\t\treturn nil, NewErrExpectedStdin()\n\t\t}\n\t} else {\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer func() { _ = f.Close() }()\n\t\tinputFile = f\n\t}\n\tfileContent, err := ioutil.ReadAll(inputFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// golang adds a new line characters at the end of every line, not what we want here\n\t// note that we need to make sure the workaround is cross platform\n\tfileContent = bytes.TrimRight(fileContent, \"\\r\\n\")\n\treturn fileContent, nil\n}", "func readInput(prompt string) []int {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(prompt)\n\tinputString, _ := reader.ReadString('\\n')\n\n\tnumbers := make([]int, len(inputString)-1)\n\tfor i := 0; i < len(inputString)-1; i++ {\n\t\tnumbers[i] = int(inputString[i]) - 48\n\t}\n\treturn numbers\n}", "func (p *program) doReadInput(i *instruction) {\n var input int64\n channelReadOk := false\n\n if p.inChannel != nil {\n select {\n case <-time.After(10 * time.Second):\n fmt.Println(\"waiting for input timed-out, trying to read from dataStack\")\n case input = <-p.inChannel:\n channelReadOk = true\n }\n }\n\n if !channelReadOk {\n if len(p.dataStack) > 0 {\n input = p.dataStack[len(p.dataStack)-1]\n p.dataStack = p.dataStack[:len(p.dataStack)-1]\n } else {\n reader := bufio.NewReader(os.Stdin)\n fmt.Print(\"Enter value: \")\n value, err := reader.ReadString('\\n')\n\n if err != nil {\n fmt.Println(err)\n }\n\n inputInt, err := strconv.Atoi(strings.TrimSuffix(value, \"\\n\"))\n\n if err != nil {\n fmt.Println(err)\n }\n\n input = int64(inputInt)\n }\n }\n\n p.memory[i.params[0].value] = input\n p.position += i.length\n}", "func getInput(request string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\n\" + request)\n\tusrInput, _ := reader.ReadString('\\n')\n\treturn strings.TrimSpace(usrInput)\n}", "func readInput() (string, error) {\n buffer := make([]byte, 100)\n\n cnt, err := os.Stdin.Read(buffer)\n if err != nil {\n return \"\", err\n }\n\n if cnt == 1 && buffer[0] == 0x1b {\n return \"ESC\", nil\n }else if cnt >= 3 {\n if buffer[0] == 0x1b && buffer[1] == '[' {\n switch buffer[2] {\n case 'A':\n return \"UP\", nil\n case 'B':\n return \"DOWN\", nil\n case 'C':\n return \"RIGHT\", nil\n case 'D':\n return \"LEFT\", nil\n }\n }\n }\n\n return \"\", nil\n}", "func readStdin() (grid []lineRep, err error) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tline := strings.Trim(scanner.Text(), \"\\r\\n\")\n\t\tif len(line) != lineLen {\n\t\t\terr = ErrBadLine\n\t\t\treturn\n\t\t}\n\t\tvar lrep lineRep\n\t\tfor i := 0; i < lineLen; i++ {\n\t\t\tlrep[i] = (line[i] == '#')\n\t\t}\n\t\tgrid = append(grid, lrep)\n\t}\n\treturn\n}", "func readCmd() {\n\tbzIn, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot read stdin: %v\", err)\n\t\treturn\n\t}\n\tvestingData, err := unmarshalVestingData(bzIn)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot decode vesting data: %v\", err)\n\t\treturn\n\t}\n\tevents, err := vestingDataToEvents(vestingData)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot convert vesting data: %v\", err)\n\t}\n\tbzOut, err := marshalEvents(events)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot encode events: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(string(bzOut))\n}", "func testBufioOs() {\n\n\t// a reader object can collect information from a variety of inputs\n\treader := bufio.NewReader(os.Stdin) // --> this means that this reader object is looking for information from standard input\n\tfmt.Print(\"Enter text: \")\n\tstr, _ := reader.ReadString('\\n') // --> the character defines when the ReadString operation needs to return\n\t// --> in this case, it will return whatever it reads until the new line character\n\tfmt.Println(str)\n\n}", "func getInput() (string, error) {\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(text), nil\n}", "func (l *Linenoise) readBasic() (string, error) {\n\tif l.scanner == nil {\n\t\tl.scanner = bufio.NewScanner(os.Stdin)\n\t}\n\t// scan a line\n\tif !l.scanner.Scan() {\n\t\t// EOF - return quit\n\t\treturn \"\", ErrQuit\n\t}\n\t// check for unexpected errors\n\terr := l.scanner.Err()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// get the line string\n\treturn l.scanner.Text(), nil\n}", "func main() {\n\tc := AnagramsReader(os.Stdin)\n\tfmt.Println(c)\n}", "func detectInput() (io.Reader, error) {\n\tstats, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"file.Stat() in detectInput\")\n\t}\n\n\tif stats.Mode()&os.ModeNamedPipe != 0 {\n\t\treturn os.Stdin, nil\n\t}\n\tif len(flag.Args()) < 1 {\n\t\treturn nil, errors.New(\"No inputs found\")\n\t}\n\tif len(flag.Args()) > 1 {\n\t\treturn nil, errors.Errorf(\"Multiple input files is not supported. Your choise is '%v'\", flag.Args()[1:])\n\t}\n\tf, err := os.Open(flag.Args()[0])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Coudn't open file\")\n\t}\n\treturn f, nil\n}", "func get_input(question string) string {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Printf(question)\n\t\tresponse, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Err: %s\\n\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tresponse = cleanInput(response)\n\t\tif len(response) > 0 {\n\t\t\treturn response\n\t\t}\n\t}\n}", "func ReadInput(fname string) string {\n\tcontents, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstrContents := strings.TrimRight(string(contents), \"\\r\\n\")\n\treturn strContents\n}", "func ReadStdin() <-chan string {\n\tc := make(chan string)\n\tif seenStdin {\n\t\tlog.Fatalf(\"Repeated - on command line; can't reread stdin.\")\n\t}\n\tseenStdin = true\n\tgo func() {\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tscanner.Split(bufio.ScanWords)\n\t\tfor scanner.Scan() {\n\t\t\ts := strings.TrimSpace(scanner.Text())\n\t\t\tif s != \"\" {\n\t\t\t\tc <- s\n\t\t\t}\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tlog.Fatalf(\"Error reading stdin: %s\", err)\n\t\t}\n\t\tclose(c)\n\t}()\n\treturn c\n}", "func readCommand(input chan<- string) {\n\tfor {\n\t\tvar cmd string\n\t\t_, err := fmt.Scanln(&cmd)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tinput <- cmd\n\t}\n}", "func TakeInput() string {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\ttext = removeWhiteSpace(text)\n\treturn text\n}", "func (p *Prompt) GetInput(msg string) (string, error) {\n\tfmt.Fprintln(p.out, msg)\n\tfmt.Fprint(p.out, \"-> \")\n\tp.out.Flush()\n\ttext, err := p.in.ReadString('\\n')\n\treturn strings.TrimSpace(text), err\n}", "func ReadDataFromTerminal(input, original string) (string, error) {\n\tvar prompt string\n\tif len(original) > 0 {\n\t\tprompt = fmt.Sprintf(\"Enter %s [%s]: \", input, original)\n\t} else {\n\t\tprompt = fmt.Sprintf(\"Enter %s: \", input)\n\t}\n\tfmt.Print(prompt)\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _, err := reader.ReadLine()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error on reading %s...\", prompt)\n\t\treturn \"\", err\n\t}\n\tif len(text) == 0 {\n\t\treturn original, nil\n\t}\n\treturn string(text), nil\n}", "func MustReadIn() string {\n\tfor i := 0; i < 3; i++ {\n\t\ttext, err := tryReadStdIn()\n\t\tif err == nil {\n\t\t\treturn strings.TrimSpace(text)\n\t\t}\n\t\t// TODO Theme\n\t\tfmt.Printf(\"Error while reading stdin:: %s. Failed %d/3\\n\", err, i)\n\t}\n\tfmt.Println(\"Could not read stdin. Aborting...\")\n\tos.Exit(1)\n\treturn \"\"\n}", "func ReadPipedInput() ([]byte, error) {\n\tinfo, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpipedInput := info.Mode()&os.ModeNamedPipe != 0\n\tif info.Size() == 0 && !pipedInput {\n\t\treturn []byte{}, nil\n\t}\n\treturn ioutil.ReadAll(os.Stdin)\n}", "func takeUserInput() string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func Reader(conn net.Conn){\r\n osReader := bufio.NewReader(os.Stdin) // make a READER\r\n for {\r\n msg,err:=osReader.ReadString('\\n')\r\n if err != nil {\r\n fmt.Println(\"Client DISCONNECTED\")\r\n return\r\n }else {\r\n pass <- msg // pass the user input to channel\r\n }\r\n }\r\n }", "func TtyIn() *os.File {\n\treturn os.Stdin\n}", "func (rl *Instance) readlineInput(r []rune) {\n\tswitch rl.modeViMode {\n\tcase vimKeys:\n\t\trl.vi(r[0])\n\t\trl.viHintMessage()\n\n\tcase vimDelete:\n\t\trl.vimDelete(r)\n\t\trl.viHintMessage()\n\n\tcase vimReplaceOnce:\n\t\trl.modeViMode = vimKeys\n\t\trl.delete()\n\t\trl.insert([]rune{r[0]})\n\t\trl.viHintMessage()\n\n\tcase vimReplaceMany:\n\t\tfor _, char := range r {\n\t\t\trl.delete()\n\t\t\trl.insert([]rune{char})\n\t\t}\n\t\trl.viHintMessage()\n\n\tdefault:\n\t\trl.insert(r)\n\t}\n}", "func GetInput(sorted bool) []string {\n\treader := getPipeReader()\n\tvar input []string\n\n\tfor {\n\t\tlineBytes, _, err := reader.ReadLine()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tlineString := string(lineBytes)\n\t\tinput = append(input, lineString)\n\t}\n\n\tif sorted {\n\t\tsort.Strings(input)\n\t}\n\treturn input\n}", "func InteractiveInput(prompt string) string {\n\tif prompt != \"\" {\n\t\tfmt.Printf(\"%s \", prompt)\n\t}\n\tinput, err := bufio.NewReader(os.Stdin).ReadString('\\n')\n\tCheck(err)\n\n\t// sanitize input\n\treturn SanitizeInput(input)\n}", "func (cmd Cmd) Read(stdin io.Reader) Cmd {\n\tcmd.Stdin = stdin\n\treturn cmd\n}", "func localClientInput(conn net.Conn) {\n\tfmt.Print(\"> \")\n\tscanner := bufio.NewScanner(os.Stdin)\n\twriter := bufio.NewWriter(conn)\n\tfor scanner.Scan() {\n\t\tfmt.Print(\"> \")\n\t\t_, err := writer.WriteString(scanner.Text() + \"\\n\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\twriter.Flush()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func InputWithError(prompt string) (string, error) {\n\tfmt.Print(prompt)\n\tin := bufio.NewReader(os.Stdin)\n\tline, err := in.ReadString('\\n')\n\tif err != nil {\n\t\treturn line, err\n\t}\n\t// else\n\tline = strings.TrimRight(line, \"\\r\\n\")\n\treturn line, nil\n}", "func getIntInput(prompt string) int {\n\tfmt.Print(prompt)\n\treader := bufio.NewReader(os.Stdin)\n\trawInput, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tintInput, convertErr := strconv.Atoi(strings.TrimSuffix(rawInput, \"\\n\"))\n\n\tfor convertErr != nil {\n\t\tfmt.Println(\"Invalid integer, please try again.\")\n\t\tfmt.Print(prompt)\n\t\trawInput, err = reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tintInput, convertErr = strconv.Atoi(strings.TrimSuffix(rawInput, \"\\n\"))\n\t}\n\n\treturn intInput\n}", "func Reader(conn net.Conn){\n osReader := bufio.NewReader(os.Stdin) // make a READER\n for {\n msg,err:=osReader.ReadString('\\n')\n if err != nil {\n fmt.Println(\"Client DISCONNECTED\")\n return\n }else {\n pass <- msg // pass the user input to channel\n\n }\n }\n }", "func readTxIn(r io.Reader, pver uint32, ti *TxIn) error {\n\terr := readOutPoint(r, &ti.PreviousOutPoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tti.SignatureScript, err = readScript(r, pver, MaxMessagePayload,\n\t\t\"transaction input signature script\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = serialization.ReadUint32(r, &ti.Sequence)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *stdinParser) Read() ([]byte, error) {\n\tif p.size == p.start {\n\t\tbuf, err := p.ConsoleParser.Read()\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tp.start = 0\n\t\tp.size = len(buf)\n\t\tp.buf = buf\n\t}\n\ti := p.start\nL:\n\tfor ; i < p.size; i++ {\n\t\tif remapped, ok := p.keyMap[prompt.GetKey(p.buf[i:])]; ok {\n\t\t\tp.start = p.size\n\t\t\treturn remapped, nil\n\t\t}\n\t\tswitch prompt.GetKey(p.buf[i : i+1]) {\n\t\tcase prompt.Enter, prompt.ControlJ, prompt.ControlM:\n\t\t\tbreak L\n\t\t}\n\t}\n\tif i == p.start {\n\t\tp.start++\n\t\treturn p.buf[i : i+1], nil\n\t}\n\tbuf := p.buf[p.start:i]\n\tp.start = i\n\treturn buf, nil\n}", "func Readline(prompt string, interfaces ...interface{}) (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(prompt, interfaces...)\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinput = strings.Trim(input, \"\\n\\r\")\n\treturn input, nil\n}", "func getInput(r *bufio.Reader, q string) string {\n\tfmt.Printf(\"%s:\\n\", q)\n\ttext, err := r.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"an error has occured: %s\", err.Error())\n\t\tos.Exit(2)\n\t}\n\treturn text\n}", "func GetInput() string {\n\treader := bufio.NewReader(os.Stdin)\n\tinput, _ := reader.ReadString('\\n')\n\t// convert CRLF to LF\n\tinput = strings.Replace(input, \"\\n\", \"\", -1)\n\tinput = strings.Replace(input, \"\\r\", \"\", -1)\n\treturn input\n}", "func (t Terminal) Read(prompt string) (string, error) {\n\tif prompt != \"\" {\n\t\tfmt.Fprintf(t.Output, \"%s \", prompt)\n\t}\n\n\treader := bufio.NewReader(t.Input)\n\n\ttext, readErr := reader.ReadString('\\n')\n\tif readErr != nil {\n\t\treturn \"\", readErr\n\t}\n\n\ttext = strings.TrimSpace(text)\n\n\treturn text, nil\n}", "func getConsoleInput(loadedGame *gameStaticData) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"> \")\n\ttextInput, _ := reader.ReadString('\\n')\n\tsplitWord, extractStatus := extractWords(textInput)\n\tif extractStatus {\n\t\ttruncatedWord := truncateWords(loadedGame, splitWord)\n\t\tfmt.Printf(\"DEBUG: truncated words: \\\"%s\\\", \\\"%s\\\"\\n\", truncatedWord[0], truncatedWord[1])\n\t\tidentifiedWordsObjectsExits := deduceThingsFromInput(loadedGame, truncatedWord)\n\t\tfmt.Println(\"DEBUG: found verb(s):\", identifiedWordsObjectsExits.verb)\n\t\tfmt.Println(\"DEBUG: found noun(s):\", identifiedWordsObjectsExits.noun)\n\t\tfmt.Println(\"DEBUG: found noun for object(s):\", identifiedWordsObjectsExits.object)\n\t\tfmt.Println(\"DEBUG: found directions for noun(s):\", identifiedWordsObjectsExits.direction)\n\t}\n}", "func readMessage() string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func ReadStdin() []byte {\n\tfileBytes, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tFatal(FILE_IO_ERROR, i18n.GetMessagePrinter().Sprintf(\"reading stdin failed: %v\", err))\n\t}\n\treturn fileBytes\n}", "func stdinToString(maildata []byte) (*strings.Reader, error) {\n\tr := strings.NewReader(string(maildata))\n\treturn r, nil\n}", "func Input(query string, predef string) string {\n\tif *DryRunFlag {\n\t\treturn DryRunPop()\n\t}\n\tinputUI := &input.UI{\n\t\tWriter: os.Stdout,\n\t\tReader: os.Stdin,\n\t}\n\tinput, err := inputUI.Ask(query, &input.Options{\n\t\tDefault: predef,\n\t\tRequired: true,\n\t\tLoop: true,\n\t})\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn input\n}", "func ReadInputString(rd *bufio.Reader) string {\n\tline, err := rd.ReadString('\\n')\n\tMust(err)\n\treturn line\n}", "func userInput() string {\n\tmsg, err := reader.ReadBytes('\\n')\n\tcheck(err)\n\tif len(msg) == 0 {\n\t\tmsg = append(msg, 32)\n\t}\n\treturn string(msg)\n}", "func AskForInput() (string, error) {\n\tfmt.Println(\"\\nEnter a sequence of integers, divided by spaces.\")\n\tfmt.Print(\">> \")\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\n\tfmt.Println()\n\n\treturn scanner.Text(), scanner.Err()\n}", "func (mongoImport *MongoImport) getInputReader() (io.ReadCloser, error) {\n\tif mongoImport.InputOptions.File != \"\" {\n\t\tfile, err := os.Open(util.ToUniversalPath(mongoImport.InputOptions.File))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfileStat, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Logf(1, \"filesize: %v\", fileStat.Size())\n\t\treturn file, err\n\t}\n\tlog.Logf(1, \"filesize: 0\")\n\treturn os.Stdin, nil\n}", "func ReadInput(r io.Reader) (map[string]string, error) {\n\tscan := bufio.NewScanner(r)\n\n\tdata := map[string]string{}\n\n\tfor scan.Scan() {\n\t\tkv := bytes.SplitN(scan.Bytes(), []byte(\"=\"), 2)\n\t\tif len(kv) > 1 {\n\t\t\tdata[string(kv[0])] = string(kv[1])\n\t\t}\n\t}\n\n\tif err := scan.Err(); err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func PromptForInput(ctx context.Context, prompt string) (string, error) {\n\tvar input string\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Println(prompt)\n\tscanner.Scan()\n\tinput = scanner.Text()\n\tif scanner.Err() != nil {\n\t\tlog.Error(ctx, \"Failed to read user input\", scanner.Err())\n\t\treturn \"\", scanner.Err()\n\t}\n\treturn input, nil\n}", "func GetInput() (ConcourseInput, error) {\n\tinput := ConcourseInput{}\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tif scanner.Scan() {\n\t\terr := json.Unmarshal(scanner.Bytes(), &input)\n\t\tif err != nil {\n\t\t\treturn input, err\n\t\t}\n\n\t\treturn input, nil\n\t}\n\n\treturn input, errors.New(\"No input received\")\n}", "func readline() (value string, err error) {\n\tvar valb []byte\n\tvar n int\n\tb := make([]byte, 1)\n\tfor {\n\t\t// read one byte at a time so we don't accidentally read extra bytes\n\t\tn, err = os.Stdin.Read(b)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif n == 0 || b[0] == '\\n' {\n\t\t\tbreak\n\t\t}\n\t\tvalb = append(valb, b[0])\n\t}\n\n\treturn strings.TrimSuffix(string(valb), \"\\r\"), nil\n}", "func userInput(inVal string, rangeLower float64, rangeHigher float64, ok bool) string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Println(inVal)\n\tvar input string\n\tfor scanner.Scan() {\n\t\tif ok {\n\t\t\ti, err := strconv.ParseInt(scanner.Text(), 10, 64)\n\t\t\tif err == nil && float64(i) >= rangeLower && float64(i) <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\ti, err := strconv.ParseFloat(scanner.Text(), 64)\n\t\t\tif err == nil && i >= rangeLower && i <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfmt.Println(inVal)\n\t}\n\treturn input\n}", "func GetInput(path string) ([]byte, error) {\n\tf, err := Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn io.ReadAll(f)\n}", "func (c *CmdReal) StdinPipe() (io.WriteCloser, error) {\n\treturn c.cmd.StdinPipe()\n}", "func Read() string {\n\tvar buf bytes.Buffer\n\t_, err := io.Copy(&buf, os.Stdin)\n\tif err != nil {\n\t\tpanic(\"ReadStdin\")\n\t}\n\treturn buf.String()\n}", "func (l *Linenoise) Read(prompt, init string) (string, error) {\n\tif !isatty.IsTerminal(uintptr(syscall.Stdin)) {\n\t\t// Not a tty, read from a file or pipe.\n\t\treturn l.readBasic()\n\t} else if unsupportedTerm() {\n\t\t// Not a terminal we know about, so basic line reading.\n\t\tfmt.Printf(prompt)\n\t\ts, err := l.readBasic()\n\t\tif err == ErrQuit {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t}\n\t\treturn s, err\n\t} else {\n\t\t// A command line on stdin, our raison d'etre.\n\t\treturn l.readRaw(prompt, init)\n\t}\n}", "func GetPasswordFromStdIn(confirm bool) ([]byte, error) {\n\tread := Read()\n\tfmt.Fprint(os.Stderr, \"Enter password for private key: \")\n\tpw1, err := read()\n\tfmt.Fprintln(os.Stderr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !confirm {\n\t\treturn pw1, nil\n\t}\n\tfmt.Fprint(os.Stderr, \"Enter again: \")\n\tpw2, err := read()\n\tfmt.Fprintln(os.Stderr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif string(pw1) != string(pw2) {\n\t\treturn nil, errors.New(\"passwords do not match\")\n\t}\n\treturn pw1, nil\n}" ]
[ "0.74022907", "0.6980113", "0.69574684", "0.6914523", "0.6872895", "0.6857479", "0.67382133", "0.6729678", "0.67284584", "0.667263", "0.6658712", "0.6641374", "0.6628669", "0.6623709", "0.65930325", "0.65362674", "0.65176934", "0.6508544", "0.6500082", "0.64806294", "0.64117384", "0.6392273", "0.63759285", "0.6358561", "0.6346432", "0.6327157", "0.63240767", "0.6318934", "0.6317067", "0.6310918", "0.6273693", "0.62608284", "0.6257561", "0.6240655", "0.6194877", "0.6185446", "0.6179503", "0.616558", "0.61624885", "0.6154316", "0.6150739", "0.61324835", "0.6128474", "0.61271256", "0.6126096", "0.61077696", "0.6107744", "0.60951114", "0.60824007", "0.60508084", "0.603051", "0.6029882", "0.60244614", "0.5996462", "0.59937143", "0.5966368", "0.59396964", "0.593361", "0.59277564", "0.5926742", "0.58845615", "0.5869906", "0.5869353", "0.58660865", "0.5808815", "0.5808111", "0.5790564", "0.57904315", "0.5783649", "0.57698584", "0.57355195", "0.57347286", "0.57158875", "0.5707505", "0.5705802", "0.5684602", "0.5676145", "0.56732845", "0.56730115", "0.56699693", "0.5667408", "0.56554717", "0.56553876", "0.56499404", "0.56417704", "0.563733", "0.5636329", "0.5617564", "0.5615815", "0.5609736", "0.56058306", "0.55988884", "0.5591954", "0.55850655", "0.5578965", "0.5549891", "0.5545578", "0.5536039", "0.55331904", "0.55310506", "0.552981" ]
0.0
-1
userInput reads from Stdin untill newline, if input was empty append space to msg
func userInput() string { msg, err := reader.ReadBytes('\n') check(err) if len(msg) == 0 { msg = append(msg, 32) } return string(msg) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func UserInput() string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"What's up?\")\n\tfmt.Print(\"-> \")\n\tinput, _ := reader.ReadString('\\n')\n\tsanitizedInput := strings.Replace(input, \"\\n\", \"\", -1)\n\treturn sanitizedInput\n}", "func input(cmd_chan chan string) {\n\tin := bufio.NewReader(os.Stdin)\n\n\tlog(\"\")\n\tfor {\n\t\tif cmd, err := in.ReadString('\\n'); err == nil && cmd != \"\\n\" {\n\t\t\tcmd_chan <- strings.Trim(cmd, \"\\n\")\n\t\t}\n\t\tlogPrompt()\n\t}\n}", "func readInput(message string) string {\r\n\tscanner := bufio.NewScanner(os.Stdin)\r\n\tfmt.Print(\"Value of \", message, \" not found. Please enter the value\\n\")\r\n\tscanner.Scan()\r\n\ttext := scanner.Text()\r\n\tfmt.Print(\"\\n Value of text is: \", text)\r\n\treturn text\r\n\r\n}", "func userInputString(prompt string) string {\n\n\tfmt.Printf(\"\\n%s\", prompt)\n\treader := bufio.NewReader(os.Stdin)\n\tname, err := reader.ReadString('\\n')\n\tif err != nil {\n \t\tfmt.Println(err)\n \t\treturn \"\"\n \t}\n \tif runtime.GOOS == \"windows\" {\n \t\tname = strings.TrimRight(name, \"\\r\\n\") \t\t/* for windows */\n \t} else {\n\t\tname = strings.TrimRight(name, \"\\n\") \t\t/* for linux */\n\t}\n\treturn name\n}", "func PromptMessage(message, value string) string {\n\tfor value == \"\" {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(message + \": \")\n\t\tvalueRaw, err := reader.ReadString('\\n')\n\t\terrors.CheckError(err)\n\t\tvalue = strings.TrimSpace(valueRaw)\n\t}\n\treturn value\n}", "func (p *Prompt) GetInput(msg string) (string, error) {\n\tfmt.Fprintln(p.out, msg)\n\tfmt.Fprint(p.out, \"-> \")\n\tp.out.Flush()\n\ttext, err := p.in.ReadString('\\n')\n\treturn strings.TrimSpace(text), err\n}", "func watchForConsoleInput(conn net.Conn) {\n reader := bufio.NewReader(os.Stdin)\n\n for true {\n message, err := reader.ReadString('\\n')\n util.CheckForError(err, \"Lost console connection\")\n\n message = strings.TrimSpace(message)\n if (message != \"\") {\n command := parseInput(message)\n\n if (command.Command == \"\") {\n // there is no command so treat this as a simple message to be sent out\n sendCommand(\"message\", message, conn);\n } else {\n switch command.Command {\n\n // enter a room\n case \"enter\":\n sendCommand(\"enter\", command.Body, conn)\n\n // ignore someone\n case \"ignore\":\n sendCommand(\"ignore\", command.Body, conn)\n\n // leave a room\n case \"leave\":\n // leave the current room (we aren't allowing multiple rooms)\n sendCommand(\"leave\", \"\", conn)\n\n // disconnect from the chat server\n case \"disconnect\":\n sendCommand(\"disconnect\", \"\", conn)\n\n default:\n fmt.Printf(\"Unknown command \\\"%s\\\"\\n\", command.Command)\n }\n }\n }\n }\n}", "func readInput() string {\r\n cmdString, err := reader.ReadString('\\n')\r\n check(err)\r\n\r\n return cmdString\r\n}", "func getInput(request string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\n\" + request)\n\tusrInput, _ := reader.ReadString('\\n')\n\treturn strings.TrimSpace(usrInput)\n}", "func (inputReader InputReader) GetUserInput() string {\n\tdata, _ := inputReader.reader.ReadString('\\n')\n\treturn strings.TrimSuffix(data, \"\\n\")\n}", "func listenForUserInput(blockWrapperChannel chan *BlockWrapper, packetChannel chan Packet, n *Node) {\n\treader := bufio.NewReader(os.Stdin) //constantly be reading in from std in\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil || input == \"\\n\" {\n\t} else {\n\t\tfmt.Println()\n\t\tgo handleUserInput(input, blockWrapperChannel, packetChannel, n)\n\t}\n}", "func getInput(input chan string) {\n for {\n reader := bufio.NewReader(os.Stdin)\n d,_ := reader.ReadString('\\n')\n input <- d\n }\n}", "func Input(s bool, a ...interface{}) string {\n\tif s {\n\t\tfmt.Printf(\"\\a\")\n\t}\n\tfmt.Printf(\"%v\", a...)\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func UserInputHandler() {\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tif input, err := reader.ReadString('\\n'); err != nil {\n\t\t\tlog.Print(err)\n\t\t} else {\n\t\t\tif ws != nil {\n\t\t\t\tif _, err := ws.Write([]byte(input)); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Print(\"Connection closed. Try later!\")\n\t\t\t}\n\t\t}\n\t}\n}", "func ReadUserMessage(msg chan<- []byte) {\n\n\t// Prepare a Reader for input message from the console\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tmessage, _ := reader.ReadBytes('\\n')\n\t\tmsg <- message\n\t}\n}", "func Reader(conn net.Conn){\r\n osReader := bufio.NewReader(os.Stdin) // make a READER\r\n for {\r\n msg,err:=osReader.ReadString('\\n')\r\n if err != nil {\r\n fmt.Println(\"Client DISCONNECTED\")\r\n return\r\n }else {\r\n pass <- msg // pass the user input to channel\r\n }\r\n }\r\n }", "func takeUserInput() string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func Reader(conn net.Conn){\n osReader := bufio.NewReader(os.Stdin) // make a READER\n for {\n msg,err:=osReader.ReadString('\\n')\n if err != nil {\n fmt.Println(\"Client DISCONNECTED\")\n return\n }else {\n pass <- msg // pass the user input to channel\n\n }\n }\n }", "func readInput(conn net.Conn, qst string) (string, error) {\n\tconn.Write([]byte(qst))\n\ts, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\tlog.Printf(\"readinput: could not read input from stdin: %v from client %v\", err, conn.RemoteAddr().String())\n\t\treturn \"\", err\n\t}\n\ts = strings.Trim(s, \"\\r\\n\")\n\treturn s, nil\n}", "func PromptUserForInput(prompt string, terragruntOptions *options.TerragruntOptions) (string, error) {\n\t// We are writing directly to ErrWriter so the prompt is always visible\n\t// no matter what logLevel is configured. If `--non-interactive` is set, we log both prompt and\n\t// a message about assuming `yes` to Debug, so\n\tif terragruntOptions.NonInteractive {\n\t\tterragruntOptions.Logger.Debugf(prompt)\n\t\tterragruntOptions.Logger.Debugf(\"The non-interactive flag is set to true, so assuming 'yes' for all prompts\")\n\t\treturn \"yes\", nil\n\t}\n\tn, err := terragruntOptions.ErrWriter.Write([]byte(prompt))\n\tif err != nil {\n\t\tterragruntOptions.Logger.Error(err)\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\tif n != len(prompt) {\n\t\tterragruntOptions.Logger.Errorln(\"Failed to write data\")\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treader := bufio.NewReader(os.Stdin)\n\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treturn strings.TrimSpace(text), nil\n}", "func read(msg string) string {\n\tfmt.Print(msg)\n\tvar ret, _ = bufio.NewReader(os.Stdin).ReadString('\\n')\n\treturn ret\n}", "func TakeInput() string {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\ttext = removeWhiteSpace(text)\n\treturn text\n}", "func readInput(kind, defaultValue string) (string, error) {\n\tr := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"%s (%s): \", color.YellowString(\"Enter a value\"), kind)\n\ttext, err := r.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif text == \"\\n\" {\n\t\ttext = defaultValue\n\t\tfmt.Printf(\"%s%s (%s): %s\\n\", moveLineUp, color.YellowString(\"Enter a value\"), kind, text)\n\t}\n\tfmt.Println()\n\treturn text, nil\n}", "func (this *Client) handleInput(text string) {\n\tif this.server {\n\t\t// We are the server, so send the message to all peers\n\t\tmsg := CreateMessage(MESSAGE_SHOW, text, this.nick)\n\t\tmsg.Send(this.connections)\n\t} else {\n\t\t// We are a client, so send the message to the server\n\t\tmsg := CreateMessage(MESSAGE_PUBLIC, text, this.nick)\n\t\t// TODO: Clean this up since we know there's only going to be one connection (to the server)\n\t\tmsg.Send(this.connections)\n\t}\n}", "func processInput(introwords string, location int, wid int, ht int, isValid validCheck, uiEvents <-chan ui.Event) (string, string, error) {\n\tintro := newParagraph(introwords, false, location, len(introwords)+4, 3)\n\tlocation += 2\n\tinput := newParagraph(\"\", true, location, wid, ht+2)\n\tlocation += ht + 2\n\twarning := newParagraph(\"<Esc> to go back, <Ctrl+d> to exit\", false, location, wid, 15)\n\n\tui.Render(intro)\n\tui.Render(input)\n\tui.Render(warning)\n\n\t// The input box is wid characters wide\n\t// - 2 chars are reserved for the left and right borders\n\t// - 1 char is left empty at the end of input to visually\n\t// signify that the text box is still accepting input\n\t// The user might want to input a string longer than wid-3\n\t// characters, so we store the full typed input in fullText\n\t// and display a substring of the full text to the user\n\tvar fullText string\n\n\tfor {\n\t\tk := readKey(uiEvents)\n\t\tswitch k {\n\t\tcase \"<C-d>\":\n\t\t\treturn \"\", \"\", ExitRequest\n\t\tcase \"<Escape>\":\n\t\t\treturn \"\", \"\", BackRequest\n\t\tcase \"<Enter>\":\n\t\t\tinputString, warningString, ok := isValid(fullText)\n\t\t\tif ok {\n\t\t\t\treturn inputString, warning.Text, nil\n\t\t\t}\n\t\t\tfullText = \"\"\n\t\t\tinput.Text = \"\"\n\t\t\twarning.Text = warningString\n\t\t\tui.Render(input)\n\t\t\tui.Render(warning)\n\t\tcase \"<Backspace>\":\n\t\t\tif len(input.Text) > 0 {\n\t\t\t\tfullText = fullText[:len(fullText)-1]\n\t\t\t\tstart := max(0, len(fullText)-wid+3)\n\t\t\t\tinput.Text = fullText[start:]\n\t\t\t\tui.Render(input)\n\t\t\t}\n\t\tcase \"<Space>\":\n\t\t\tfullText += \" \"\n\t\t\tstart := max(0, len(fullText)-wid+3)\n\t\t\tinput.Text = fullText[start:]\n\t\t\tui.Render(input)\n\t\tdefault:\n\t\t\t// the termui use a string begin at '<' to represent some special keys\n\t\t\t// for example the 'F1' key will be parsed to \"<F1>\" string .\n\t\t\t// we should do nothing when meet these special keys, we only care about alphabets and digits.\n\t\t\tif k[0:1] != \"<\" {\n\t\t\t\tfullText += k\n\t\t\t\tstart := max(0, len(fullText)-wid+3)\n\t\t\t\tinput.Text = fullText[start:]\n\t\t\t\tui.Render(input)\n\t\t\t}\n\t\t}\n\t}\n}", "func ReadInput(printText string, defaultVal Default, validate func(value string) bool, invalidText string, retryOnInvalid bool) (string, error) {\n\tretry := true\n\tvalue := \"\"\n\treader := bufio.NewReader(os.Stdin)\n\ttext := fmt.Sprintf(\"%s: \", printText)\n\tif defaultVal.IsDefault {\n\t\ttext = fmt.Sprintf(\"%s: %s: \", printText, defaultVal.Value)\n\t}\n\n\tfor retry {\n\t\tfmt.Print(text)\n\t\tinputValue, err := reader.ReadString('\\n')\n\t\tvalue = strings.TrimSpace(inputValue)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif value == \"\" && defaultVal.IsDefault {\n\t\t\treturn defaultVal.Value, nil\n\t\t}\n\n\t\tisValid := validate(value)\n\n\t\tif !isValid {\n\t\t\tfmt.Println(invalidText)\n\t\t\tif !retryOnInvalid {\n\t\t\t\treturn value, errors.New(\"input validation failed\")\n\t\t\t}\n\t\t}\n\n\t\tretry = retryOnInvalid && !isValid\n\t}\n\n\treturn value, nil\n}", "func readMessage() string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func localClientInput(conn net.Conn) {\n\tfmt.Print(\"> \")\n\tscanner := bufio.NewScanner(os.Stdin)\n\twriter := bufio.NewWriter(conn)\n\tfor scanner.Scan() {\n\t\tfmt.Print(\"> \")\n\t\t_, err := writer.WriteString(scanner.Text() + \"\\n\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\twriter.Flush()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func userInput(inVal string, rangeLower float64, rangeHigher float64, ok bool) string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Println(inVal)\n\tvar input string\n\tfor scanner.Scan() {\n\t\tif ok {\n\t\t\ti, err := strconv.ParseInt(scanner.Text(), 10, 64)\n\t\t\tif err == nil && float64(i) >= rangeLower && float64(i) <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\ti, err := strconv.ParseFloat(scanner.Text(), 64)\n\t\t\tif err == nil && i >= rangeLower && i <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfmt.Println(inVal)\n\t}\n\treturn input\n}", "func get_input(question string) string {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Printf(question)\n\t\tresponse, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Err: %s\\n\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tresponse = cleanInput(response)\n\t\tif len(response) > 0 {\n\t\t\treturn response\n\t\t}\n\t}\n}", "func RequestInput(message string, validate ValidatorFunction) (string, error) {\n\tfor {\n\t\tvalue, err := skipEOFError(getTextInput(fmt.Sprintf(\"%s: \", message)))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvalue = strings.TrimSpace(value)\n\t\tif err = validate(value); err != nil {\n\t\t\tfmt.Println(strings.TrimSpace(err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\treturn value, nil\n\t}\n}", "func InputPrompt(label string, required bool) string {\n\tinput := bufio.NewScanner(os.Stdin)\n\n\tfmt.Printf(\"%s : \\n\", label)\n\tfor input.Scan() {\n\n\t\tinputValue := input.Text()\n\t\tif !required || len(inputValue) > 0 {\n\t\t\treturn inputValue\n\t\t}\n\n\t\tfmt.Printf(\"%s : \\n\", label)\n\t}\n\n\treturn \"\"\n}", "func GetInputString(scnr scanner, msg, def string) string {\n\tif def == \"\" {\n\t\tfmt.Printf(\"%s: \", msg)\n\t} else {\n\t\tfmt.Printf(\"%s [%s]: \", msg, def)\n\t}\n\tfor scnr.Scan() {\n\t\tinput := scnr.Text()\n\t\tif input == \"\" {\n\t\t\treturn def\n\t\t}\n\t\treturn input\n\t}\n\treturn \"\"\n}", "func InputWithError(prompt string) (string, error) {\n\tfmt.Print(prompt)\n\tin := bufio.NewReader(os.Stdin)\n\tline, err := in.ReadString('\\n')\n\tif err != nil {\n\t\treturn line, err\n\t}\n\t// else\n\tline = strings.TrimRight(line, \"\\r\\n\")\n\treturn line, nil\n}", "func Input(prompt string) string {\n\ttext, err := InputWithError(prompt)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn text\n}", "func GetFromStdin(params *GetFromStdinParams) *string {\n\tparamutil.SetDefaults(params, defaultParams)\n\n\tvalidationRegexp, _ := regexp.Compile(params.ValidationRegexPattern)\n\tinput := \"\"\n\n\tfor {\n\t\tfmt.Print(params.Question)\n\n\t\tif len(params.DefaultValue) > 0 {\n\t\t\tfmt.Print(\"\\n\")\n\t\t\tlog.WriteColored(\"Press ENTER to use: \"+params.DefaultValue, ct.Green)\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\n\t\tfor {\n\t\t\tfmt.Print(\"> \")\n\n\t\t\treader := bufio.NewReader(os.Stdin)\n\t\t\tnextLine := \"\"\n\n\t\t\tif params.IsPassword {\n\t\t\t\tinStreamFD := command.NewInStream(os.Stdin).FD()\n\t\t\t\toldState, err := term.SaveState(inStreamFD)\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\tterm.DisableEcho(inStreamFD, oldState)\n\t\t\t\tnextLine, _ = reader.ReadString('\\n')\n\t\t\t\tterm.RestoreTerminal(inStreamFD, oldState)\n\t\t\t} else {\n\t\t\t\tnextLine, _ = reader.ReadString('\\n')\n\t\t\t}\n\n\t\t\tnextLine = strings.Trim(nextLine, \"\\r\\n \")\n\n\t\t\tif strings.Compare(params.InputTerminationString, \"\\n\") == 0 {\n\t\t\t\t// Assign the input value to input var\n\t\t\t\tinput = nextLine\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tinput += nextLine + \"\\n\"\n\n\t\t\tif strings.HasSuffix(input, params.InputTerminationString+\"\\n\") {\n\t\t\t\tinput = strings.TrimSuffix(input, params.InputTerminationString+\"\\n\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif len(input) == 0 && len(params.DefaultValue) > 0 {\n\t\t\tinput = params.DefaultValue\n\t\t}\n\t\tif validationRegexp.MatchString(input) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Print(\"Input must match \" + params.ValidationRegexPattern + \"\\n\")\n\t\t\tinput = \"\"\n\t\t}\n\t}\n\tfmt.Println(\"\")\n\n\treturn &input\n}", "func readString(toRead string) string {\n\n\tfmt.Printf(\"Please enter the %s: \", toRead)\n\n\t// read from scanner\n\tscanner := bufio.NewScanner(os.Stdin)\n scanner.Scan()\n s := scanner.Text()\n\n\tif s == \"\" {\n\t\ts = \"N/A\"\n\t}\n\n\treturn s\n}", "func waitForuserInput(scanner bufio.Scanner) {\n\tenter := \"wait for user\"\n\tfor enter != \"\" {\n\t\tfmt.Printf(\"\\nPlease press enter to continue: \")\n\t\tenter = scanWithValidation(scanner)\n\t}\n}", "func PromptForInput(ctx context.Context, prompt string) (string, error) {\n\tvar input string\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Println(prompt)\n\tscanner.Scan()\n\tinput = scanner.Text()\n\tif scanner.Err() != nil {\n\t\tlog.Error(ctx, \"Failed to read user input\", scanner.Err())\n\t\treturn \"\", scanner.Err()\n\t}\n\treturn input, nil\n}", "func getInput() (string, error) {\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(text), nil\n}", "func main() {\n\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Enter your name:\")\n\n\tname, _ := reader.ReadString('\\n')\n\tfmt.Print(\"Your name is \", name)\n\n}", "func LogUserInput(text string) string {\n\treturn html.EscapeString(\n\t\tstrings.Replace(\n\t\t\tstrings.Replace(text, \"\\r\", \"\", -1),\n\t\t\t\"\\n\",\n\t\t\t\"\",\n\t\t\t-1,\n\t\t),\n\t)\n}", "func ReadInput() (input string) {\n\tkbReader := bufio.NewReader(os.Stdin)\n\tinput, _ = kbReader.ReadString('\\n') // 엔터키가 나올때까지 입력을 받음.\n\tinput = strings.Replace(input, \" \", \"\", -1) // input에서 모든 공백 제거\n\n\treturn\n}", "func InteractiveInput(prompt string) string {\n\tif prompt != \"\" {\n\t\tfmt.Printf(\"%s \", prompt)\n\t}\n\tinput, err := bufio.NewReader(os.Stdin).ReadString('\\n')\n\tCheck(err)\n\n\t// sanitize input\n\treturn SanitizeInput(input)\n}", "func getUserInput(question string) bool {\n\tvar input string\n\tfor input != \"1\" && input != \"2\" {\n\t\tfmt.Println(question)\n\t\tfmt.Scan(&input)\n\t}\n\n\treturn input == \"1\"\n}", "func readNewOrKeepDefaultString(toRead string, def string) string {\n\n\tfmt.Printf(\"Please enter the %s [%s]: \", toRead, def)\n\n\t// read from scanner\n\tscanner := bufio.NewScanner(os.Stdin)\n scanner.Scan()\n s := scanner.Text()\n\n\tif s == \"\" {\n\t\ts = def\n\t}\n\n\treturn s\n}", "func enterUserName() string {\n\tfmt.Println(\"Wat is uw gebruikersnaam?\")\n\n\tvar userName string\n\tfmt.Scanf(\"%s\", &userName)\n\n\treturn userName\n}", "func checkShot(input chan string, b *Board, r *bufio.Reader, conn net.Conn, username string) {\n message, _ := r.ReadString('\\n')\n input <- message\n}", "func getInput() string {\n\tvar str string\n\tscanner := bufio.NewScanner(os.Stdin)\n\tif scanner.Scan() {\n\t\tstr = scanner.Text()\n\t}\n\n\treturn str\n}", "func (console *Console) Prompt() (string, error) {\n\tfmt.Print(\">\")\n\n\trawInput, hasMore, err := console.reader.ReadLine()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"issue reading from STDIN\")\n\t}\n\n\tinput := string(rawInput)\n\n\tif hasMore {\n\t\trawInput, hasMore, err = console.reader.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"issue reading additional characters in buffer\")\n\t\t}\n\n\t\tinput += string(rawInput)\n\t}\n\n\treturn input, nil\n}", "func getInput(r *bufio.Reader, q string) string {\n\tfmt.Printf(\"%s:\\n\", q)\n\ttext, err := r.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"an error has occured: %s\", err.Error())\n\t\tos.Exit(2)\n\t}\n\treturn text\n}", "func readInput(in io.Reader) (string, error) {\n\tline, _, err := bufio.NewReader(in).ReadLine()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error while reading input\")\n\t}\n\treturn strings.TrimSpace(string(line)), nil\n}", "func getConsoleInput(loadedGame *gameStaticData) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"> \")\n\ttextInput, _ := reader.ReadString('\\n')\n\tsplitWord, extractStatus := extractWords(textInput)\n\tif extractStatus {\n\t\ttruncatedWord := truncateWords(loadedGame, splitWord)\n\t\tfmt.Printf(\"DEBUG: truncated words: \\\"%s\\\", \\\"%s\\\"\\n\", truncatedWord[0], truncatedWord[1])\n\t\tidentifiedWordsObjectsExits := deduceThingsFromInput(loadedGame, truncatedWord)\n\t\tfmt.Println(\"DEBUG: found verb(s):\", identifiedWordsObjectsExits.verb)\n\t\tfmt.Println(\"DEBUG: found noun(s):\", identifiedWordsObjectsExits.noun)\n\t\tfmt.Println(\"DEBUG: found noun for object(s):\", identifiedWordsObjectsExits.object)\n\t\tfmt.Println(\"DEBUG: found directions for noun(s):\", identifiedWordsObjectsExits.direction)\n\t}\n}", "func userInput() (string, string, int, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"Enter the filepath for the manifest file: \")\n\tfilePath, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", \"\", 0, fmt.Errorf(\"could not read user input: %s\", err.Error())\n\t}\n\t// remove trailing newline char\n\tfilePath = strings.Trim(filePath, \"\\n\")\n\n\tfmt.Print(\"Enter the namespace to deploy to: \")\n\tnamespace, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", \"\", 0, fmt.Errorf(\"could not read user input: %s\", err.Error())\n\t}\n\t// remove trailing newline char\n\tnamespace = strings.Trim(namespace, \"\\n\")\n\n\tvar deletionDelay int\n\tfmt.Print(\"Enter the time delay in seconds between resource becoming available and being deleted: \")\n\t_, err = fmt.Scanf(\"%d\", &deletionDelay)\n\tif err != nil {\n\t\treturn \"\", \"\", 0, fmt.Errorf(\"could not read user input: %s\", err.Error())\n\t}\n\tfmt.Println(deletionDelay)\n\n\treturn filePath, namespace, deletionDelay, nil\n}", "func (c *Client) Ask(prompt string) string {\n\tfmt.Printf(\"%s \", prompt)\n\trd := bufio.NewReader(os.Stdin)\n\tline, err := rd.ReadString('\\n')\n\tif err == nil {\n\t\treturn strings.TrimSpace(line)\n\t}\n\treturn \"\"\n}", "func readInput() (string, error) {\n buffer := make([]byte, 100)\n\n cnt, err := os.Stdin.Read(buffer)\n if err != nil {\n return \"\", err\n }\n\n if cnt == 1 && buffer[0] == 0x1b {\n return \"ESC\", nil\n }else if cnt >= 3 {\n if buffer[0] == 0x1b && buffer[1] == '[' {\n switch buffer[2] {\n case 'A':\n return \"UP\", nil\n case 'B':\n return \"DOWN\", nil\n case 'C':\n return \"RIGHT\", nil\n case 'D':\n return \"LEFT\", nil\n }\n }\n }\n\n return \"\", nil\n}", "func Input(query string, predef string) string {\n\tif *DryRunFlag {\n\t\treturn DryRunPop()\n\t}\n\tinputUI := &input.UI{\n\t\tWriter: os.Stdout,\n\t\tReader: os.Stdin,\n\t}\n\tinput, err := inputUI.Ask(query, &input.Options{\n\t\tDefault: predef,\n\t\tRequired: true,\n\t\tLoop: true,\n\t})\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn input\n}", "func getInput(node *noise.Node, overlay *kademlia.Protocol) {\n\tr := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tbuf, _, err := r.ReadLine()\n\n\t\tif err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\tline := string(buf)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase line == \"/discover\":\n\t\t\tdiscover(overlay)\n\t\t\tcontinue\n\t\tcase line == \"/peers\":\n\t\t\tids := overlay.Table().Peers()\n\t\t\tstr := fmtPeers(ids)\n\t\t\tfmt.Printf(\"You know %d peer(s): [%v]\\n\", len(ids), strings.Join(str, \", \"))\n\t\t\tcontinue\n\t\tcase line == \"/me\":\n\t\t\tme := node.ID()\n\t\t\tfmt.Printf(\"%s(%s)\\n\", me.Address, me.ID.String()[:printedLength])\n\t\t\tcontinue\n\t\tcase strings.Contains(line, \"/ping\"):\n\t\t\taddr := strings.Fields(line)[1]\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\t\t\t_, err := node.Ping(ctx, addr)\n\t\t\tcancel()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to ping node (%s). Skipping... [error: %s]\\n\", addr, err)\n\t\t\t}\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\n\t\tfor _, id := range overlay.Table().Peers() {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\t\t\terr := node.SendMessage(ctx, id.Address, message{contents: line})\n\t\t\tcancel()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to send message to %s(%s). Skipping... [error: %s]\\n\",\n\t\t\t\t\tid.Address,\n\t\t\t\t\tid.ID.String()[:printedLength],\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func getInput(trim bool) string {\n fi, err := os.Stdin.Stat()\n if err != nil {\n panic(err)\n }\n\n if fi.Mode() & os.ModeNamedPipe == 0 {\n fmt.Println(\"Nothing to draw\")\n os.Exit(0)\n }\n\n reader := bufio.NewReader(os.Stdin)\n var input []rune\n for {\n\t\tchunk, _, err := reader.ReadRune()\n\t\tif err != nil && err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tinput = append(input, chunk)\n\t}\n\n if trim {\n return strings.TrimSpace(string(input))\n }\n\n return string(input)\n}", "func readInput() (string, error) {\n\tbuffer := make([]byte, 100)\n\tcnt, err := os.Stdin.Read(buffer)\n\n\t// If error, return error and empty string\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// If the key press is esc\n\tif cnt == 1 && buffer[0] == 0x1b {\n\t\treturn \"ESC\", nil\n\t} else if cnt >= 3 {\n\t\tif buffer[0] == 0x1b && buffer[1] == '[' {\n\t\t\tswitch buffer[2] {\n\t\t\tcase 'A':\n\t\t\t\treturn \"UP\", nil\n\t\t\tcase 'B':\n\t\t\t\treturn \"DOWN\", nil\n\t\t\tcase 'C':\n\t\t\t\treturn \"RIGHT\", nil\n\t\t\tcase 'D':\n\t\t\t\treturn \"LEFT\", nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil // Nothing read in\n}", "func scanUserRequest() userRequest {\n\n\temptyStr := \" \"\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\tline := scanner.Text()\n\tline = strings.Trim(line, emptyStr)\n\tarr := strings.Split(line, emptyStr)\n\n\tvar userRequest userRequest\n\n\tif len(arr) != 3 {\n\n\t\tuserRequest.cmd = emptyStr\n\t\tuserRequest.inputOne = emptyStr\n\t\tuserRequest.inputTwo = emptyStr\n\n\t\treturn userRequest\n\t}\n\n\tuserRequest.cmd = arr[0]\n\tuserRequest.inputOne = arr[1]\n\tuserRequest.inputTwo = arr[2]\n\n\treturn userRequest\n\n}", "func Menu(username string) {\r\n\r\n\tvar response string\r\n\tin := bufio.NewReader(os.Stdin)\r\n\r\n\tfor {\r\n\r\n\t\tfmt.Println()\r\n\t\tfmt.Println(\"\\t\\tWelcome to our Chat Service\", username+\"!\\n\")\r\n\t\tfmt.Println(\"Select one of the choices below!\")\r\n\t\tfmt.Println(\"1. Create a new channel\")\r\n\t\tfmt.Println(\"2. Join an existing channel\")\r\n\t\tfmt.Println(\"3. Start a direct message with another user\")\r\n\t\tfmt.Println(\"4. Quit\")\r\n\r\n\t\tfmt.Print(\"Select a number 1-4: \")\r\n\t\tresponse, _ = in.ReadString('\\n')\r\n\t\tresponse = strings.TrimSpace(response)\r\n\r\n\t\tswitch response {\r\n\r\n\t\tcase \"1\":\r\n\t\t\taddch.Begin()\r\n\t\tcase \"2\":\r\n\t\t\tjoinch.Begin(username)\r\n\t\tcase \"3\":\r\n\t\t\tdm.RunDM(username)\r\n\t\tcase \"4\":\r\n\t\t\tfmt.Println(\"Thank you\", username, \"for chatting with us!\")\r\n\t\t\tos.Exit(1)\r\n\t\tdefault:\r\n\t\t\tfmt.Println(\"Invalid response. Please try again.\")\r\n\t\t\tcontinue\r\n\t\t}\r\n\t}\r\n}", "func (ptr *terminalPrompter) PromptInput(prompt string) (string, error) {\n\tif ptr.supported {\n\t\tptr.rawMode.ApplyMode()\n\t\tdefer ptr.normalMode.ApplyMode()\n\t} else {\n\t\t// liner tries to be smart about printing the prompt\n\t\t// and doesn't print anything if input is redirected.\n\t\t// Un-smart it by printing the prompt always.\n\t\tfmt.Print(prompt)\n\t\tprompt = \"\"\n\t\tdefer fmt.Println()\n\t}\n\treturn ptr.State.Prompt(prompt)\n}", "func watchForConnectionInput(username string, properties util.Properties, conn net.Conn) {\n reader := bufio.NewReader(conn)\n\n for true {\n message, err := reader.ReadString('\\n')\n util.CheckForError(err, \"Lost server connection\");\n message = strings.TrimSpace(message)\n if (message != \"\") {\n Command := parseCommand(message)\n switch Command.Command {\n\n // the handshake - send out our username\n case \"ready\":\n sendCommand(\"user\", username, conn)\n\n // the user has connected to the chat server\n case \"connect\":\n fmt.Printf(properties.HasEnteredTheLobbyMessage + \"\\n\", Command.Username)\n\n // the user has disconnected\n case \"disconnect\":\n fmt.Printf(properties.HasLeftTheLobbyMessage + \"\\n\", Command.Username)\n\n // the user has entered a room\n case \"enter\":\n fmt.Printf(properties.HasEnteredTheRoomMessage + \"\\n\", Command.Username, Command.Body)\n\n // the user has left a room\n case \"leave\":\n fmt.Printf(properties.HasLeftTheRoomMessage + \"\\n\", Command.Username, Command.Body)\n\n // the user has sent a message\n case \"message\":\n if (Command.Username != username) {\n fmt.Printf(properties.ReceivedAMessage + \"\\n\", Command.Username, Command.Body)\n }\n\n // the user has connected to the chat server\n case \"ignoring\":\n fmt.Printf(properties.IgnoringMessage + \"\\n\", Command.Body)\n }\n }\n }\n}", "func CleanInput(reader *bufio.Reader) string {\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting input to clean it: %v \\n\", err)\n\t}\n\tinput = strings.TrimSuffix(input, \"\\n\")\n\n\treturn input\n}", "func askQuestionToUser(isImportant bool, question string) string {\n\tprint(\"\\n\")\n\tif isImportant {\n\t\tcolor.Style{color.Cyan, color.OpBold}.Print(question)\n\t} else {\n\t\tcolor.Style{color.Cyan}.Print(question)\n\t}\n\tinput := bufio.NewScanner(os.Stdin)\n\tinput.Scan()\n\treturn input.Text()\n}", "func (s *ShellSession) handleKeyboardInput(log log.T) (err error) {\n\tvar (\n\t\tstdinBytesLen int\n\t)\n\n\t//handle double echo and disable input buffering\n\ts.disableEchoAndInputBuffering()\n\n\tstdinBytes := make([]byte, StdinBufferLimit)\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tif stdinBytesLen, err = reader.Read(stdinBytes); err != nil {\n\t\t\tlog.Errorf(\"Unable read from Stdin: %v\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tif err = s.Session.DataChannel.SendInputDataMessage(log, message.Output, stdinBytes[:stdinBytesLen]); err != nil {\n\t\t\tlog.Errorf(\"Failed to send UTF8 char: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\t// sleep to limit the rate of data transfer\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\treturn\n}", "func ReadString(prompt string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(prompt)\n\ttext, _ := reader.ReadString('\\n')\n\tcleanText := strings.TrimSpace(text)\n\tif cleanText == \"exit\" {\n\t\tlog.Fatal(\"exitting program...\")\n\t}\n\n\treturn cleanText\n}", "func askInput(message string, response interface{}) error {\n\treturn survey.AskOne(&survey.Input{Message: message}, response, survey.MinLength(1))\n}", "func printTheInput(pipe chan string) {\n\tvar lineFromChannel string\n\n\tfor {\n\t\t// Block and then wait for the string\n\t\tlineFromChannel = <-pipe\n\t\tif lineFromChannel == \"exit\\n\" {\n\t\t\tbreak\n\t\t}\n\t\t// TrimSuffix chomps the newline off the end of the string\n\t\tfmt.Println(\"Got the string \\\"\" + strings.TrimSuffix(lineFromChannel, \"\\n\") + \"\\\" from the channel\")\n\t}\n}", "func AskForInput() (string, error) {\n\tfmt.Println(\"\\nEnter a sequence of integers, divided by spaces.\")\n\tfmt.Print(\">> \")\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\n\tfmt.Println()\n\n\treturn scanner.Text(), scanner.Err()\n}", "func (c Client) getUserName() string {\n\tvar username string\n\tfor {\n\t\tfmt.Fprint(c.Output, \"=> Enter your username: \")\n\t\treader := bufio.NewReader(os.Stdin)\n\n\t\tu, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(c.Output, \"Unexpected error: %v.\\n\", err)\n\t\t}\n\n\t\tu = strings.TrimSpace(strings.TrimRight(u, \"\\r\\n\"))\n\t\tif u != \"\" {\n\t\t\tusername = u\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Fprintln(c.Output, \"Please enter a valid user name\")\n\t}\n\n\treturn username\n}", "func parseInput(message string) Command {\n res := standardInputMessageRegex.FindAllStringSubmatch(message, -1)\n if (len(res) == 1) {\n // there is a command\n return Command {\n Command: res[0][1],\n Body: res[0][2],\n }\n } else {\n return Command {\n Body: util.Decode(message),\n }\n }\n}", "func readInput(output string) (num int) {\n\tfor {\n\t\t// Create a new reader\n\t\tbuf := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(output + \"\\n\")\n\t\tsentence, err := buf.ReadString('\\n')\n\t\t// Check if error\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\t// remove newLine Char\n\t\t\tsentence = strings.TrimSuffix(sentence, \"\\n\")\n\t\t\t// Check if input is numeric\n\t\t\tif result, converted := isNumeric(sentence); result {\n\t\t\t\treturn converted\n\t\t\t}\n\t\t\tfmt.Println(string(errorInt))\n\t\t}\n\t}\n}", "func Prompt(msg string) (string, error) {\n\tif !IsInteractive() {\n\t\treturn \"\", fmt.Errorf(\"not an interactive session\")\n\t}\n\n\tpromptMux.Lock()\n\tdefer promptMux.Unlock()\n\n\t// Even if Wash is running interactively, it will not have control of STDIN while another command\n\t// is running within the shell environment. If it doesn't have control and tries to read from it,\n\t// the read will fail. If we have control, read normally. If not, temporarily acquire control for\n\t// the current process group while we're prompting, then return it afterward so the triggering\n\t// command can continue.\n\tinFd := int(os.Stdin.Fd())\n\tinGrp, err := tcGetpgrp(inFd)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error getting process group controlling stdin: %v\", err)\n\t}\n\tcurGrp := unix.Getpgrp()\n\n\tvar v string\n\tif inGrp == curGrp {\n\t\t// We control stdin\n\t\tfmt.Fprintf(os.Stderr, \"%s: \", msg)\n\t\t_, err = fmt.Scanln(&v)\n\t} else {\n\t\t// Need to get control, prompt, then return control.\n\t\tif err := tcSetpgrp(inFd, curGrp); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error getting control of stdin: %v\", err)\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"%s: \", msg)\n\t\t_, err = fmt.Scanln(&v)\n\t\tif err := tcSetpgrp(inFd, inGrp); err != nil {\n\t\t\t// Panic if we can't return control. A messed up environment that they 'kill -9' is worse.\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\t// Return the error set by Scanln.\n\treturn v, err\n}", "func input() io.Reader {\n\tif isatty.IsTerminal(os.Stdin.Fd()) {\n\t\treturn strings.NewReader(\"{}\")\n\t}\n\n\treturn os.Stdin\n}", "func (client *Client) InputReader(c net.Conn) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Print(\"> \")\n\tfor scanner.Scan() {\n\t\targs := strings.Split(scanner.Text(), \" \")\n\t\tif args[0] == \"exit\" {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tresponse, err := client.processCommand(c, args[0], args[1:]...)\n\t\tparseResponse(response, err, defaultTag)\n\t\tif args[0] == \"subscribe\" {\n\t\t\tsubscribePattern(c, scanner)\n\t\t\tfmt.Printf(\"\\r%s\", defaultTag)\n\t\t}\n\t}\n\n\tif scanner.Err() != nil {\n\t\tfmt.Printf(\"%v\", scanner.Err())\n\t\tos.Exit(2)\n\t}\n}", "func MustReadIn() string {\n\tfor i := 0; i < 3; i++ {\n\t\ttext, err := tryReadStdIn()\n\t\tif err == nil {\n\t\t\treturn strings.TrimSpace(text)\n\t\t}\n\t\t// TODO Theme\n\t\tfmt.Printf(\"Error while reading stdin:: %s. Failed %d/3\\n\", err, i)\n\t}\n\tfmt.Println(\"Could not read stdin. Aborting...\")\n\tos.Exit(1)\n\treturn \"\"\n}", "func (term *Terminal) prompt(buf *Buffer, in io.Reader) (string, error) {\n\tinput, err := term.setup(buf, in)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tterm.History = append(term.History, \"\")\n\tterm.histIdx = len(term.History) - 1\n\tcurHistIdx := term.histIdx\n\n\tfor {\n\t\ttyp, char, err := term.read(input)\n\t\tif err != nil {\n\t\t\treturn buf.String(), err\n\t\t}\n\n\t\tswitch typ {\n\t\tcase evChar:\n\t\t\terr = buf.Insert(char)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evSkip:\n\t\t\tcontinue\n\t\tcase evReturn:\n\t\t\terr = buf.EndLine()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tline := buf.String()\n\t\t\tif line == \"\" {\n\t\t\t\tterm.histIdx = curHistIdx - 1\n\t\t\t\tterm.History = term.History[:curHistIdx]\n\t\t\t} else {\n\t\t\t\tterm.History[curHistIdx] = line\n\t\t\t}\n\n\t\t\treturn line, nil\n\t\tcase evEOF:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrEOF\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evCtrlC:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrCTRLC\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evBack:\n\t\t\terr = buf.DelLeft()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evClear:\n\t\t\terr = buf.ClsScreen()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evHome:\n\t\t\terr = buf.Start()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evEnd:\n\t\t\terr = buf.End()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evUp:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx > 0 {\n\t\t\t\tidx--\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evDown:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx < len(term.History)-1 {\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evRight:\n\t\t\terr = buf.Right()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evLeft:\n\t\t\terr = buf.Left()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evDel:\n\t\t\terr = buf.Del()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\t}\n\t}\n}", "func (cli CLI) AskString(query string, defaultStr string) (string, error) {\n\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, os.Interrupt)\n\tdefer signal.Stop(sigCh)\n\n\tresult := make(chan string, 1)\n\tgo func() {\n\t\tfmt.Fprintf(cli.errStream, \"%s [default: %s] \", query, defaultStr)\n\n\t\t// TODO when string includes blank ...\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tline, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tDebugf(\"Failed to scan stdin: %s\", err.Error())\n\t\t}\n\t\tDebugf(\"Input: %q\", line)\n\n\t\t// Use Default value\n\t\tline = strings.TrimRight(line, \"\\n\")\n\t\tif line == \"\" {\n\t\t\tresult <- defaultStr\n\t\t}\n\n\t\tresult <- line\n\t}()\n\n\tselect {\n\tcase <-sigCh:\n\t\treturn \"\", fmt.Errorf(\"interrupted\")\n\tcase str := <-result:\n\t\treturn str, nil\n\t}\n}", "func waitForInput(pipe chan string) {\n\tvar line string\n\tvar err error\n\n\tbuf := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Print(\"Enter a string (or \\\"exit\\\" to quit): \")\n\t\tline, err = buf.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\t// Send the string that was entered to the other goroutine\n\t\tpipe <- line\n\n\t\tif line == \"exit\\n\" {\n\t\t\t// Close the pipe on exit to avoid a deadlock\n\t\t\tclose(pipe)\n\t\t\tbreak\n\t\t}\n\n\t\t// Sleep for a 500ms to allow the other go routine print the string\n\t\ttime.Sleep(500 + time.Millisecond)\n\t}\n}", "func TermMessage(msg ...interface{}) {\n\tscreenb := TempFini()\n\n\tfmt.Println(msg...)\n\tfmt.Print(\"\\nPress enter to continue\")\n\n\treader := bufio.NewReader(os.Stdin)\n\treader.ReadString('\\n')\n\n\tTempStart(screenb)\n}", "func ReadString(msg string) string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Print(msg)\n\tscanner.Scan()\n\treturn scanner.Text()\n}", "func cleanInput(reader *bufio.Reader) string {\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil && err != io.EOF {\n\t\tfmt.Println(\"Error reading line\", err)\n\t}\n\t// windows does carriage return and new line,\n\t// other OSes don't (I believe)\n\tinput = strings.Replace(input, \"\\r\", \"\", -1)\n\tinput = strings.Replace(input, \"\\n\", \"\", -1)\n\n\treturn input\n}", "func (c Client) parseUserCommand() messages.PlayerReq {\n\tvar req messages.PlayerReq\n\n\tfor {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Fprint(c.Output, \"=> \")\n\t\ttext, _ := reader.ReadString('\\n')\n\n\t\ttext = strings.TrimSpace(text)\n\t\tif text == \"\" {\n\t\t\tfmt.Fprintln(c.Output, \"Please enter a valid command\")\n\t\t}\n\n\t\tparts := strings.Split(text, \" \")\n\n\t\treq = messages.PlayerReq{\n\t\t\tAction: game.PlayerAction(parts[0]),\n\t\t}\n\n\t\tif len(parts) > 1 {\n\t\t\tjoined := strings.Join(parts[1:len(parts)], \"\")\n\t\t\treq.Value = strings.TrimRight(joined, \"\\r\\n\")\n\t\t}\n\n\t\tbreak\n\t}\n\n\treturn req\n}", "func ReadMessage(conn *websocket.Conn, stopChan chan<- bool) {\n\tfor {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tstopChan <- true\n\t\t\treturn\n\t\t}\n\t\terr = conn.WriteMessage(websocket.TextMessage, []byte(text))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func input_ln(fp*bufio.Reader)error{\nvar prefix bool\nvar err error\nvar buf[]byte\nvar b[]byte\nbuffer= nil\nfor buf,prefix,err= fp.ReadLine()\nerr==nil&&prefix\nb,prefix,err= fp.ReadLine(){\nbuf= append(buf,b...)\n}\nif len(buf)> 0{\nbuffer= bytes.Runes(buf)\n}\nif err==io.EOF&&len(buffer)!=0{\nreturn nil\n}\nif err==nil&&len(buffer)==0{\nbuffer= append(buffer,' ')\n}\nreturn err\n}", "func ReadIn() string {\n\ttext, err := tryReadStdIn()\n\tif err == nil {\n\t\treturn strings.TrimSpace(text)\n\t}\n\tfmt.Printf(\"Error while reading stdin: %s\", err)\n\treturn \"\"\n}", "func CheckInput(sc ServerConfig) {\n\tfor {\n\t\tenvelope, ok := <-sc.Input\n\t\tif !ok {\n\t\t\tpanic(\"channels closed..\")\n\t\t}\n\t\tfmt.Printf(\"Received msg from %d to %d\\n\", envelope.SendBy, envelope.SendTo)\n\t\tsc.N_msgRcvd++\n\t}\n}", "func InputSecure(w io.Writer, prefix string, r io.Reader, validators ...func(string) error) (string, error) {\n\tif !IsStdin(r) {\n\t\treturn Input(w, prefix, r, validators...)\n\t}\n\n\tread := func() (string, error) {\n\t\tfmt.Fprint(w, Bold(prefix))\n\t\tp, err := term.ReadPassword(int(syscall.Stdin))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn string(p), nil\n\t}\n\nouter:\n\tfor {\n\t\tline, err := read()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tfor _, validate := range validators {\n\t\t\tif err := validate(line); err != nil {\n\t\t\t\tfmt.Fprintln(w, err.Error())\n\t\t\t\tcontinue outer\n\t\t\t}\n\t\t}\n\n\t\treturn line, nil\n\t}\n}", "func readInput(inCh chan byte) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tinput := scanner.Bytes()\n\t\tfor _, c := range input {\n\t\t\tinCh <- c\n\t\t}\n\t}\n}", "func stdInText(b strings.Builder) (string, uint, error) {\n\tvar count uint\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tb.WriteString(scanner.Text())\n\t\tb.WriteString(\" \")\n\t\tcount++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\treturn strings.TrimSpace(b.String()), count, nil\n}", "func QueryInputString(rd *bufio.Reader, query string) string {\n\tfmt.Println(query)\n\tfmt.Printf(\">\")\n\treturn strings.TrimSpace(ReadInputString(rd))\n}", "func ReadLine(msg string) (string, error) {\n\tvar s string\n\tPrintfInfo(msg)\n\t_, err := fmt.Scanf(\"%s\", &s)\n\treturn s, err\n}", "func readInputLoop(dt *discordterm.Client) {\n\trd := bufio.NewReader(os.Stdin)\n\n\tl, err := readline.NewEx(&readline.Config{\n\t\tPrompt: prompt,\n\t\tAutoComplete: completer,\n\t\tHistoryFile: filepath.Join(os.TempDir(), historyFile),\n\t\tHistorySearchFold: true,\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error creating readline:\", err)\n\t\treturn\n\t}\n\n\tvar standardReader bool\n\n\tfor {\n\t\tvar line string\n\t\tvar err error\n\n\t\tl.SetPrompt(createPrompt(dt))\n\n\t\tif !standardReader {\n\t\t\tline, err = l.Readline()\n\t\t\tif err != nil {\n\t\t\t\tstandardReader = true\n\t\t\t\tlog.Println(\"Error using readline package: switching to bufio reader: \", err)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Print(prompt)\n\t\t\tline, err = rd.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t// Read a line of input\n\n\t\t// Remove whitespace characters from line\n\t\tline = strings.TrimSpace(line)\n\n\t\terr = executeCommand(dt, line)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func CleanInput(in string) (out io.Reader) {\n\tr := bufio.NewReader(bytes.NewReader([]byte(in)))\n\to := new(bytes.Buffer)\n\tvar buf []byte\n\tvar err error\n\tfor {\n\t\tbuf, _, err = r.ReadLine()\n\t\tif err == io.EOF {\n\t\t\terr = nil\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = o.Write([]byte(strings.TrimSpace(string(buf)) + \"\\n\"))\n\t}\n\tout = bytes.NewReader(o.Bytes())\n\treturn\n}", "func listenWrite(conn net.Conn, done chan bool) {\n readerStdin := bufio.NewReader(os.Stdin)\n\n for {\n // read in input from stdin\n message, err := readerStdin.ReadString('\\n')\n\n // treat \"END\" as a keyword used by the user to terminate the connection\n if message == \"END\\n\" {\n conn.Close()\n done <- true\n break\n }\n\n if err != nil {\n fmt.Println(\"Error reading outgoing message: \", err.Error())\n }\n\n outgoing := encrypt([]byte(message))\n sendOutgoing(conn, outgoing)\n }\n}", "func readLine() string {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\ttext = strings.Replace(text, \"\\n\", \"\", -1)\n\treturn text\n}", "func Prompt(msg string) (string, error) {\n\tif !IsInteractive() {\n\t\treturn \"\", fmt.Errorf(\"not an interactive session\")\n\t}\n\n\tpromptMux.Lock()\n\tdefer promptMux.Unlock()\n\n\tvar v string\n\tfmt.Fprintf(os.Stderr, \"%s: \", msg)\n\t_, err := fmt.Scanln(&v)\n\treturn v, err\n}", "func Prompt(prompt string) (s string, err error) {\n\tfmt.Printf(\"%s\", prompt)\n\tstdin := bufio.NewReader(os.Stdin)\n\tl, _, err := stdin.ReadLine()\n\treturn string(l), err\n}" ]
[ "0.6536337", "0.65160227", "0.6378787", "0.6338915", "0.61996585", "0.6172181", "0.6155437", "0.6152924", "0.61121726", "0.6099486", "0.60795236", "0.60671675", "0.60584617", "0.60556275", "0.6027462", "0.59518105", "0.59339887", "0.59317434", "0.5923238", "0.58978343", "0.58947915", "0.5892359", "0.58892125", "0.5886827", "0.5871687", "0.58625746", "0.5861207", "0.5850321", "0.58499205", "0.58477724", "0.58459616", "0.5845773", "0.5822623", "0.5808193", "0.576161", "0.57273465", "0.56695104", "0.5653082", "0.5614913", "0.5603659", "0.5588148", "0.55826354", "0.5576844", "0.5562665", "0.5561743", "0.5561365", "0.55567557", "0.5493223", "0.54903734", "0.54668164", "0.5442759", "0.54338336", "0.5422481", "0.54019904", "0.5395417", "0.5353552", "0.5314842", "0.53006434", "0.52978307", "0.52957094", "0.52939975", "0.52676505", "0.5265232", "0.52601045", "0.5259739", "0.5258805", "0.5248971", "0.52307814", "0.52240235", "0.52239054", "0.522015", "0.5219818", "0.5210909", "0.5189313", "0.51892483", "0.51838684", "0.51781666", "0.51706773", "0.5160863", "0.51523226", "0.51520014", "0.5151961", "0.5146748", "0.5124286", "0.5119887", "0.51064277", "0.5101016", "0.509858", "0.5084593", "0.5077679", "0.50698", "0.5066645", "0.50656855", "0.5053398", "0.5048999", "0.5034314", "0.5020976", "0.5020312", "0.49927953", "0.49876502" ]
0.71271926
0
fills our return value from makeMsg up to 10 byte.
func fillup(array []byte, endIndex, startIndex int) []byte { for tmp := startIndex; tmp < endIndex; tmp++ { array[tmp] = byte(0) } return array }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}", "func (z NestInner) Msgsize() (s int) {\n\ts = 1 + 6 + msgp.StringPrefixSize + len(z.Hello)\n\treturn\n}", "func allocMsg(t string, length int) (messager, error) {\n\tswitch t {\n\tcase \"msgheader\":\n\t\tvar msg msgHdr\n\t\treturn &msg, nil\n\tcase \"version\":\n\t\tvar msg version\n\t\treturn &msg, nil\n\tcase \"verack\":\n\t\tvar msg verACK\n\t\treturn &msg, nil\n\tcase \"getheaders\":\n\t\tvar msg headersReq\n\t\treturn &msg, nil\n\tcase \"headers\":\n\t\tvar msg blkHeader\n\t\treturn &msg, nil\n\tcase \"getaddr\":\n\t\tvar msg addrReq\n\t\treturn &msg, nil\n\tcase \"addr\":\n\t\tvar msg addr\n\t\treturn &msg, nil\n\tcase \"inv\":\n\t\tvar msg inv\n\t\t// the 1 is the inv type lenght\n\t\tmsg.p.blk = make([]byte, length - MSGHDRLEN - 1)\n\t\treturn &msg, nil\n\tcase \"getdata\":\n\t\tvar msg dataReq\n\t\treturn &msg, nil\n\tcase \"block\":\n\t\tvar msg block\n\t\treturn &msg, nil\n\tcase \"tx\":\n\t\tvar msg trn\n\t\treturn &msg, nil\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func newMessage(c cipher.API, s string) (buf, msg []byte) {\n\treturn make([]byte, 0, len(s)+c.Overhead()), []byte(s)\n}", "func fillMsg(fromAddress address.Address, api *apistruct.FullNodeStruct, msg *types.Message) (*types.SignedMessage, error) {\n\t// Get nonce\n\tnonce, err := api.MpoolGetNonce(context.Background(), msg.From)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.Nonce = nonce\n\n\t// Calculate gas\n\tlimit, err := api.GasEstimateGasLimit(context.Background(), msg, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasLimit = int64(float64(limit) * 1.25)\n\n\tpremium, err := api.GasEstimateGasPremium(context.Background(), 10, msg.From, msg.GasLimit, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasPremium = premium\n\n\tfeeCap, err := api.GasEstimateFeeCap(context.Background(), msg, 20, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasFeeCap = feeCap\n\n\t// Sign message\n\treturn api.WalletSignMessage(context.Background(), fromAddress, msg)\n}", "func (z *MessageControl) Msgsize() (s int) {\n\ts = 1 + 5\n\tif z.Hash == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.Hash.Msgsize()\n\t}\n\treturn\n}", "func newMsg(t string) ([]byte, error) {\n\tswitch t {\n\tcase \"version\":\n\t\treturn newVersion()\n\tcase \"verack\":\n\t\treturn newVerack()\n\tcase \"getheaders\":\n\t\treturn newHeadersReq()\n\tcase \"getaddr\":\n\t\treturn newGetAddr()\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func (z *SendGameFail) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 4 + msgp.StringPrefixSize + len(z.Msg) + 5 + msgp.Int32Size + 5 + msgp.Int32Size\n\treturn\n}", "func (z Int8) Msgsize() (s int) {\n\ts = msgp.Int8Size\n\treturn\n}", "func (z *MessageGetMsg) Msgsize() (s int) {\n\ts = 1 + 5\n\tif z.Hash == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.Hash.Msgsize()\n\t}\n\treturn\n}", "func (z *MessageTermChange) Msgsize() (s int) {\n\ts = 1 + 11\n\tif z.TermChange == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.TermChange.Msgsize()\n\t}\n\treturn\n}", "func (z *MessageNewTxs) Msgsize() (s int) {\n\ts = 1 + z.RawTxs.Msgsize()\n\treturn\n}", "func (z *LoginGameReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 6 + msgp.Int32Size + 5 + msgp.Int32Size + 5 + msgp.StringPrefixSize + len(z.Args)\n\treturn\n}", "func (z ExitGameReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 5 + msgp.Int32Size\n\treturn\n}", "func (z *LoginGameAck) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 5 + msgp.Int32Size + 5 + msgp.Int32Size + 4 + msgp.StringPrefixSize + len(z.Msg)\n\treturn\n}", "func (z *MessagePing) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.BytesPrefixSize + len(z.Data)\n\treturn\n}", "func (z HexBytes) Msgsize() (s int) {\n\ts = msgp.BytesPrefixSize + len([]byte(z))\n\treturn\n}", "func (z ExitGameAck) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 4 + msgp.StringPrefixSize + len(z.Msg)\n\treturn\n}", "func (z String) Msgsize() (s int) {\n\ts = msgp.StringPrefixSize + len(string(z))\n\treturn\n}", "func (z Person) Msgsize() (s int) {\n\ts = 1 + 6 + msgp.StringPrefixSize + len(z.First) + 5 + msgp.StringPrefixSize + len(z.Last)\n\treturn\n}", "func (z *RoomInfo) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.StringPrefixSize + len(z.Name) + 3 + msgp.Int32Size + 5 + msgp.Int32Size + 6 + msgp.Int32Size + 4 + msgp.Int32Size + 5 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.Int64Size + 8 + msgp.StringPrefixSize + len(z.CoinKey) + 5 + msgp.Int32Size + 7 + msgp.Int32Size\n\treturn\n}", "func testPackMessage(length, sequence uint32, v uint8, pad uint16, mType MessageType, message []byte) []byte {\n\tbuf := sbuf.NewBuffer(messageOverhead + len(message))\n\tbuf.WriteByte(v)\n\tbuf.WriteByte(uint8(mType))\n\tbinary.Write(buf, binary.BigEndian, pad)\n\n\t// An sbuf won't fail to write unless it's out of memory, then this\n\t// whole house of cards is coming crashing down anyways.\n\tbinary.Write(buf, binary.BigEndian, sequence)\n\tbinary.Write(buf, binary.BigEndian, length)\n\tbuf.Write(message)\n\treturn buf.Bytes()\n}", "func (z Task) Msgsize() (s int) {\n\ts = 1 + 3 + msgp.Uint32Size + 8 + msgp.StringPrefixSize + len(z.Content) + 6 + msgp.StringPrefixSize + len(z.Token)\n\treturn\n}", "func (z scanStatus) Msgsize() (s int) {\n\ts = msgp.Uint8Size\n\treturn\n}", "func (z *BcastGetReply) Msgsize() (s int) {\n\ts = 1 + 7 + msgp.StringPrefixSize + len(z.FromID) + 3\n\tif z.Ki == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.Ki.Msgsize()\n\t}\n\ts += 4 + msgp.StringPrefixSize + len(z.Err)\n\treturn\n}", "func (z Rune) Msgsize() (s int) {\n\ts = msgp.Int32Size\n\treturn\n}", "func (z *BotRecord) Msgsize() (s int) {\n\ts = 1 + 2 + z.ID.Msgsize() + 2 + z.Addresses.Msgsize() + 2 + z.Names.Msgsize() + 2 + z.PublicKey.Msgsize() + 2 + z.Expiration.Msgsize()\n\treturn\n}", "func (z *MessageSyncResponse) Msgsize() (s int) {\n\ts = 1 + z.RawTxs.Msgsize() + z.RawSequencers.Msgsize() + msgp.Uint32Size\n\treturn\n}", "func (z *ContractService) Msgsize() (s int) {\n\ts = 1 + 3 + msgp.StringPrefixSize + len(z.ServiceId) + 4 + msgp.Uint64Size + 4 + msgp.Uint64Size + 2 + msgp.Uint64Size + 2 + msgp.Float64Size + 2 + msgp.StringPrefixSize + len(z.Currency)\n\treturn\n}", "func makeEmptyMessage(command string) (Message, error) {\n\tvar msg Message\n\tswitch command {\n\tcase cmdVersion:\n\t\tmsg = &MsgVersion{}\n\n\tcase cmdVerAck:\n\t\tmsg = &MsgVerAck{}\n\n\tcase cmdGetAddr:\n\t\tmsg = &MsgGetAddr{}\n\n\tcase cmdAddr:\n\t\tmsg = &MsgAddr{}\n\n\tcase cmdGetBlocks:\n\t\tmsg = &MsgGetBlocks{}\n\n\tcase cmdBlock:\n\t\tmsg = &MsgBlock{}\n\n\tcase cmdInv:\n\t\tmsg = &MsgInv{}\n\n\tcase cmdGetData:\n\t\tmsg = &MsgGetData{}\n\n\tcase cmdNotFound:\n\t\tmsg = &MsgNotFound{}\n\n\tcase cmdTx:\n\t\tmsg = &MsgTx{}\n\n\tcase cmdPing:\n\t\tmsg = &MsgPing{}\n\n\tcase cmdPong:\n\t\tmsg = &MsgPong{}\n\n\tcase cmdGetHeaders:\n\t\tmsg = &MsgGetHeaders{}\n\n\tcase cmdHeaders:\n\t\tmsg = &MsgHeaders{}\n\n\tcase cmdAlert:\n\t\tmsg = &MsgAlert{}\n\n\tcase cmdMemPool:\n\t\tmsg = &MsgMemPool{}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled command [%s]\", command)\n\t}\n\treturn msg, nil\n}", "func (z *TermChange) Msgsize() (s int) {\n\ts = 1 + z.TxBase.Msgsize() + msgp.BytesPrefixSize + len(z.PkBls) + z.Issuer.Msgsize()\n\treturn\n}", "func (z *MessageNewTx) Msgsize() (s int) {\n\ts = 1\n\tif z.RawTx == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.RawTx.Msgsize()\n\t}\n\treturn\n}", "func (z *WalletUnlockedOutput) Msgsize() (s int) {\n\ts = 1 + 2 + z.Amount.Msgsize() + 2 + msgp.StringPrefixSize + len(z.Description)\n\treturn\n}", "func (z Resolution) Msgsize() (s int) {\n\ts = msgp.Int32Size\n\treturn\n}", "func (z RawData) Msgsize() (s int) {\n\ts = msgp.BytesPrefixSize + len([]byte(z))\n\treturn\n}", "func (z Status) Msgsize() (s int) {\n\ts = hsp.Int32Size\n\treturn\n}", "func (z *ZebraUUID) Msgsize() (s int) {\n\ts = msgp.ArrayHeaderSize + (16 * (msgp.ByteSize))\n\treturn\n}", "func (res *response) Marshal(buf []byte) ([]byte, error) {\n\tvar size uint64\n\tsize += 10\n\tsize += 10 + uint64(len(res.Error))\n\tsize += 10 + uint64(len(res.Reply))\n\tif uint64(cap(buf)) >= size {\n\t\tbuf = buf[:size]\n\t} else {\n\t\tbuf = make([]byte, size)\n\t}\n\tvar offset uint64\n\tvar n uint64\n\t//n = code.EncodeVarint(buf[offset:], res.Seq)\n\t{\n\t\tvar t = res.Seq\n\t\tvar size = code.SizeofVarint(t)\n\t\tfor i := uint64(0); i < size-1; i++ {\n\t\t\tbuf[offset+i] = byte(t) | 0x80\n\t\t\tt >>= 7\n\t\t}\n\t\tbuf[offset+size-1] = byte(t)\n\t\tn = size\n\t}\n\toffset += n\n\t//n = code.EncodeString(buf[offset:], res.Error)\n\tif len(res.Error) > 127 {\n\t\tvar length = uint64(len(res.Error))\n\t\tvar lengthSize = code.SizeofVarint(length)\n\t\tvar s = lengthSize + length\n\t\tt := length\n\t\tfor i := uint64(0); i < lengthSize-1; i++ {\n\t\t\tbuf[offset+i] = byte(t) | 0x80\n\t\t\tt >>= 7\n\t\t}\n\t\tbuf[offset+lengthSize-1] = byte(t)\n\t\tcopy(buf[offset+lengthSize:], res.Error)\n\t\tn = s\n\t} else if len(res.Error) > 0 {\n\t\tvar length = uint64(len(res.Error))\n\t\tbuf[offset] = byte(length)\n\t\tcopy(buf[offset+1:], res.Error)\n\t\tn = 1 + length\n\t} else {\n\t\tbuf[offset] = 0\n\t\tn = 1\n\t}\n\toffset += n\n\t//n = code.EncodeBytes(buf[offset:], res.Reply)\n\tif len(res.Reply) > 127 {\n\t\tvar length = uint64(len(res.Reply))\n\t\tvar lengthSize = code.SizeofVarint(length)\n\t\tvar s = lengthSize + length\n\t\tt := length\n\t\tfor i := uint64(0); i < lengthSize-1; i++ {\n\t\t\tbuf[offset+i] = byte(t) | 0x80\n\t\t\tt >>= 7\n\t\t}\n\t\tbuf[offset+lengthSize-1] = byte(t)\n\t\tcopy(buf[offset+lengthSize:], res.Reply)\n\t\tn = s\n\t} else if len(res.Reply) > 0 {\n\t\tvar length = uint64(len(res.Reply))\n\t\tbuf[offset] = byte(length)\n\t\tcopy(buf[offset+1:], res.Reply)\n\t\tn = 1 + length\n\t} else {\n\t\tbuf[offset] = 0\n\t\tn = 1\n\t}\n\toffset += n\n\treturn buf[:offset], nil\n}", "func (z Byte) Msgsize() (s int) {\n\ts = msgp.ByteSize\n\treturn\n}", "func (z *WalletLockedOutput) Msgsize() (s int) {\n\ts = 1 + 2 + z.Amount.Msgsize() + 3 + z.LockedUntil.Msgsize() + 2 + msgp.StringPrefixSize + len(z.Description)\n\treturn\n}", "func fillmsgall(evto *thspbs.Event) {\n\tfor len(evto.Args) < 10 {\n\t\tevto.Args = append(evto.Args, \"\")\n\t}\n\tfor len(evto.Margs) < 10 {\n\t\tevto.Margs = append(evto.Margs, \"\")\n\t}\n}", "func (z *MessageCampaign) Msgsize() (s int) {\n\ts = 1 + 9\n\tif z.Campaign == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.Campaign.Msgsize()\n\t}\n\treturn\n}", "func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func (z Int) Msgsize() (s int) {\n\ts = msgp.IntSize\n\treturn\n}", "func getTenResults(whatPageNum int, whatBoard string) ([]Message, bool) {\n\tgiveMessages := []Message{} //The messages to return, based on what page number we are\n\tminResult := ((whatPageNum * 10) - 10) + 1 //First result to add to map\n\tokayResult := true //The result returned if we have messages to return\n\n\tswitch whatBoard {\n\tcase \"hotdog\":\n\t\t/* Get the highest count of messages in an array from our message board */\n\t\togMessageArrayLength := len(theMessageBoardHDog.AllOriginalMessages)\n\t\tstart := ogMessageArrayLength - (whatPageNum * 10)\n\t\t//Initial check to see if this message exists in our map\n\t\tif _, ok := loadedMessagesMapHDog[minResult]; ok {\n\t\t\tfor g := start; g <= start+10; g++ {\n\t\t\t\t//if the message exists, add it\n\t\t\t\tif _, ok := loadedMessagesMapHDog[g]; ok {\n\t\t\t\t\tgiveMessages = append([]Message{loadedMessagesMapHDog[g]}, giveMessages...)\n\t\t\t\t} else {\n\t\t\t\t\t//Do nothing, message does not exist\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"DEBUG: Page value does not exist! The Value: %v\\n\", minResult)\n\t\t\tfmt.Printf(\"DEBUG: Here is our map currently: \\n\\n%v\\n\\n\", loadedMessagesMapHDog)\n\t\t\tokayResult = false\n\t\t}\n\t\tbreak\n\tcase \"hamburger\":\n\t\t/* Get the highest count of messages in an array from our message board */\n\t\togMessageArrayLength := len(theMessageBoardHam.AllOriginalMessages)\n\t\tstart := ogMessageArrayLength - (whatPageNum * 10)\n\t\t//Initial check to see if this message exists in our map\n\t\tif _, ok := loadedMessagesMapHam[minResult]; ok {\n\t\t\tfor g := start; g <= start+10; g++ {\n\t\t\t\t//if the message exists, add it\n\t\t\t\tif _, ok := loadedMessagesMapHam[g]; ok {\n\t\t\t\t\tgiveMessages = append([]Message{loadedMessagesMapHam[g]}, giveMessages...)\n\t\t\t\t} else {\n\t\t\t\t\t//Do nothing, message does not exist\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"DEBUG: Page value does not exist! The Value: %v\\n\", minResult)\n\t\t\tfmt.Printf(\"DEBUG: Here is our map currently: \\n\\n%v\\n\\n\", loadedMessagesMapHam)\n\t\t\tokayResult = false\n\t\t}\n\t\tbreak\n\tdefault:\n\t\ttheMessage := \"Error, wrong board entered: \" + whatBoard\n\t\tlogWriter(theMessage)\n\t\tfmt.Printf(\"DEBUG: %v\\n\", theMessage)\n\t\tokayResult = false\n\t\tbreak\n\t}\n\n\treturn giveMessages, okayResult\n}", "func (z GameKindReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size\n\treturn\n}", "func (z *ZebraData) Msgsize() (s int) {\n\ts = 1 + 7 + msgp.ArrayHeaderSize + (16 * (msgp.ByteSize)) + 9 + msgp.StringPrefixSize + len(z.Username) + 5 + msgp.StringPrefixSize + len(z.Note)\n\treturn\n}", "func (z *KeyInv) Msgsize() (s int) {\n\ts = 1 + 4 + msgp.BytesPrefixSize + len(z.Key) + 4 + msgp.StringPrefixSize + len(z.Who) + 5 + msgp.TimeSize + 5 + msgp.Int64Size + 8 + msgp.BytesPrefixSize + len(z.Blake2b) + 4 + msgp.BytesPrefixSize + len(z.Val)\n\treturn\n}", "func (message *Message) str() []byte {\n\n\tmessage.MsgType = norStrMsg\n\n\treturn message.generateByte()\n}", "func (z *Weather) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.TimeSize + 5 + msgp.Int64Size + 5 + msgp.StringPrefixSize + len(z.Type) + 8 + msgp.BytesPrefixSize + len(z.Details)\n\treturn\n}", "func (z ContractStatus) Msgsize() (s int) {\n\ts = msgp.IntSize\n\treturn\n}", "func fillString(retunString string, toLength int) string {\n\tfor {\n\t\tlengtString := len(retunString)\n\t\tif lengtString < toLength {\n\t\t\tretunString = retunString + \":\"\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn retunString\n}", "func fillString(retunString string, toLength int) string {\n\tfor {\n\t\tlengtString := len(retunString)\n\t\tif lengtString < toLength {\n\t\t\tretunString = retunString + \":\"\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn retunString\n}", "func fillString(retunString string, toLength int) string {\n\tfor {\n\t\tlengtString := len(retunString)\n\t\tif lengtString < toLength {\n\t\t\tretunString = retunString + \":\"\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn retunString\n}", "func (z Bytes) Msgsize() (s int) {\n\ts = msgp.BytesPrefixSize + len([]byte(z))\n\treturn\n}", "func CompletePackage(msg []byte, data_len int) int {\n //fmt.Println(\"data_len\", data_len)\n if data_len <= 8 {\n return 0\n }\n /*\n magic_byte:= msg[0:4]\n magic_num := binary.BigEndian.Uint32(magic_byte)\n if magic_num != MAGIC_NUM {\n return -1\n } \n */\n\n len_byte := msg[4:8]\n parse_len := binary.BigEndian.Uint32(len_byte)\n \n if int(parse_len) <= data_len {\n return int(parse_len)\n }\n return -1\n}", "func (z *MessageBodyData) Msgsize() (s int) {\n\ts = 1 + 7 + z.RawTxs.Msgsize() + 13\n\tif z.RawSequencer == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.RawSequencer.Msgsize()\n\t}\n\treturn\n}", "func (z *UserArrears) Msgsize() (s int) {\n\ts = 1 + 8 + hsp.Uint64Size + 5 + z.User.Msgsize()\n\treturn\n}", "func (z RegistRequest) Msgsize() (s int) {\n\ts = 1 + 4 + msgp.Uint32Size + 5 + msgp.StringPrefixSize + len(z.Name) + 8 + msgp.StringPrefixSize + len(z.Version)\n\treturn\n}", "func (z *MessageHeaderResponse) Msgsize() (s int) {\n\ts = 1 + z.Headers.Msgsize() + msgp.Uint32Size\n\treturn\n}", "func (z *QueryAsTx) Msgsize() (s int) {\n\ts = 1 + 8\n\tif z.Request == nil {\n\t\ts += hsp.NilSize\n\t} else {\n\t\ts += z.Request.Msgsize()\n\t}\n\ts += 9\n\tif z.Response == nil {\n\t\ts += hsp.NilSize\n\t} else {\n\t\ts += z.Response.Msgsize()\n\t}\n\treturn\n}", "func (ce *mySpiderError) genFullErrMsg() {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Spider Error:\")\n\tif ce.errType != \"\" {\n\t\tbuffer.WriteString(string(ce.errType))\n\t\tbuffer.WriteString(\": \")\n\t}\n\tbuffer.WriteString(ce.errMsg)\n\n\tce.fullErrMsg = fmt.Sprintf(\"%s\\n\", buffer.String())\n}", "func (msg *MsgReturnInit) MaxPayloadLength(pver uint32) uint32 {\n\treturn MaxReturnedMsgsPayload\n}", "func (z Terminator) Msgsize() (s int) {\n\ts = 1 + 2 + msgp.ExtensionPrefixSize + z.Address.Len() + 2 + msgp.BoolSize\n\treturn\n}", "func (z TxBaseType) Msgsize() (s int) {\n\ts = msgp.Uint16Size\n\treturn\n}", "func (self *EV3Message) getBytes() []byte {\n\tself.commandSize = uint16(len(self.byteCodes)) + EV3MessageHeaderSize - 2 // 2 means commandSize = uint16 that should not be counted\n\tbuf := make([]byte, EV3MessageHeaderSize)\n\tbinary.LittleEndian.PutUint16(buf[0:], self.commandSize)\n\tbinary.LittleEndian.PutUint16(buf[2:], self.messageCount)\n\tbuf[4] = self.commandType\n\tbinary.LittleEndian.PutUint16(buf[5:], self.variablesReservation)\n\tbuf = append(buf, self.byteCodes...)\n\treturn buf\n}", "func (z *TokenInfo) Msgsize() (s int) {\n\ts = 1 + z.PublicOffering.Msgsize() + z.Sender.Msgsize()\n\tif z.CurrentValue == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.CurrentValue.Msgsize()\n\t}\n\ts += msgp.BoolSize\n\treturn\n}", "func terr(msg string) []byte {\n\tfmt.Printf(\"ERROR: %s\\n\", msg)\n\tvar b bytes.Buffer\n\tb.Grow(len(msg) + 5)\n\tb.Write([]byte{0, 5, 0, 0})\n\tb.Write([]byte(msg))\n\tb.Write([]byte{0})\n\treturn b.Bytes()\n}", "func (z *RootRaw) Msgsize() (s int) {\n\ts = 1 + 5 + z.Size.Msgsize() + 12 + z.BucketCount.Msgsize() + 11 + z.SplitIndex.Msgsize() + 9 + z.MaskHigh.Msgsize() + 8 + z.MaskLow.Msgsize() + 8 + msgp.BytesPrefixSize + len(z.HashKey)\n\treturn\n}", "func (z Int64) Msgsize() (s int) {\n\ts = msgp.Int64Size\n\treturn\n}", "func (z Uint8) Msgsize() (s int) {\n\ts = msgp.Uint8Size\n\treturn\n}", "func (z *SQLChainUser) Msgsize() (s int) {\n\ts = 1 + 8 + z.Address.Msgsize() + 15 + hsp.Uint64Size + 8 + hsp.Uint64Size + 8 + hsp.Uint64Size + 11\n\tif z.Permission == nil {\n\t\ts += hsp.NilSize\n\t} else {\n\t\ts += 1 + 5 + hsp.Int32Size + 9 + hsp.ArrayHeaderSize\n\t\tfor za0001 := range z.Permission.Patterns {\n\t\t\ts += hsp.StringPrefixSize + len(z.Permission.Patterns[za0001])\n\t\t}\n\t}\n\ts += 7 + hsp.Int32Size\n\treturn\n}", "func (z Position) Msgsize() (s int) {\n\ts = 1 + 6 + msgp.Uint16Size + 7 + msgp.Uint16Size\n\treturn\n}", "func (z *WalletLockedBalance) Msgsize() (s int) {\n\ts = 1 + 2 + z.Total.Msgsize() + 2 + z.Outputs.Msgsize()\n\treturn\n}", "func (z *BcastGetRequest) Msgsize() (s int) {\n\ts = 1 + 7 + msgp.StringPrefixSize + len(z.FromID) + 4 + msgp.BytesPrefixSize + len(z.Key) + 4 + msgp.StringPrefixSize + len(z.Who) + 13 + msgp.BoolSize + 14 + msgp.StringPrefixSize + len(z.ReplyGrpcHost) + 15 + msgp.IntSize + 15 + msgp.IntSize\n\treturn\n}", "func (z Int32) Msgsize() (s int) {\n\ts = msgp.Int32Size\n\treturn\n}", "func (z *MessageTxsResponse) Msgsize() (s int) {\n\ts = 1 + z.RawTxs.Msgsize()\n\tif z.RawSequencer == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.RawSequencer.Msgsize()\n\t}\n\ts += msgp.Uint32Size\n\treturn\n}", "func (z BcastSetReply) Msgsize() (s int) {\n\ts = 1 + 4 + msgp.StringPrefixSize + len(z.Err)\n\treturn\n}", "func MsgPrepare(common Common, tx *Transfer) base.Message {\n\tif tx.MessageType == 2 && common.PrivateKey != \"\" {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: \"\",\n\t\t}\n\t} else if tx.MessageType == 2 && common.IsHW {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t\tPublicKey: tx.RecipientPublicKey,\n\t\t}\n\n\t} else if tx.MessageType == 0 && utils.IsHexadecimal(tx.Message) {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: \"fe\" + tx.Message,\n\t\t}\n\t} else {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t}\n\t}\n}", "func createFormat(message string) big.Int {\n\t//*Takes as input the message that the user has typed in.\n\t//*Creates a correctly padded message block, given some message.\n\t//*Return the decimal version of the correctly padded message block.\n\tfmt.Println(\"########################################################################---CREATING FORMAT---########################################################################\")\n\tfmt.Println(\"\")\n\tvar padding string\n\n\tzeroTwoAsString := []byte{0x00, 0x02} //Sets the two first bytes in the padding format to \"00\" and \"02\".\n\tzeroAsString := []byte{0x00} //Sets the seperator byte in the padding format to \"00\".\n\tencodedStr := hex.EncodeToString([]byte(zeroTwoAsString)) //Encodes the \"00\" and \"02\" bytes into a hex string.\n\tencodedzeroStr := hex.EncodeToString([]byte(zeroAsString)) //Encodes the seporator byte \"00\" into a hex string.\n\tencodedmessage := hex.EncodeToString([]byte(message)) //Encodes the message into a hex string\n\tmesLength := len(encodedmessage) //Sets the length of the message.\n\n\tpadToAdd := keyLengthInt - mesLength - 6 //Calculate how much padding is needed.\n\tfmt.Println(\"Padding to add: \" + strconv.Itoa(padToAdd))\n\tpadding = RandomString(padToAdd) //Creates the random padding using the RandomString method with\n\t//the amount from the above line.\n\tpkcsStr := encodedStr + padding + encodedzeroStr + encodedmessage //Construct a full message block such as: \"00|02|padding|00|message\"\n\n\tfmt.Println(\"Message block: \" + pkcsStr)\n\tstartMessageBlock = pkcsStr\n\thex2intEncode := HexToDec(pkcsStr) //Convert this message block from hexadecimal to decimal.\n\treturn hex2intEncode\n}", "func appendMessage(startpos int, msg *Message) (int, Burst) {\n\t// expand the parameters of the message\n\taddr := msg.Addr\n\tfunction := byte(msg.Function)\n\ttype_ := 'a'\n\tcontent := msg.Content\n\n\tdebugf(\"append_message: addr %d function %d type %d content %s\", addr, function, type_, content)\n\n\t// the starting frame is selected based on the three least significant bits\n\tframeAddr := addr & 7\n\tframeAddrCw := frameAddr * 2 // or << 2 ?\n\n\tdebugf(\" frame_addr is %d, current position %d\", frameAddr, startpos)\n\n\t// append idle codewords, until we're in the right frame for this address\n\ttx := make(Burst, 0)\n\tpos := 0\n\tfor uint32(startpos+pos)%16 != frameAddrCw {\n\t\tdebugf(\" inserting IDLE codewords in position %d (%d)\", startpos+pos, (startpos+pos)%16)\n\t\ttx = append(tx, pocsagIdleWord)\n\t\tpos++\n\t}\n\n\t// Then, append the address codeword, containing the function and the address\n\t// (sans 3 least significant bits, which are indicated by the starting frame,\n\t// which the receiver is waiting for)\n\ttx = append(tx, addressCodeword(addr, function))\n\tpos++\n\n\t// Next, append the message contents\n\tvar contentEncLen int\n\tvar contentEnc Burst\n\tif msg.IsNumeric {\n\t\tcontentEncLen, contentEnc = appendContentNumeric(content)\n\t} else {\n\t\tcontentEncLen, contentEnc = appendContentText(content)\n\t}\n\n\ttx = append(tx, contentEnc...)\n\tpos += contentEncLen\n\n\t// Return the current frame position and the binary string to be appended\n\treturn pos, tx\n}", "func (z *InsertQuery) Msgsize() (s int) {\n\ts = 1 + 8\n\tif z.Actions == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += msgp.BoolSize\n\t}\n\ts += 7\n\tif z.Method == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += msgp.StringPrefixSize + len(*z.Method)\n\t}\n\treturn\n}", "func (z SQLChainRole) Msgsize() (s int) {\n\ts = hsp.ByteSize\n\treturn\n}", "func (z MessageDuplicate) Msgsize() (s int) {\n\ts = msgp.BoolSize\n\treturn\n}", "func (z *Account) Msgsize() (s int) {\n\ts = 1 + 8 + z.Address.Msgsize() + 10 + z.NextNonce.Msgsize() + 7 + hsp.Float64Size + 13 + hsp.ArrayHeaderSize + (int(SupportTokenNumber) * (hsp.Uint64Size))\n\treturn\n}", "func (z *CreateContractParam) Msgsize() (s int) {\n\ts = 1 + 3 + z.PartyA.Msgsize() + 3 + z.PartyB.Msgsize() + 4 + msgp.ExtensionPrefixSize + z.Previous.Len() + 2 + msgp.ArrayHeaderSize\n\tfor za0001 := range z.Services {\n\t\ts += z.Services[za0001].Msgsize()\n\t}\n\ts += 3 + msgp.Int64Size + 3 + msgp.Int64Size + 3 + msgp.Int64Size\n\treturn\n}", "func (z *ResultNode) Msgsize() (s int) {\n\ts = 1 + 4 + 1 + 6 + msgp.Uint16Size + 7 + msgp.Uint16Size\n\treturn\n}", "func (LP72 LongPoll72OutBound) BuildAndByte(params ...interface{}) ([]byte, error) {\n\n\tcashableMoneyInCents := params[0].(uint64)\n\trestrictedMoneyInCents := params[1].(uint64)\n\tnonRestrictedMoneyInCents := params[2].(uint64)\n\n\tbinAssetNo := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(binAssetNo, AssetNumber)\n\n\tLP72.Address = 0x01\n\tLP72.Command = 0x72\n\tLP72.TransferCode = 0x00\n\tLP72.TransactionIndex = 0x00\n\tLP72.CashableBCD = bcd.FromUint(cashableMoneyInCents, 5)\n\tLP72.RestrictedBCD = bcd.FromUint(restrictedMoneyInCents, 5)\n\tLP72.NonRestrictedBCD = bcd.FromUint(nonRestrictedMoneyInCents, 5)\n\tLP72.TransferFlags = 0x00\n\tLP72.AssetNumber = binAssetNo\n\tLP72.RegistrationKey = RegistrationKey\n\tLP72.Expiration = []byte{0x01, 0x01, 0x20, 0x25}\n\tLP72.PoolID = []byte{0x00, 0x00}\n\tLP72.ReceiptDataLength = 0x00\n\tLP72.LockTimeout = []byte{0x44, 0xCD}\n\n\tdate := jodaTime.Format(\"YYYYMMddHHmmssSSS\", time.Now())\n\n\tLP72.TransactionID = []byte(date)\n\tLP72.TransactionIDLength = byte(len(LP72.TransactionID))\n\n\tif params[3].(uint64) != 0 {\n\t\tLP72.TransferType = 0x80\n\t} else {\n\t\tLP72.TransferType = 0x00\n\t}\n\n\tmessageLen := (1 + 1 + 1 + 5 + 5 + 5 + 1 + 4 + 20 + 1 + len(LP72.TransactionID) + 4 + 2 + 1 + 2)\n\tLP72.Length = byte(messageLen)\n\n\tmessageData := []byte{\n\t\tLP72.Address,\n\t\tLP72.Command,\n\t\tLP72.Length,\n\t\tLP72.TransferCode,\n\t\tLP72.TransactionIndex,\n\t\tLP72.TransferType,\n\t}\n\tmessageData = append(messageData, LP72.CashableBCD...)\n\tmessageData = append(messageData, LP72.RestrictedBCD...)\n\tmessageData = append(messageData, LP72.NonRestrictedBCD...)\n\tmessageData = append(messageData, LP72.TransferFlags)\n\tmessageData = append(messageData, LP72.AssetNumber...)\n\tmessageData = append(messageData, LP72.RegistrationKey...)\n\tmessageData = append(messageData, LP72.TransactionIDLength)\n\tmessageData = append(messageData, LP72.TransactionID...)\n\tmessageData = append(messageData, LP72.Expiration...)\n\tmessageData = append(messageData, LP72.PoolID...)\n\tmessageData = append(messageData, LP72.ReceiptDataLength)\n\tmessageData = append(messageData, LP72.LockTimeout...)\n\n\tcrc := CalculateCRC(0, messageData)\n\n\tmessageData = append(messageData, crc...)\n\treturn messageData, nil\n\n}", "func (z *EAIFee) Msgsize() (s int) {\n\ts = 1 + 4 + z.Fee.Msgsize() + 3\n\tif z.To == nil {\n\t\ts += msgp.NilSize\n\t} else {\n\t\ts += z.To.Msgsize()\n\t}\n\treturn\n}", "func (z *GameKindAck) Msgsize() (s int) {\n\ts = 1 + 6 + msgp.ArrayHeaderSize\n\tfor za0001 := range z.Rooms {\n\t\tif z.Rooms[za0001] == nil {\n\t\t\ts += msgp.NilSize\n\t\t} else {\n\t\t\ts += z.Rooms[za0001].Msgsize()\n\t\t}\n\t}\n\treturn\n}", "func (z RawRenderItems) Msgsize() (s int) {\n\ts = msgp.ArrayHeaderSize\n\tfor zkgt := range z {\n\t\tif z[zkgt] == nil {\n\t\t\ts += msgp.NilSize\n\t\t} else {\n\t\t\ts += z[zkgt].Msgsize()\n\t\t}\n\t}\n\treturn\n}", "func (z *metacache) Msgsize() (s int) {\n\ts = 1 + 3 + msgp.StringPrefixSize + len(z.id) + 2 + msgp.StringPrefixSize + len(z.bucket) + 5 + msgp.StringPrefixSize + len(z.root) + 4 + msgp.BoolSize + 4 + msgp.StringPrefixSize + len(z.filter) + 5 + msgp.Uint8Size + 4 + msgp.BoolSize + 4 + msgp.StringPrefixSize + len(z.error) + 3 + msgp.TimeSize + 4 + msgp.TimeSize + 2 + msgp.TimeSize + 3 + msgp.TimeSize + 2 + msgp.Uint8Size\n\treturn\n}", "func (cc *ContinueCompress) MsgLen() int {\n\treturn cc.msgLen\n}", "func (z bucketMetadata) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.StringPrefixSize + len(z.Name) + 8 + msgp.TimeSize + 12 + msgp.BoolSize\n\treturn\n}", "func MsgGet(rw http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tret = InternalErr\n\t\tresult = make(map[string]interface{})\n\t)\n\n\t// Final ResponseWriter operation\n\tdefer func() {\n\t\tresult[\"ret\"] = ret\n\t\tresult[\"msg\"] = GetErrMsg(ret)\n\t\tdate, _ := json.Marshal(result)\n\n\t\tLog.Info(\"request:Get messages, ret:%d\", ret)\n\n\t\tio.WriteString(rw, string(date))\n\t}()\n\n\tif r.Method != \"GET\" {\n\t\thttp.Error(rw, \"Method Not Allowed\", 405)\n\t}\n\n\t// Get params\n\tLog.Debug(\"request_url:%s\", r.URL.String())\n\tval := r.URL.Query()\n\tkey := val.Get(\"key\")\n\tmid := val.Get(\"mid\")\n\tif key == \"\" || mid == \"\" {\n\t\tret = ParamErr\n\t\treturn\n\t}\n\n\tmidI, err := strconv.ParseInt(mid, 10, 64)\n\tif err != nil {\n\t\tret = ParamErr\n\t\treturn\n\t}\n\n\t// Get all of offline messages which larger than midI\n\tmsgs, err := GetMessages(key, midI)\n\tif err != nil {\n\t\tLog.Error(\"get messages error (%v)\", err)\n\t\tret = InternalErr\n\t\treturn\n\t}\n\n\tnumMsg := len(msgs)\n\tif len(msgs) == 0 {\n\t\tret = OK\n\t\treturn\n\t}\n\n\tvar (\n\t\tdata []string\n\t\tmsg = &Message{}\n\t)\n\n\t// Checkout expired offline messages\n\tfor i := 0; i < numMsg; i++ {\n\t\tif err := json.Unmarshal([]byte(msgs[i]), &msg); err != nil {\n\t\t\tLog.Error(\"internal message:%s error (%v)\", msgs[i], err)\n\t\t\tret = InternalErr\n\t\t\treturn\n\t\t}\n\n\t\tif time.Now().UnixNano() > msg.Expire {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata = append(data, msgs[i])\n\t}\n\n\tif len(data) == 0 {\n\t\tret = OK\n\t\treturn\n\t}\n\n\tresult[\"data\"] = data\n\tret = OK\n\treturn\n}", "func Encode(msg MessageTemp) string{\n var r = make([]string,15)\n i := 0\n r[i] = \"35=\"+msg.order_type\n i++\n if msg.order_type==\"trade\"{\n r[i] = fmt.Sprintf(\"44=%d\", msg.price)\n i++\n r[i] = fmt.Sprintf(\"11=%d\", msg.stock_id)\n i++\n r[i] = fmt.Sprintf(\"38=%d\", msg.quantity)\n i++\n if msg.trade_type == \"buy\"{\n r[i] = \"54=1\"\n i++\n } else if msg.trade_type == \"sell\"{\n r[i] = \"54=2\"\n i++\n }\n } else if msg.order_type==\"user\"{\n r[i] = \"5001=\"+msg.username\n i++\n r[i] = \"5002=\"+msg.password\n i++\n }\n\n var result string\n for ;i>=0;i--{\n result += r[i] + \";\"\n }\n //fmt.Println(result)\n return result\n}", "func QueryChainLengthMsg() *Message {\n\treturn &Message{MsgTypeQueryLatest, []Block{}}\n}", "func TestBigMessage(t *testing.T) {\n\tda := NewFrameOutputBuffer()\n\n\td := &model.Device{DeviceEUI: makeRandomEUI(), DevAddr: makeRandomDevAddr()}\n\tbuffer := make([]byte, 255)\n\tif n, err := rand.Read(buffer); n != len(buffer) || err != nil {\n\t\tt.Fatal(\"Couldn't generate random numbers\")\n\t}\n\n\tda.SetPayload(d.DeviceEUI, buffer, 12, false)\n\tda.AddMACCommand(d.DeviceEUI, &protocol.MACLinkADRReq{})\n\n\t// Retrieve the messages until there's no more\n\tvar returnedMacs []protocol.MACCommand\n\tvar returnedBuffer []byte\n\n\tvar err error\n\tvar ret protocol.PHYPayload\n\titerations := 0\n\tfor err == nil {\n\t\tret, err = da.GetPHYPayloadForDevice(d, &context)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif iterations > 999 {\n\t\t\tt.Errorf(\"Breaking after %d iterations\", iterations)\n\t\t\tbreak\n\t\t}\n\t\titerations++\n\t\treturnedMacs = append(returnedMacs, ret.MACPayload.MACCommands.List()...)\n\t\treturnedMacs = append(returnedMacs, ret.MACPayload.FHDR.FOpts.List()...)\n\t\treturnedBuffer = append(returnedBuffer, ret.MACPayload.FRMPayload...)\n\t}\n\tif iterations == 0 {\n\t\tt.Fatalf(\"Didn't get anything at all, err = %s\", err)\n\t}\n\tif !bytes.Equal(buffer, returnedBuffer) {\n\t\tt.Fatalf(\"Mismatch on returned buffer (orig len=%d, returned len=%d)\", len(buffer), len(returnedBuffer))\n\t}\n}", "func (z *UserPermission) Msgsize() (s int) {\n\ts = 1 + 9 + hsp.ArrayHeaderSize\n\tfor za0001 := range z.Patterns {\n\t\ts += hsp.StringPrefixSize + len(z.Patterns[za0001])\n\t}\n\ts += 5 + hsp.Int32Size\n\treturn\n}", "func (z *TxBaseJson) Msgsize() (s int) {\n\ts = 1 + msgp.Uint16Size + z.Hash.Msgsize() + z.ParentsHash.Msgsize() + msgp.Uint64Size + msgp.Uint64Size + z.PublicKey.Msgsize() + z.Signature.Msgsize() + msgp.Uint64Size + msgp.Uint64Size + msgp.ByteSize\n\treturn\n}", "func generatePayload(size int, message string) []byte {\n\tvar payload []byte\n\tif size > len(message) {\n\t\tpayload = make([]byte, size-len(message))\n\t\tpayload = append([]byte(message), payload...)\n\t} else {\n\t\tpayload = []byte(message)\n\t}\n\treturn payload\n}" ]
[ "0.62804025", "0.5524537", "0.5503694", "0.536583", "0.5355071", "0.528174", "0.527688", "0.52213", "0.5175756", "0.5156568", "0.514852", "0.51458406", "0.5132084", "0.5126586", "0.51242393", "0.51024973", "0.51014316", "0.5098779", "0.50937325", "0.5093115", "0.50910634", "0.50907403", "0.50786036", "0.5073983", "0.5056823", "0.50514555", "0.50377315", "0.50235677", "0.500551", "0.49971864", "0.499195", "0.49896696", "0.4979463", "0.49742416", "0.4970462", "0.49698076", "0.4959936", "0.49585328", "0.4951716", "0.49477544", "0.49410233", "0.49328017", "0.4930247", "0.4922104", "0.49221012", "0.49135056", "0.4912021", "0.49109468", "0.490268", "0.49008715", "0.49006486", "0.4900444", "0.4900444", "0.4900444", "0.4890469", "0.48890573", "0.4888074", "0.48795372", "0.4879234", "0.4858745", "0.4852226", "0.48478627", "0.48451197", "0.48450333", "0.4842304", "0.48404345", "0.48366538", "0.4835556", "0.48349956", "0.48273858", "0.48239392", "0.48224884", "0.48198193", "0.48106125", "0.4809578", "0.4806942", "0.47760838", "0.47749117", "0.4773298", "0.47683525", "0.47656447", "0.4764522", "0.47641018", "0.47618577", "0.47582126", "0.47564876", "0.47550026", "0.4743862", "0.47373378", "0.47352383", "0.47247547", "0.47069818", "0.47029555", "0.4702732", "0.47018245", "0.46985632", "0.4697911", "0.46899658", "0.46884388", "0.46879634", "0.4684543" ]
0.0
-1
makeMsg takes opt code for what we want to send and a msg return value will always be 10 bytes
func makeMsg(opt int, msg string) []byte { msg = strings.TrimSpace(msg) //remove space from input var res = make([]byte, 10) //return array variable for what to send back to srv res[0] = byte(opt) //opt code will always be on index zero switch opt { case 2 : //Withdrawl if len(msg) > 9 { //cant whithdrawl amounts more than length 9, break } //convert input msg to bytes, each byte gets its own index in res for index := range msg { res[index+1] = byte(msg[index]) } //if msg was less then 9 we fill upp the rest so we always send 10 bytes res = fillup(res, len(msg)+1, 10) case 3 : //deposit does same as case 2 if len(msg) > 9 { break } for index := range msg { res[index+1] = byte(msg[index]) } res = fillup(res, len(msg) +1, 10) case 100 : //cardnumber if len(msg) != 16 { //cardnumber must be 16 digits break } //each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255 res[1] = byte(stringToInt(msg[0:2])) res[2] = byte(stringToInt(msg[2:4])) res[3] = byte(stringToInt(msg[4:6])) res[4] = byte(stringToInt(msg[6:8])) res[5] = byte(stringToInt(msg[8:10])) res[6] = byte(stringToInt(msg[10:12])) res[7] = byte(stringToInt(msg[12:14])) res[8] = byte(stringToInt(msg[14:16])) res = fillup(res, 9,10) case 101 : //password if len(msg) != 4 { //password must be length 4 break } //each digit in the password converts to bytes into res res[1] = byte(stringToInt(msg[0:1])) res[2] = byte(stringToInt(msg[1:2])) res[3] = byte(stringToInt(msg[2:3])) res[4] = byte(stringToInt(msg[3:4])) res = fillup(res, 5, 10) case 103 : //engångs koderna must be length 2 if len(msg) != 2 { break } res[1] = byte(msg[0]) res[2] = byte(msg[1]) res= fillup(res, 3, 10) } return res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func allocMsg(t string, length int) (messager, error) {\n\tswitch t {\n\tcase \"msgheader\":\n\t\tvar msg msgHdr\n\t\treturn &msg, nil\n\tcase \"version\":\n\t\tvar msg version\n\t\treturn &msg, nil\n\tcase \"verack\":\n\t\tvar msg verACK\n\t\treturn &msg, nil\n\tcase \"getheaders\":\n\t\tvar msg headersReq\n\t\treturn &msg, nil\n\tcase \"headers\":\n\t\tvar msg blkHeader\n\t\treturn &msg, nil\n\tcase \"getaddr\":\n\t\tvar msg addrReq\n\t\treturn &msg, nil\n\tcase \"addr\":\n\t\tvar msg addr\n\t\treturn &msg, nil\n\tcase \"inv\":\n\t\tvar msg inv\n\t\t// the 1 is the inv type lenght\n\t\tmsg.p.blk = make([]byte, length - MSGHDRLEN - 1)\n\t\treturn &msg, nil\n\tcase \"getdata\":\n\t\tvar msg dataReq\n\t\treturn &msg, nil\n\tcase \"block\":\n\t\tvar msg block\n\t\treturn &msg, nil\n\tcase \"tx\":\n\t\tvar msg trn\n\t\treturn &msg, nil\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func newMsg(t string) ([]byte, error) {\n\tswitch t {\n\tcase \"version\":\n\t\treturn newVersion()\n\tcase \"verack\":\n\t\treturn newVerack()\n\tcase \"getheaders\":\n\t\treturn newHeadersReq()\n\tcase \"getaddr\":\n\t\treturn newGetAddr()\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func (a *Asock) genMsg(conn, req uint, code, ml int, txt string, err error) {\n\t// if this message's level is below the instance's level, don't\n\t// generate the message\n\tif ml < a.ml {\n\t\treturn\n\t}\n\tselect {\n\tcase a.Msgr <- &Msg{conn, req, code, txt, err}:\n\tdefault:\n\t}\n}", "func sendMsg(useBase bool, baseCmd byte, cmd byte, msg proto.Message, conn *UniqueConnection) {\n\tdata, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tTimeEncodedPrintln(\"marshaling error: \", err)\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\tlength := int32(len(data)) + 1\n\n\tif useBase {\n\t\tlength = length + 1\n\t}\n\n\tif BYPASS_CONNECTION_SERVER {\n\t\tlength = length + 8\n\t}\n\n\tif DEBUG_SENDING_MESSAGE {\n\t\tTimeEncodedPrintln(\"sending message base length: \", length, \" command / command / message: \", baseCmd, cmd, msg)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\n\tbinary.Write(buf, binary.LittleEndian, length)\n\tif useBase {\n\t\tbinary.Write(buf, binary.LittleEndian, baseCmd)\n\t}\n\n\tbinary.Write(buf, binary.LittleEndian, cmd)\n\tif BYPASS_CONNECTION_SERVER {\n\t\tif DEBUG_SENDING_MESSAGE {\n\t\t\tTimeEncodedPrintln(\"Send extra 8 bytes: \", conn.Identifier)\n\t\t}\n\t\tbinary.Write(buf, binary.LittleEndian, int64(conn.Identifier))\n\t}\n\tbuf.Write(data)\n\tn, err := conn.Connection.Write(buf.Bytes())\n\tif DEBUG_SENDING_MESSAGE {\n\t\tfmt.Println(\"Sent\", n, \"bytes\", \"encounter error:\", err)\n\t}\n}", "func BuildMsg(from sdk.AccAddress, to sdk.AccAddress, coins sdk.Coins) sdk.Msg {\n\tinput := bank.NewInput(from, coins)\n\toutput := bank.NewOutput(to, coins)\n\tmsg := bank.NewMsgSend([]bank.Input{input}, []bank.Output{output})\n\treturn msg\n}", "func sendmsg(s int, msg *unix.Msghdr, flags int) (n int, err error)", "func makePacket(addr string, args []string) Packet {\n\tmsg := NewMessage(addr)\n\tfor _, arg := range args {\n\t\tmsg.Append(arg)\n\t}\n\treturn msg\n}", "func makeMessage(data Payload, job IJob) message {\n\treturn message{\n\t\tId: messageId(uuid.New().String()),\n\t\tAddress: job.Config().getAddr().md5(),\n\t\tQueue: job.Queue().Name,\n\t\tPayload: data,\n\t\tState: messageSend,\n\t\tCreateAt: time.Now(),\n\t}\n}", "func (eth *Eth) Msg(addr string, data []string) (string, error) {\n\tpacked := PackTxDataArgs(data...)\n\tkeys := eth.fetchKeyPair()\n\t//addr = ethutil.StripHex(addr)\n\tbyte_addr := ethutil.Hex2Bytes(addr)\n\thash, err := eth.pipe.Transact(keys, byte_addr, ethutil.NewValue(ethutil.Big(\"350\")), ethutil.NewValue(ethutil.Big(\"200000000000\")), ethutil.NewValue(ethutil.Big(\"1000000\")), []byte(packed))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ethutil.Bytes2Hex(hash), nil\n}", "func codeToDefaultMsg(code btypes.CodeType) string {\n\tswitch code {\n\tcase CodeInvalidInput:\n\t\treturn \"invalid input\"\n\tcase CodeOwnerNotExists:\n\t\treturn \"owner not exists\"\n\tcase CodeOwnerNoEnoughToken:\n\t\treturn \"owner has no enough token\"\n\tcase CodeValidatorExists:\n\t\treturn \"validator exists\"\n\tcase CodeOwnerHasValidator:\n\t\treturn \"owner already bind a validator\"\n\tcase CodeValidatorNotExists:\n\t\treturn \"validator not exists\"\n\tcase CodeValidatorIsActive:\n\t\treturn \"validator is active\"\n\tcase CodeValidatorIsInactive:\n\t\treturn \"validator is inactive\"\n\tcase CodeValidatorInactiveIncome:\n\t\treturn \"vaidator in inactive and got fees\"\n\tdefault:\n\t\treturn btypes.CodeToDefaultMsg(code)\n\t}\n}", "func (conn *Connection) SendMessage(msg message.Messager, timeout time.Duration) (err error) {\n\t// Send residual data\n\tpriBufLen := conn.WriteBuf.Len()\n\tif priBufLen > 0 {\n\t\t_, err = io.CopyN(conn.RWC, conn.WriteBuf, int64(conn.WriteBuf.Len()))\n\t}\n\tif err != nil {\n\t\tutils.Logger.Error(\"Send residual data error with %s\", err.Error())\n\t\treturn\n\t}\n\n\t// Pack data\n\thead := new(frame.Head)\n\thead.Init()\n\thead.Seq = conn.tickSeq()\n\tswitch msg.(type) {\n\tcase *node.ACK:\n\t\thead.CMD = proto.MNCMDACK\n\tcase *node.SessionRsp:\n\t\thead.CMD = proto.MNCMDSessionRsp\n\tcase *knot.ConnRsp:\n\t\thead.CMD = proto.MKCMDConnRsp\n\tcase *knot.AgentArriveReq:\n\t\thead.CMD = proto.MKCMDAgentArriveReq\n\tcase *node.Confirm:\n\t\thead.CMD = proto.MNCMDConfirm\n\tcase *knot.NodeMsg:\n\t\thead.CMD = proto.MKCMDNodeMsg\n\tcase *node.KnotMsg:\n\t\thead.CMD = proto.MNCMDKnotMsg\n\tcase *node.ErrorMsg:\n\t\thead.CMD = proto.MNCMDErrorMsg\n\tcase *knot.AgentQuit:\n\t\thead.CMD = proto.MKCMDAgentQuit\n\tcase *node.Discard:\n\t\thead.CMD = proto.MNCMDDiscard\n\tdefault:\n\t\thead.CMD = proto.MLCMDUnknown\n\n\t}\n\tframe := frame.Frame{\n\t\tHead: head,\n\t\tBody: msg,\n\t}\n\tutils.Logger.Debug(\"before pack buf is %d\", conn.WriteBuf.Len())\n\terr = frame.Pack(conn.WriteBuf)\n\tutils.Logger.Debug(\"after pack buf is %d\", conn.WriteBuf.Len())\n\tif err != nil {\n\t\tutils.Logger.Error(\"Pack frame with error %s\", err.Error())\n\t\treturn\n\t}\n\n\t// Send current package\n\ts, err := io.CopyN(conn.RWC, conn.WriteBuf, int64(conn.WriteBuf.Len()))\n\tif err != nil {\n\t\tutils.Logger.Error(\"Send current packge data error with %s\", err.Error())\n\t\treturn\n\t}\n\tutils.Logger.Debug(\"CopyN with %d\", s)\n\treturn\n}", "func newMessage(c cipher.API, s string) (buf, msg []byte) {\n\treturn make([]byte, 0, len(s)+c.Overhead()), []byte(s)\n}", "func fillMsg(fromAddress address.Address, api *apistruct.FullNodeStruct, msg *types.Message) (*types.SignedMessage, error) {\n\t// Get nonce\n\tnonce, err := api.MpoolGetNonce(context.Background(), msg.From)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.Nonce = nonce\n\n\t// Calculate gas\n\tlimit, err := api.GasEstimateGasLimit(context.Background(), msg, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasLimit = int64(float64(limit) * 1.25)\n\n\tpremium, err := api.GasEstimateGasPremium(context.Background(), 10, msg.From, msg.GasLimit, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasPremium = premium\n\n\tfeeCap, err := api.GasEstimateFeeCap(context.Background(), msg, 20, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasFeeCap = feeCap\n\n\t// Sign message\n\treturn api.WalletSignMessage(context.Background(), fromAddress, msg)\n}", "func SendMsg(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg sdk.Msg, ctx sdk.Context, chainID string, gasValue uint64, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr := msg.GetSigners()[0]\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tgasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error {\n\tvar command [commandSize]byte\n\n\t// Enforce max command size.\n\tcmd := msg.Command()\n\tif len(cmd) > commandSize {\n\t\tstr := fmt.Sprintf(\"command [%s] is too long [max %v]\",\n\t\t\tcmd, commandSize)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\tcopy(command[:], []byte(cmd))\n\n\t// Encode the message payload.\n\tvar bw bytes.Buffer\n\terr := msg.BtcEncode(&bw, pver)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpayload := bw.Bytes()\n\tlenp := len(payload)\n\n\t// Enforce maximum overall message payload.\n\tif lenp > maxMessagePayload {\n\t\tstr := fmt.Sprintf(\"message payload is too large - encoded \"+\n\t\t\t\"%d bytes, but maximum message payload is %d bytes\",\n\t\t\tlenp, maxMessagePayload)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\n\t// Enforce maximum message payload based on the message type.\n\tmpl := msg.MaxPayloadLength(pver)\n\tif uint32(lenp) > mpl {\n\t\tstr := fmt.Sprintf(\"message payload is too large - encoded \"+\n\t\t\t\"%d bytes, but maximum message payload size for \"+\n\t\t\t\"messages of type [%s] is %d.\", lenp, cmd, mpl)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\n\t// Create header for the message.\n\thdr := messageHeader{}\n\thdr.magic = btcnet\n\thdr.command = cmd\n\thdr.length = uint32(lenp)\n\tcopy(hdr.checksum[:], DoubleSha256(payload)[0:4])\n\n\t// Write header.\n\terr = writeElements(w, hdr.magic, command, hdr.length, hdr.checksum)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write payload.\n\t_, err = w.Write(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func MsgPrepare(common Common, tx *Transfer) base.Message {\n\tif tx.MessageType == 2 && common.PrivateKey != \"\" {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: \"\",\n\t\t}\n\t} else if tx.MessageType == 2 && common.IsHW {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t\tPublicKey: tx.RecipientPublicKey,\n\t\t}\n\n\t} else if tx.MessageType == 0 && utils.IsHexadecimal(tx.Message) {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: \"fe\" + tx.Message,\n\t\t}\n\t} else {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t}\n\t}\n}", "func NewMsg(channel string, pk string, kind int64, options ...func(*Msg) error) (*Msg, error) {\n\tmsg := &Msg{ChannelPK: channel, AuthorPK: pk, Kind: kind, CreatedAt: time.Now().Unix()}\n\tmsg.Data = make(map[string]interface{})\n\tfor _, opt := range options {\n\t\terr := opt(msg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif msg.PK == \"\" {\n\t\tid, err := ksuid.NewRandomWithTime(time.Unix(msg.CreatedAt, 0))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmsg.PK = fmt.Sprintf(\"%s%s\", MsgKeyPrefix, id.String())\n\t\tmsg.CreatedAt = id.Time().Unix() //there is a bit difference from origin, we need this to be stored\n\t}\n\n\tmsg.UMS.PK = msg.AuthorPK\n\tmsg.SK = msg.PK\n\treturn msg, nil\n}", "func (p *protocol) readMsg() (tcp.ProtocolMessage, error) {\n\tvar header [8]byte\n\n\tif _, err := p.conn.Read(header[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Grab length of message\n\tbodyLength := binary.BigEndian.Uint32(header[4:8])\n\n\tvar newFunc func(tcp.Connection, uint32) (tcp.ProtocolMessage, error)\n\tswitch {\n\tcase bytes.Equal(header[0:4], []byte(\"????\")): // UNKN\n\t\tnewFunc = newProtocolUNKN\n\tcase bytes.Equal(header[0:4], []byte(\"HELO\")):\n\t\tnewFunc = newProtocolHELO\n\tcase bytes.Equal(header[0:4], []byte(\"VERS\")):\n\t\tnewFunc = newProtocolVERS\n\tcase bytes.Equal(header[0:4], []byte(\"PING\")):\n\t\tnewFunc = newProtocolPING\n\tcase bytes.Equal(header[0:4], []byte(\"PONG\")):\n\t\tnewFunc = newProtocolPONG\n\tcase bytes.Equal(header[0:4], []byte(\"ACKN\")):\n\t\tnewFunc = newProtocolACKN\n\tcase bytes.Equal(header[0:4], []byte(\"JDAT\")):\n\t\tif p.isClient {\n\t\t\treturn nil, errors.New(\"protocol error: Unexpected JDAT message received on client connection\")\n\t\t}\n\t\tnewFunc = newProtocolJDAT\n\tcase bytes.Equal(header[0:4], []byte(\"EVNT\")):\n\t\tif p.isClient {\n\t\t\treturn nil, errors.New(\"protocol error: Unexpected JDAT message received on client connection\")\n\t\t}\n\t\tnewFunc = newProtocolEVNT\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected message code: %s\", header[0:4])\n\t}\n\n\treturn newFunc(p.conn, bodyLength)\n}", "func NewMsg(typ string) Msg {\n\treturn Msg{\n\t\tID: uuid.New().String(),\n\t\tType: typ,\n\t\tTimestamp: time.Now().UTC(),\n\t}\n}", "func (obj *MessagePacket) makeMessagePacket() {\n\tif obj.dataType == 0 {\n\t\tobj.dataType = 2\n\t}\n}", "func (mp JSONMsgPacker) PackMsg(msg interface{}, buf []byte) ([]byte, error) {\n\tbuffer := bytes.NewBuffer(buf)\n\tjsonEncoder := json.NewEncoder(buffer)\n\terr := jsonEncoder.Encode(msg)\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tbuf = buffer.Bytes()\n\treturn buf[:len(buf)-1], nil // encoder always put '\\n' at the end, we trim it\n}", "func makeEmptyMessage(command string) (Message, error) {\n\tvar msg Message\n\tswitch command {\n\tcase cmdVersion:\n\t\tmsg = &MsgVersion{}\n\n\tcase cmdVerAck:\n\t\tmsg = &MsgVerAck{}\n\n\tcase cmdGetAddr:\n\t\tmsg = &MsgGetAddr{}\n\n\tcase cmdAddr:\n\t\tmsg = &MsgAddr{}\n\n\tcase cmdGetBlocks:\n\t\tmsg = &MsgGetBlocks{}\n\n\tcase cmdBlock:\n\t\tmsg = &MsgBlock{}\n\n\tcase cmdInv:\n\t\tmsg = &MsgInv{}\n\n\tcase cmdGetData:\n\t\tmsg = &MsgGetData{}\n\n\tcase cmdNotFound:\n\t\tmsg = &MsgNotFound{}\n\n\tcase cmdTx:\n\t\tmsg = &MsgTx{}\n\n\tcase cmdPing:\n\t\tmsg = &MsgPing{}\n\n\tcase cmdPong:\n\t\tmsg = &MsgPong{}\n\n\tcase cmdGetHeaders:\n\t\tmsg = &MsgGetHeaders{}\n\n\tcase cmdHeaders:\n\t\tmsg = &MsgHeaders{}\n\n\tcase cmdAlert:\n\t\tmsg = &MsgAlert{}\n\n\tcase cmdMemPool:\n\t\tmsg = &MsgMemPool{}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled command [%s]\", command)\n\t}\n\treturn msg, nil\n}", "func debugMsg(rcode int, r *dns.Msg) *dns.Msg {\n\tanswer := new(dns.Msg)\n\tanswer.SetRcode(r, rcode)\n\treturn answer\n}", "func (_obj *DataService) InsertMessage(msg *Message, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = msg.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"insertMessage\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func Send(w MsgWriter, code uint64, data interface{}) error {\n\tsize, r, err := rlp.EncodeToReader(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// fmt.Println(\"Msg send code:\", msg code, \" size:\", size)\n\treturn w.WriteMsg(Msg{Code: code, Size: uint32(size), Payload: r})\n}", "func (cl CellAdvisor) SendMessage(cmd byte, data string) (int, error) {\n\n\tsendingMsg := []byte{'C', cmd, 0x01, 0x01}\n\tif data != \"\" {\n\t\tsendingMsg = append(sendingMsg, []byte(data)...)\n\t}\n\t//append checksum\n\tsendingMsg = append(sendingMsg, getChecksum(sendingMsg))\n\tsendingMsg = maskingCommandCharacter(sendingMsg)\n\tsendingMsg = append(append([]byte{0x7f}, sendingMsg...), 0x7e)\n\n\tnum, err := cl.writer.Write(sendingMsg)\n\t//num, err := fmt.Fprintf(cl.writer, string(sendingMsg))\n\terr = cl.writer.Flush()\n\treturn num, err\n}", "func generatePluginMsg(prefixMsg, suffixMsg, socketPath, details string) (simpleMsg, detailedMsg string) {\n\tsimpleMsg = fmt.Sprintf(\"%v for plugin at %q %v\", prefixMsg, socketPath, suffixMsg)\n\treturn simpleMsg, generatePluginMsgDetailed(prefixMsg, suffixMsg, socketPath, details)\n}", "func CreateMessage(topic string)(msg Message){\n msg = C.CreateMessage(C.CString(topic))\n return msg;\n}", "func SimulateMsgSend(\n\t_ *codec.ProtoCodec,\n\ttxCfg client.TxConfig,\n\tak nft.AccountKeeper,\n\tbk nft.BankKeeper,\n\tk keeper.Keeper,\n) simtypes.Operation {\n\treturn func(\n\t\tr *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,\n\t) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {\n\t\tsender, _ := simtypes.RandomAcc(r, accs)\n\t\treceiver, _ := simtypes.RandomAcc(r, accs)\n\n\t\tif sender.Address.Equals(receiver.Address) {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, \"sender and receiver are same\"), nil, nil\n\t\t}\n\n\t\tsenderAcc := ak.GetAccount(ctx, sender.Address)\n\t\tspendableCoins := bk.SpendableCoins(ctx, sender.Address)\n\t\tfees, err := simtypes.RandomFees(r, ctx, spendableCoins)\n\t\tif err != nil {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, err.Error()), nil, err\n\t\t}\n\n\t\tspendLimit := spendableCoins.Sub(fees...)\n\t\tif spendLimit == nil {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, \"spend limit is nil\"), nil, nil\n\t\t}\n\n\t\tn, err := randNFT(ctx, r, k, senderAcc.GetAddress())\n\t\tif err != nil {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, err.Error()), nil, err\n\t\t}\n\n\t\tmsg := &nft.MsgSend{\n\t\t\tClassId: n.ClassId,\n\t\t\tId: n.Id,\n\t\t\tSender: senderAcc.GetAddress().String(),\n\t\t\tReceiver: receiver.Address.String(),\n\t\t}\n\n\t\ttx, err := simtestutil.GenSignedMockTx(\n\t\t\tr,\n\t\t\ttxCfg,\n\t\t\t[]sdk.Msg{msg},\n\t\t\tfees,\n\t\t\tsimtestutil.DefaultGenTxGas,\n\t\t\tchainID,\n\t\t\t[]uint64{senderAcc.GetAccountNumber()},\n\t\t\t[]uint64{senderAcc.GetSequence()},\n\t\t\tsender.PrivKey,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, TypeMsgSend, \"unable to generate mock tx\"), nil, err\n\t\t}\n\n\t\tif _, _, err = app.SimDeliver(txCfg.TxEncoder(), tx); err != nil {\n\t\t\treturn simtypes.NoOpMsg(nft.ModuleName, sdk.MsgTypeURL(msg), \"unable to deliver tx\"), nil, err\n\t\t}\n\n\t\treturn simtypes.NewOperationMsg(msg, true, \"\"), nil, nil\n\t}\n}", "func Msg(body interface{}) *Message {\n\tvar bytes []byte\n\n\tswitch subject := body.(type) {\n\tcase string:\n\t\tbytes = []byte(subject)\n\tcase []byte:\n\t\tbytes = subject\n\tcase Byter:\n\t\tbytes = subject.Bytes()\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"No convertion to bytes for %T\", subject))\n\t}\n\n\treturn &Message{Body: bytes}\n}", "func NewMsg(v NodeID, i SlotID, q QSet, t Topic) *Msg {\n\tc := atomic.AddInt32(&msgCounter, 1)\n\treturn &Msg{\n\t\tC: c,\n\t\tV: v,\n\t\tI: i,\n\t\tQ: q,\n\t\tT: t,\n\t}\n}", "func msgEasy(L *lua.State) int {\n\n\t//var message = msgInstance(L)\n\t//luar.Register(L, \"\", map[string]interface{}{\n\t//\t\"theM\": message,\n\t//})\n\n\t// TODO\n\t// L.GetGlobal(\"theM\")\n\n\treturn 0\n}", "func makeHeader(bmnet wire.BitmessageNet, command string,\n\tpayloadLen uint32, checksum uint32) []byte {\n\n\t// The length of a bitmessage message header is 24 bytes.\n\t// 4 byte magic number of the bitmessage network + 12 byte command + 4 byte\n\t// payload length + 4 byte checksum.\n\tbuf := make([]byte, 24)\n\tbinary.BigEndian.PutUint32(buf, uint32(bmnet))\n\tcopy(buf[4:], []byte(command))\n\tbinary.BigEndian.PutUint32(buf[16:], payloadLen)\n\tbinary.BigEndian.PutUint32(buf[20:], checksum)\n\treturn buf\n}", "func (c *clientHandler) sendMessage(errCode int, msg string) {\n\tc.resetWTO()\n\n\tvar cmd string\n\tif 0 == errCode {\n\t\tcmd = fmt.Sprintf(\"+OK %s\\r\\n\", msg)\n\t} else {\n\t\tcmd = fmt.Sprintf(\"-%d %s\\r\\n\", errCode, msg)\n\t}\n\tsnd, err := c.conn.Write([]byte(cmd))\n\tif err != nil {\n\t\tc.server.log.Error(\"conn.Write:\", err)\n\t\tpanic(err)\n\t}\n\tif snd < len(cmd) {\n\t\tc.server.log.Error(\"conn.Write less msg:\")\n\t\tpanic(errors.New(\"write less\"))\n\t}\n}", "func makeEmptyMessage(msgType MessageType) (Message, error) {\n\tswitch msgType {\n\tcase VERSION_TYPE:\n\t\treturn &Version{}, nil\n\tcase VERACK_TYPE:\n\t\treturn &VersionAck{}, nil\n\tcase PING_TYPE:\n\t\treturn &PingMsg{}, nil\n\tcase PONG_TYPE:\n\t\treturn &PongMsg{}, nil\n\tcase GETADDR_TYPE:\n\t\treturn &AddrReq{}, nil\n\tcase ADDR_TYPE:\n\t\treturn &Addr{}, nil\n\tcase REJECT_TYPE:\n\t\treturn &RejectMsg{}, nil\n\tcase GET_HEADERS_TYPE:\n\t\treturn &BlockHeaderReq{}, nil\n\tcase HEADERS_TYPE:\n\t\treturn &BlockHeaders{}, nil\n\tcase GET_BLOCK_TYPE:\n\t\treturn &BlockReq{}, nil\n\tcase BLOCK_TYPE:\n\t\treturn &Block{}, nil\n\tcase TX_TYPE:\n\t\treturn &Transaction{}, nil\n\tcase TRACE_TYPE:\n\t\treturn &TraceMsg{}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown message type %v\", msgType)\n\t}\n}", "func appendMessage(startpos int, msg *Message) (int, Burst) {\n\t// expand the parameters of the message\n\taddr := msg.Addr\n\tfunction := byte(msg.Function)\n\ttype_ := 'a'\n\tcontent := msg.Content\n\n\tdebugf(\"append_message: addr %d function %d type %d content %s\", addr, function, type_, content)\n\n\t// the starting frame is selected based on the three least significant bits\n\tframeAddr := addr & 7\n\tframeAddrCw := frameAddr * 2 // or << 2 ?\n\n\tdebugf(\" frame_addr is %d, current position %d\", frameAddr, startpos)\n\n\t// append idle codewords, until we're in the right frame for this address\n\ttx := make(Burst, 0)\n\tpos := 0\n\tfor uint32(startpos+pos)%16 != frameAddrCw {\n\t\tdebugf(\" inserting IDLE codewords in position %d (%d)\", startpos+pos, (startpos+pos)%16)\n\t\ttx = append(tx, pocsagIdleWord)\n\t\tpos++\n\t}\n\n\t// Then, append the address codeword, containing the function and the address\n\t// (sans 3 least significant bits, which are indicated by the starting frame,\n\t// which the receiver is waiting for)\n\ttx = append(tx, addressCodeword(addr, function))\n\tpos++\n\n\t// Next, append the message contents\n\tvar contentEncLen int\n\tvar contentEnc Burst\n\tif msg.IsNumeric {\n\t\tcontentEncLen, contentEnc = appendContentNumeric(content)\n\t} else {\n\t\tcontentEncLen, contentEnc = appendContentText(content)\n\t}\n\n\ttx = append(tx, contentEnc...)\n\tpos += contentEncLen\n\n\t// Return the current frame position and the binary string to be appended\n\treturn pos, tx\n}", "func (client *RPCClient) createRequest(call *Call, seq uint64) (*protocol.Message, error) {\n\tcall.seq = seq\n\n\treq := protocol.GetPooledMsg()\n\treq.ServicePath = call.ServicePath\n\treq.ServiceMethod = call.ServiceMethod\n\n\tif call.heartBeat {\n\t\treq.SetHeartbeat(true)\n\t} else {\n\t\treq.SetHeartbeat(false)\n\t}\n\n\tif call.compressType != protocol.None {\n\t\treq.SetCompressType(protocol.Gzip)\n\t}\n\n\treq.SetSeq(seq)\n\n\tmd := extractMdFromClientCtx(call.ctx)\n\tif len(md) > 0 {\n\t\treq.Metadata = md\n\t}\n\n\tif call.serializeType != protocol.SerializeNone {\n\t\treq.SetSerializeType(call.serializeType)\n\t\tcodec := share.Codecs[req.SerializeType()]\n\t\tif codec == nil {\n\t\t\terr := fmt.Errorf(\"can not find codec for %d\", req.SerializeType())\n\t\t\treturn nil, err\n\t\t}\n\t\tdata, err := codec.Encode(call.Args)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"encode \")\n\t\t}\n\t\treq.Payload = data\n\t}\n\n\treturn req, nil\n}", "func (z NestInner) Msgsize() (s int) {\n\ts = 1 + 6 + msgp.StringPrefixSize + len(z.Hello)\n\treturn\n}", "func prepare_msg(t byte, id int, content []byte) *TSP_msg {\n\treturn &TSP_msg{TSP_header{t, id}, content}\n}", "func (msg MsgSend) Type() string { return \"send\" }", "func createClientPacket(destination, fileName, request, keywords, msg string, budget int) (gossiper.ClientPacket, error) {\n\tif isSimpleMessage(destination, fileName, request, keywords, msg) {\n\t\treturn gossiper.ClientPacket{Simple: &gossiper.SimpleMessage{Contents: msg}}, nil\n\t} else if isPrivateMessage(destination, fileName, request, keywords, msg) {\n\t\treturn gossiper.ClientPacket{Private: &gossiper.PrivateMessage{Text: msg, Destination: destination}}, nil\n\t} else if isFileIndexingRequest(destination, fileName, request, keywords) {\n\t\treturn gossiper.ClientPacket{FileIndex: &gossiper.FileIndexMessage{FileName: fileName}}, nil\n\t} else if isFileRequest(fileName, request, keywords) {\n\t\t// DESTINATION IS EITHER A PEER, EITHER THE EMPTY STRING\n\t\tfileRequest := gossiper.FileRequestMessage{FileName: fileName, Destination: destination, Request: request}\n\t\treturn gossiper.ClientPacket{FileRequest: &fileRequest}, nil\n\t} else if isSearchRequest(destination, fileName, request, keywords) {\n\t\tkeywordsArray := strings.Split(strings.Replace(keywords, \" \", \"\", -1), \",\")\n\t\tsearchRequestMessage := gossiper.SearchRequestMessage{Keywords: keywordsArray, Budget:uint64(budget)}\n\t\treturn gossiper.ClientPacket{FileSearchRequest: &searchRequestMessage}, nil\n\t} else {\n\t\treturn gossiper.ClientPacket{}, errors.New(\"unknown type of action for the values provided\")\n\t}\n}", "func OkMsg() Message {\n\treturn &messageStruct{\n\t\tresponse: &Response{true, \"\"},\n\t}\n}", "func testPackMessage(length, sequence uint32, v uint8, pad uint16, mType MessageType, message []byte) []byte {\n\tbuf := sbuf.NewBuffer(messageOverhead + len(message))\n\tbuf.WriteByte(v)\n\tbuf.WriteByte(uint8(mType))\n\tbinary.Write(buf, binary.BigEndian, pad)\n\n\t// An sbuf won't fail to write unless it's out of memory, then this\n\t// whole house of cards is coming crashing down anyways.\n\tbinary.Write(buf, binary.BigEndian, sequence)\n\tbinary.Write(buf, binary.BigEndian, length)\n\tbuf.Write(message)\n\treturn buf.Bytes()\n}", "func (i *Irc) buildMessage(inMsg irc.Msg) msg.Message {\n\t// Check for the user\n\tu := user.User{\n\t\tName: inMsg.Origin,\n\t}\n\n\tchannel := inMsg.Args[0]\n\tif channel == i.config.Get(\"Nick\", \"bot\") {\n\t\tchannel = inMsg.Args[0]\n\t}\n\n\tisAction := false\n\tvar message string\n\tif len(inMsg.Args) > 1 {\n\t\tmessage = inMsg.Args[1]\n\n\t\tisAction = strings.HasPrefix(message, actionPrefix)\n\t\tif isAction {\n\t\t\tmessage = strings.TrimRight(message[len(actionPrefix):], \"\\x01\")\n\t\t\tmessage = strings.TrimSpace(message)\n\t\t}\n\n\t}\n\n\tiscmd := false\n\tfilteredMessage := message\n\tif !isAction {\n\t\tiscmd, filteredMessage = bot.IsCmd(i.config, message)\n\t}\n\n\tmsg := msg.Message{\n\t\tUser: &u,\n\t\tChannel: channel,\n\t\tBody: filteredMessage,\n\t\tRaw: message,\n\t\tCommand: iscmd,\n\t\tAction: isAction,\n\t\tTime: time.Now(),\n\t\tHost: inMsg.Host,\n\t}\n\n\treturn msg\n}", "func SendMessage(conn net.Conn, message msg.FromServer) {\n\tlog.Printf(\"SendMessage() to addr: %v Worker:%v\\n\", conn.RemoteAddr().String(), message.DstWorker)\n\toutBuf := Logger.PrepareSend(fmt.Sprintf(\"Sending-%v-Message\", msg.TypeStr(message.Type)), message)\n\t// log.Printf(\"%v\\n\", outBuf)\n\tvar msgSize uint16\n\tmsgSize = uint16(len(outBuf))\n\tsizeBuf := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(sizeBuf, uint16(msgSize))\n\toutBuf = append(sizeBuf, outBuf...)\n\tsize, err := conn.Write(outBuf)\n\tcheckErr(err)\n\tif size != len(outBuf) {\n\t\tlog.Fatal(\"size of message out != size written\")\n\t}\n}", "func (ad *AgentRunCommandReplyType) constructMessage(result *contracts.DocumentResult) (*mgsContracts.AgentMessage, error) {\n\tlog := ad.context.Log()\n\tappConfig := ad.context.AppConfig()\n\tagentInfo := contracts.AgentInfo{\n\t\tLang: appConfig.Os.Lang,\n\t\tName: appConfig.Agent.Name,\n\t\tVersion: appConfig.Agent.Version,\n\t\tOs: appConfig.Os.Name,\n\t\tOsVersion: appConfig.Os.Version,\n\t}\n\treplyPayload := runcommand.FormatPayload(log, result.LastPlugin, agentInfo, result.PluginResults)\n\tcommandTopic := utils.GetTopicFromDocResult(result.ResultType, result.RelatedDocumentType)\n\treturn utils.GenerateAgentJobReplyPayload(log, ad.replyId, result.MessageID, replyPayload, commandTopic)\n}", "func createPostMsg(\n\tignorantMaster bool,\n\tlatestGuid string,\n\tnewestChange changeSet,\n\tfolder map[string]bool,\n\tpreviousGuid string,\n\tdirToWatch string) ([]byte, error) {\n\tvar result msgToMaster\n\tif ignorantMaster {\n\t\tresult = msgToMaster{\n\t\t\tFileName: newestChange.fileName,\n\t\t\tPreviousGuid: previousGuid,\n\t\t\tChangeType: changeTypeMap()[newestChange.fileChange],\n\t\t\tGuid: latestGuid,\n\t\t\tAllFiles: getKeys(folder),\n\t\t\tDirectory: dirToWatch,\n\t\t\tNewList: true,\n\t\t}\n\t} else {\n\t\tresult = msgToMaster{\n\t\t\tGuid: latestGuid,\n\t\t\tPreviousGuid: previousGuid,\n\t\t\tFileName: newestChange.fileName,\n\t\t\tChangeType: changeTypeMap()[newestChange.fileChange],\n\t\t\tAllFiles: []string{},\n\t\t\tDirectory: dirToWatch,\n\t\t\tNewList: false,\n\t\t}\n\t}\n\tjsn, err := json.Marshal(result)\n\treturn jsn, err\n}", "func (d *Dao) SendMessage(mids []int64, msg string, contest *mdlesp.Contest) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid_list\", xstr.JoinInts(mids))\n\tparams.Set(\"title\", d.c.Rule.AlertTitle)\n\tparams.Set(\"mc\", d.c.Message.MC)\n\tparams.Set(\"data_type\", _notify)\n\tparams.Set(\"context\", msg)\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\terr = d.messageHTTPClient.Post(context.Background(), d.c.Message.URL, \"\", params, &res)\n\tif err != nil {\n\t\tlog.Error(\"SendMessage d.messageHTTPClient.Post(%s) error(%+v)\", d.c.Message.URL+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tif res.Code != 0 {\n\t\tlog.Error(\"SendMessage url(%s) res code(%d)\", d.c.Message.URL+\"?\"+params.Encode(), res.Code)\n\t\terr = ecode.Int(res.Code)\n\t}\n\treturn\n}", "func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\t// Ignore all messages created by the bot itself\n\t// This isn't required in this specific example but it's a good practice.\n\tif m.Author.ID == s.State.User.ID {\n\t\treturn\n\t}\n\n\t// TODO: Maybe use regex?\n\tif len(m.Content) > 2 && m.Content[:2] == \">c\" {\n\t\tcommand := m.Content[3:]\n\t\tres := strings.SplitN(command, \" \", 2)\n\t\tif len(res) < 2 {\n\t\t\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Invalid command. Try `|compile LANG CODE`\\nCom: %#v, Res: %#v\", command, res))\n\t\t\treturn\n\t\t}\n\n\t\tswitch strings.ToLower(res[0]) {\n\t\tcase \"go\", \"golang\":\n\t\t\thandleGo(s, m, res[1])\n\t\tcase \"e\", \"elixir\":\n\t\t\thandleElixir(s, m, res[1])\n\t\tcase \"n\", \"node\", \"js\":\n\t\t\thandleJS(s, m, res[1])\n\t\tdefault:\n\t\t\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Invalid language, found %s\", res[0]))\n\t\t\treturn\n\t\t}\n\t} else if m.Content == \"hello\" {\n\t\ts.ChannelMessageSend(m.ChannelID, \"Hi!\")\n\t}\n}", "func SetMsgSize(header *uint64, size int) error {\n if size > MAX_NET_MSG_LEN {\n return ErrMaxMsgSize\n }\n\n *header = *header | uint64(size) << 16\n\n return nil\n}", "func GetMsg(code Code) string {\n\tmsg, ok := HttpStatusCodeMsgFlags[code]\n\tif ok {\n\t\treturn msg\n\t}\n\n\tmsg, ok = BusinessStatusCodeMsgFlags[code]\n\tif ok {\n\t\treturn msg\n\t}\n\n\treturn HttpStatusCodeMsgFlags[RequestErr]\n}", "func (f *fakeDiskUpdateWatchServer) SendMsg(m interface{}) error { return nil }", "func testMakeMsgTx(segwit bool) *testMsgTx {\n\tpkScript, auth := newP2PKHScript(segwit)\n\tmsgTx := wire.NewMsgTx(wire.TxVersion)\n\tmsgTx.AddTxOut(wire.NewTxOut(1, pkScript))\n\treturn &testMsgTx{\n\t\ttx: msgTx,\n\t\tauth: auth,\n\t}\n}", "func makeMessageReplier(replyRequest requestReplier) messageReplier {\n\treturn func(msg interface{}) (reply <-chan interface{}, err error) {\n\t\toutChan := make(chan interface{})\n\n\t\tswitch msg := msg.(type) {\n\t\tcase *messages.Request:\n\t\t\tgo func() {\n\t\t\t\tdefer close(outChan)\n\t\t\t\tif m, more := <-replyRequest(msg); more {\n\t\t\t\t\toutChan <- m\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn outChan, nil\n\t\tcase *messages.Prepare, *messages.Commit:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tpanic(\"Unknown message type\")\n\t\t}\n\t}\n}", "func NewMsgCreate(auth types.AccAddress,\n\tcreator types.Name, symbol types.Name,\n\tmaxSupply Coin, canIssue,\n\tcanLock, canBurn bool,\n\tissue2Height int64, initSupply Coin, desc []byte) MsgCreateCoin {\n\treturn MsgCreateCoin{\n\t\t*msg.MustNewKuMsg(\n\t\t\tRouterKeyName,\n\t\t\tmsg.WithAuth(auth),\n\t\t\tmsg.WithData(Cdc(), &MsgCreateCoinData{\n\t\t\t\tCreator: creator,\n\t\t\t\tSymbol: symbol,\n\t\t\t\tMaxSupply: maxSupply,\n\t\t\t\tCanIssue: canIssue,\n\t\t\t\tCanLock: canLock,\n\t\t\t\tCanBurn: canBurn,\n\t\t\t\tIssueToHeight: issue2Height,\n\t\t\t\tInitSupply: initSupply,\n\t\t\t\tDesc: desc,\n\t\t\t}),\n\t\t),\n\t}\n}", "func (z *LoginGameReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 6 + msgp.Int32Size + 5 + msgp.Int32Size + 5 + msgp.StringPrefixSize + len(z.Args)\n\treturn\n}", "func SendMessage(writer http.ResponseWriter, req *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(req.Body, 1048576))\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := req.Body.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Decode the passed body into the struct.\n\tvar message MessageStruct\n\tif err := json.Unmarshal(body, &message); err != nil {\n\t\tsendUnprocessableEntity(writer, err)\n\t\treturn\n\t}\n\n\tprotocol := strings.ToLower(message.Protocol)\n\n\tif protocol == \"http\" {\n\t\t// Send HTTP message\n\t\tvar httpMsg gcm.HttpMessage\n\t\tif err := json.Unmarshal(message.Message, &httpMsg); err != nil {\n\t\t\tlog.Println(\"Message Unmarshal error: %+v\", err)\n\t\t\tsendUnprocessableEntity(writer, err)\n\t\t\treturn\n\t\t}\n\n\t\tres, sendErr := gcm.SendHttp(apiKey, httpMsg)\n\t\tif sendErr != nil {\n\t\t\tSendMessageSendError(writer, sendErr)\n\t\t} else {\n\t\t\tSendOkResponse(writer, res)\n\t\t}\n\t} else if protocol == \"xmpp\" {\n\t\t// Send XMPP message\n\t\tvar xmppMsg gcm.XmppMessage\n\t\tif err := json.Unmarshal(message.Message, &xmppMsg); err != nil {\n\t\t\tlog.Println(\"Message Unmarshal error: %+v\", err)\n\t\t\tsendUnprocessableEntity(writer, err)\n\t\t\treturn\n\t\t}\n\n\t\tres, _, sendErr := gcm.SendXmpp(senderId, apiKey, xmppMsg)\n\t\tif sendErr != nil {\n\t\t\tSendMessageSendError(writer, sendErr)\n\t\t} else {\n\t\t\tSendOkResponse(writer, res)\n\t\t}\n\t} else {\n\t\t// Error\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\tsendJSON(writer, &HttpError{\"protocol should be HTTP or XMPP only.\"})\n\t}\n}", "func sendMsgAddAdmin(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgAddAdmin, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr, _ := sdk.AccAddressFromBech32(msg.Owner)\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func idForMsg(m *data.Message) string {\n\tvar sb strings.Builder\n\tsb.Grow(20 + len(m.ID)) // preallocate enough space. 19 for the timesamp, 1 for the |, plus the id\n\tsb.WriteString(strconv.Itoa(int(m.Created.UnixNano())))\n\tsb.WriteRune('|')\n\tsb.WriteString(string(m.ID))\n\treturn sb.String()\n}", "func sendMsgCreatePost(\n\tr *rand.Rand, app *baseapp.BaseApp, ak auth.AccountKeeper,\n\tmsg types.MsgCreatePost, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey,\n) error {\n\n\taccount := ak.GetAccount(ctx, msg.Creator)\n\tcoins := account.SpendableCoins(ctx.BlockTime())\n\n\tfees, err := sim.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx := helpers.GenTx(\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\n\t_, _, err = app.Deliver(tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func protocolToMessage(c net.Conn, s string) {\n\tfmt.Print(\"Recieved: \" + s) // Used to verify what was being received\n\tmessage := strings.Split(s, \"\\t\") // Split the received message into an array of strings by \\t\n\tusername := \"\" // Empty string that will contain the specified username\n\tregisterCount := 0 // Counter for the amount of times TCCHAT_REGISTER is received\n\t\n\tif len(message) > 1 { // If message has only one string in it, it's necessarily a disconnect call\n\t\t// Replace \"\\n\" in message by \"\" as many times as necessary (-1)\n\t\t// if -1 was 'n', it would replace \"\\n\" only 'n' times, no more\n\t\tusername = strings.Replace(message[1], \"\\n\", \"\", -1)\n\t}\n\t\n\t// Check if the connection has only sent 1 TCCHAT_REGISTER\n\tif registerCount > 1 {\n\t\tfmt.Println(\"Corrupted connection detected !\")\n\t\tc.Close()\n\t\tfmt.Println(\"Connection closed\")\n\t}\n\t// Prettier if else if loop checking the contents of message[0] which contains the prefix\n\t// of the protocol message\n\tswitch message[0] {\n\tcase \"TCCHAT_REGISTER\": // A new user has joined the server\n\t\tregisterUser(c, username)\n\t\tregisterCount += 1 // Increment counter by 1\n\t\t\n\tcase \"TCCHAT_MESSAGE\": // A message has been received from a connected client\n\t\tsendMessageAll(c, message[1])\n\n\tcase \"TCCHAT_DISCONNECT\\n\": // In case of a disconnect, the \\n will still be part of the message\n\t\tuserDisconnect(userMap[c])\n\t\t\n\tdefault: // Message received is not of the correct form, close the connection\n\t\tif err := c.Close(); err == nil {\n\t\t\tc.Close()\n\t\t}\n\t}\n}", "func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\n\t// Ignore all messages created by the bot itself\n\t// This isn't required in this specific example but it's a good practice.\n\tif m.Author.ID == s.State.User.ID {\n\t\treturn\n\t}\n\n\tif m.ChannelID == discordChannelID {\n\t\t//Get new message\n\t\tvar prefix = \"\"\n\n\t\t//If not messages from server (BOT) = from users in discord channel\n\t\tif m.Author.ID != discordBotID {\n\t\t\tprefix = \"[\" + m.Author.Username + \"]\"\n\t\t\tconsoleMSG = prefix + \": \" + m.Content\n\t\t} else { //if messages from Discord Minecraft Bot\n\t\t\t// Create replacer with pairs as arguments.\n\t\t\t//Fixing some EMOJIS to VK format\n\t\t\tr := strings.NewReplacer(\":octagonal_sign:\", \"&#9940;\",\n\t\t\t\t\":white_check_mark:\", \"&#9989;\",\n\t\t\t\t\":heavy_plus_sign:\", \"&#10133;\",\n\t\t\t\t\":heavy_minus_sign:\", \"&#10134;\",\n\t\t\t\t\":skull:\", \"&#128128;\",\n\t\t\t\t\":tada:\", \"&#127881;\",\n\t\t\t\t\":medal:\", \"&#127942;\")\n\n\t\t\t// Replace all pairs.\n\t\t\tresult := r.Replace(m.Content)\n\t\t\tconsoleMSG = result\n\t\t}\n\n\t\t//Call sendTOVk\n\t\tsendToVK(vkToken, consoleMSG, chatID)\n\t}\n}", "func (z GameKindReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size\n\treturn\n}", "func (c *JSONCodec) SendMsg(pack network.PackInf) (int, error) {\n\tmsg := pack.GetPackBody()\n\tt := reflect.TypeOf(msg)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\tvar out jsonMsg\n\tif name, ok := c.p.names[t]; ok {\n\t\tout.Head = name\n\t} else {\n\t\treturn 0, errors.New(\"unregisted json msg\")\n\t}\n\tout.Body = msg\n\terr := c.encoder.Encode(out)\n\n\treturn 0, err\n}", "func (plugin *PluginInfo) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(plugin details: %v)\", plugin)\n\treturn generatePluginMsg(prefixMsg, suffixMsg, plugin.SocketPath, detailedStr)\n}", "func makeFTCPMessage(r *http.Request, c *Customer) (*string, error) {\n\tmessage := string(\"smh_seg_id_version:000004|smh_source:\")\n\treturn &message, nil\n}", "func sendMessage(msg, sender, receiver, msgType string) {\n\tfmt.Println(\"Inside send message :\", msg, sender, receiver)\n\tconn, err := net.Dial(\"tcp\", Users[receiver]+\":5000\")\n\tdefer conn.Close()\n\thandleErr(err)\n\tmessage := Message{msgType, sender, msg}\n\tbuf, err2 := json.Marshal(message)\n\thandleErr(err2)\n\t_, err3 := conn.Write(buf)\n\tif err3 != nil {\n\t\treturn\n\t}\n\tfmt.Println(\"Done SendMessage\")\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 Write(w *bufio.Writer, m Message, l *log.Logger) error {\n\tdebugf := func(format string, v ...interface{}) {\n\t\tif l != nil {\n\t\t\tl.Printf(format, v...)\n\t\t}\n\t}\n\tswitch m := m.(type) {\n\tcase KeepAlive:\n\t\tdebugf(\"-> KeepAlive\")\n\t\t_, err := w.Write([]byte{0, 0, 0, 0})\n\t\treturn err\n\tcase Choke:\n\t\tdebugf(\"-> Choke\")\n\t\treturn sendMessage0(w, 0)\n\tcase Unchoke:\n\t\tdebugf(\"-> Unchoke\")\n\t\treturn sendMessage0(w, 1)\n\tcase Interested:\n\t\tdebugf(\"-> Interested\")\n\t\treturn sendMessage0(w, 2)\n\tcase NotInterested:\n\t\tdebugf(\"-> NotInterested\")\n\t\treturn sendMessage0(w, 3)\n\tcase Have:\n\t\tdebugf(\"-> Have %v\", m.Index)\n\t\treturn sendMessage1(w, 4, m.Index)\n\tcase Bitfield:\n\t\tdebugf(\"-> Bitfield %v\", len(m.Bitfield))\n\t\treturn sendMessage(w, 5, m.Bitfield, nil, nil)\n\tcase Request:\n\t\tdebugf(\"-> Request %v %v %v\", m.Index, m.Begin, m.Length)\n\t\treturn sendMessage3(w, 6, m.Index, m.Begin, m.Length)\n\tcase Piece:\n\t\tdebugf(\"-> Piece %v %v %v\", m.Index, m.Begin, len(m.Data))\n\t\tb := make([]byte, 8)\n\t\tformatUint32(b, m.Index)\n\t\tformatUint32(b[4:], m.Begin)\n\t\terr := sendMessage(w, 7, b, m.Data, nil)\n\t\tPutBuffer(m.Data)\n\t\tm.Data = nil\n\t\treturn err\n\tcase Cancel:\n\t\tdebugf(\"-> Cancel %v %v %v\", m.Index, m.Begin, m.Length)\n\t\treturn sendMessage3(w, 8, m.Index, m.Begin, m.Length)\n\tcase Port:\n\t\tdebugf(\"-> Port %v\", m.Port)\n\t\treturn sendMessageShort(w, 9, m.Port)\n\tcase SuggestPiece:\n\t\tdebugf(\"-> SuggestPiece %v\", m.Index)\n\t\treturn sendMessage1(w, 13, m.Index)\n\tcase HaveAll:\n\t\tdebugf(\"-> HaveAll\")\n\t\treturn sendMessage0(w, 14)\n\tcase HaveNone:\n\t\tdebugf(\"-> HaveNone\")\n\t\treturn sendMessage0(w, 15)\n\tcase RejectRequest:\n\t\tdebugf(\"-> RejectRequest %v %v %v\",\n\t\t\tm.Index, m.Begin, m.Length)\n\t\treturn sendMessage3(w, 16, m.Index, m.Begin, m.Length)\n\tcase AllowedFast:\n\t\tdebugf(\"-> AllowedFast %v\", m.Index)\n\t\treturn sendMessage1(w, 17, m.Index)\n\tcase Extended0:\n\t\tdebugf(\"-> Extended0\")\n\t\tvar f extensionInfo\n\t\tf.Version = m.Version\n\t\tif m.IPv6 != nil {\n\t\t\tf.IPv6 = m.IPv6.To16()\n\t\t}\n\t\tif m.IPv4 != nil {\n\t\t\tf.IPv4 = m.IPv4.To4()\n\t\t}\n\t\tf.Port = m.Port\n\t\tf.ReqQ = m.ReqQ\n\t\tf.MetadataSize = m.MetadataSize\n\t\tf.Messages = m.Messages\n\t\tf.UploadOnly = boolOrString(m.UploadOnly)\n\t\tf.Encrypt = boolOrString(m.Encrypt)\n\t\tb, err := bencode.EncodeBytes(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn sendExtended(w, 0, b, nil)\n\tcase ExtendedMetadata:\n\t\tdebugf(\"-> ExtendedMetadata %v %v\", m.Type, m.Piece)\n\t\ttpe := m.Type\n\t\tpiece := m.Piece\n\t\tinfo := &metadataInfo{Type: &tpe, Piece: &piece}\n\t\tif m.TotalSize > 0 {\n\t\t\ttotalsize := m.TotalSize\n\t\t\tinfo.TotalSize = &totalsize\n\t\t}\n\t\tb, err := bencode.EncodeBytes(info)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif m.Subtype == 0 {\n\t\t\tpanic(\"ExtendedMetadata subtype is 0\")\n\t\t}\n\t\treturn sendExtended(w, m.Subtype, b, m.Data)\n\tcase ExtendedPex:\n\t\tdebugf(\"-> ExtendedPex %v %v\", len(m.Added), len(m.Dropped))\n\t\ta4, f4, a6, f6 := pex.FormatCompact(m.Added)\n\t\td4, _, d6, _ := pex.FormatCompact(m.Dropped)\n\t\tinfo := pexInfo{\n\t\t\tAdded: a4,\n\t\t\tAddedF: f4,\n\t\t\tAdded6: a6,\n\t\t\tAdded6F: f6,\n\t\t\tDropped: d4,\n\t\t\tDropped6: d6,\n\t\t}\n\t\tb, err := bencode.EncodeBytes(info)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn sendExtended(w, m.Subtype, b, nil)\n\tcase ExtendedDontHave:\n\t\tdebugf(\"-> ExtendedDontHave %v\", m.Index)\n\t\tb := formatUint32(make([]byte, 4), m.Index)\n\t\tif m.Subtype == 0 {\n\t\t\tpanic(\"ExtendedDontHave subtype is 0\")\n\t\t}\n\t\treturn sendExtended(w, m.Subtype, b, nil)\n\tdefault:\n\t\tpanic(\"Unknown message\")\n\t}\n}", "func (s *service) MessageCreate(ctx context.Context, req *MessageCreateRequest) (*MessageCreateResponse, error) {\n\tif req.Sender == \"\" {\n\t\treturn nil, errors.Errorf(\"no sender specified\")\n\t}\n\tif req.Channel == \"\" {\n\t\treturn nil, errors.Errorf(\"no channel specified\")\n\t}\n\n\tsender, err := s.lookup(ctx, req.Sender, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsenderKey, err := s.edx25519Key(sender)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannel, err := keys.ParseID(req.Channel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchannelKey, err := s.edx25519Key(channel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: Prev\n\tid := req.ID\n\tif id == \"\" {\n\t\tid = encoding.MustEncode(keys.RandBytes(32), encoding.Base62)\n\t}\n\tmsg := &api.Message{\n\t\tID: id,\n\t\tText: req.Text,\n\t\tSender: sender,\n\t\tTimestamp: s.clock.NowMillis(),\n\t}\n\n\tif err := s.client.MessageSend(ctx, msg, senderKey, channelKey); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: Trigger message update asynchronously.\n\t// if err := s.pullMessages(ctx, channel, sender); err != nil {\n\t// \treturn nil, err\n\t// }\n\n\tout, err := s.messageToRPC(ctx, msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MessageCreateResponse{\n\t\tMessage: out,\n\t}, nil\n}", "func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}", "func appendMessageCodeword(word uint32) uint32 {\n\treturn calcBchAndParity(word | 1<<31)\n}", "func Test_Errorcode_Build(t *testing.T) {\n\n\terrorCode := uerrors.NewCodeErrorWithPrefix(\"test\", \"test0001\")\n\n\terrorCode.WithMsgBody(\"this is error message content with param.\")\n\terrorCode.WithMsgBody(\"params: ${p1} , ${p2} , ${p3}.\")\n\n\t//log.Printf()\n\n\tres := errorCode.Build(\"hello-message \", \"my deal-other \", \"define\")\n\tfmt.Println(res)\n\n\tfmt.Println(\"case 2\")\n\tres = errorCode.Build(\"hello-message2 \", \"my deal-other2 \", \"define2\")\n\tfmt.Println(res)\n\n}", "func recvmsg(s int, msg *unix.Msghdr, flags int) (n int, err error)", "func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func SendMessage(message string) {\n\tif message == \"\" {\n\t\tfmt.Println(\"Message cannot be empty\")\n\t\tos.Exit(1)\n\t}\n\n\ttype Status struct {\n\t\tSuccess bool\n\t\tMessage interface{}\n\t}\n\n\ttype Result struct {\n\t\tNewMessageID string `json:\"new_message_id\"`\n\t}\n\ttype Response struct {\n\t\tStatus Status `json:\"status\"`\n\t\tResult interface{}\n\t}\n\n\tbaseURL, err := url.Parse(apiURL)\n\n\tif err != nil {\n\t\tfmt.Println(\"Malformed URL: \", err.Error())\n\t\treturn\n\t}\n\n\troomID := viper.GetString(\"roomID\")\n\tparams := url.Values{}\n\tparams.Add(\"room_id\", roomID)\n\n\tbaseURL.RawQuery = params.Encode()\n\n\tvar replacedString = strings.ReplaceAll(message, \"\\\\n\", \"\\n\")\n\t// re := regexp.MustCompile(`\\r?\\n`)\n\t// replacedString := re.ReplaceAllString(message, `\\n`)\n\t// fmt.Printf(\"fd;fhkhfkhf %v\", replacedString)\n\tjsonValues, err := json.Marshal(map[string]string{\n\t\t\"text\": replacedString,\n\t\t\"_t\": viper.GetString(\"token\"),\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tformData := url.Values{\n\t\t\"pdata\": {string(jsonValues)},\n\t}\n\n\treq, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tbaseURL.String(),\n\t\tstrings.NewReader(formData.Encode()),\n\t)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8\")\n\treq.Header.Add(\"cookie\", fmt.Sprintf(\"%v=%v\", cookieName, viper.GetString(\"cookie\")))\n\n\tresponse, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error making send-message request, %v\\n\", err)\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error parsing response %v\\n\", err)\n\t\treturn\n\t}\n\n\tvar parsedBody Response\n\terr = json.Unmarshal(body, &parsedBody)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error parsing response\", err)\n\t}\n\n\tif parsedBody.Status.Success != true {\n\t\tvar errMsg string\n\t\tswitch v := parsedBody.Status.Message.(type) {\n\t\tcase string:\n\t\t\terrMsg = v\n\t\tcase []interface{}:\n\t\t\t// for _, val := range v {\n\t\t\t// \tfmt.Println(val)\n\t\t\t// }\n\t\t\terrMsg = v[0].(string)\n\t\t}\n\t\tfmt.Printf(\"❌ Send report failed: %v\\n\", errMsg)\n\n\t} else {\n\t\tfmt.Println(\"✅ Send report successfully\")\n\t}\n\t// fmt.Printf(\"%s\\n\", string(body))\n\n}", "func Msg(format string, args ...interface{}) string {\n\treturn fmt.Sprintf(format, args...)\n}", "func (s *server)TransMsg(ctx context.Context, msgSend *pb.MessageSend)(*pb.MessageRet, error){\n\tstart:=time.Now().UnixNano()\n\t//log.Println(\"node:\",s.NodeID,\":Reciving from node:\",msgSend.NodeID)\n\t//if msgSend.Type == 0{\n\t\t//log.Println(msgSend.Type,msgSend.Term,msgSend.LogIndex,msgSend.LogTerm,msgSend.CommitIndex,msgSend.NodeID)\n\t//}\n\t//log.Println(s.simple_raftlog_length,s.CommitIndex,s.currentTerm,s.votes,s.lastApplied,s.votedFor)\n\tvar msgRet pb.MessageRet\n\t/*\n\tResetClock()\n\tmsgRet.Success = 1\n\tmsgRet.Term = msgSend.Term\n\t*/\n\tswitch msgSend.Type{\n\t\tcase 0:msgRet.Type = 0\n\t\tcase 1:msgRet.Type = 1\n\t\tcase 2:msgRet.Type = 2\n\t}\n\tif msgSend.Term > s.currentTerm {\n\t\t//log.Println(\"i am out-of-date\")\n\t\tserverLock.Lock()\n\t\ts.currentTerm = msgSend.Term\n\t\tserverLock.Unlock()\n\t\tResetClock()\n\t\ts.BecomeFollower()\n\t}\n\tmsgRet.Term = s.currentTerm\n\tswitch msgSend.Type {\n\t\tcase 1://voteRPC\n\t\t\tserverLock.RLock()\n\t\t\tif msgSend.Term < s.currentTerm {\n\t\t\t\tserverLock.RUnlock()\n\t\t\t\t//log.Println(\"node:\",s.NodeID,\"lower term, reject\",msgSend.NodeID)\n\t\t\t\tmsgRet.Success = 0\n\t\t\t}else {\n\t\t\t\tif s.votedFor == 0 || s.votedFor == msgSend.NodeID{\n\t\t\t\t\tserverLock.RUnlock()\n\t\t\t\t\tif s.IsUpToDate(msgSend.LogTerm,msgSend.LogIndex){\n\t\t\t\t\t\tserverLock.Lock()\n\t\t\t\t\t\ts.votedFor = msgSend.NodeID\n\t\t\t\t\t\tserverLock.Unlock()\n\t\t\t\t\t\tmsgRet.Success = 1\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//log.Println(\"node:\",s.NodeID,\"out-of-date, reject\",msgSend.NodeID)\n\t\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t\t}\n\t\t\t\t}else {\n\t\t\t\t\tserverLock.RUnlock()\n\t\t\t\t\t//log.Println(\"node:\",s.NodeID,\"have votedFor other, reject\",msgSend.NodeID)\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}\n\t\t\t}\n\t\tdefault://heartbeat or appendEntry RPC\n\t\t\tif msgSend.Term < s.currentTerm {\n\t\t\t\t//log.Println(\"out-of-date,reject\")\n\t\t\t\tmsgRet.Success = 0\n\t\t\t}else {\n\t\t\t\tResetClock()\n\t\t\t\t//if msgSend.Type!=2{\n\t\t\t\t\t//log.Println(\"oh it is here:111\")\n\t\t\t\t//}\n\t\t\t\ts.CheckSendIndex(msgSend.CommitIndex)\n\t\t\t\t//log.Println(msgSend.CommitIndex,s.CommitIndex,s.simple_raftlog_length)\n\t\t\t\ts.leaderId = msgSend.NodeID\n\t\t\t\t//log.Println(\"lock check\")\n\t\t\t\tlogLock.RLock()\n\t\t\t\t//log.Println(\"msg check\")\n\t\t\t\tif s.simple_raftlog_length < msgSend.LogIndex {\n\t\t\t\t\t//didn't exist a Entry in the previous one\n\t\t\t\t\t//log.Println(\"too advanced\")\n\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}else if s.simple_raftlog_length >= msgSend.LogIndex && \n\t\t\t\tmsgSend.LogTerm != s.simple_raftlog_Term[msgSend.LogIndex]{\n\t\t\t\t\t//there is a conflict,delete all entries in Index and after it,\n\t\t\t\t\t//and we can't append this entry\n\t\t\t\t\t//log.Println(\"conflict,reject\")\n\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\tlogLock.Lock()\n\t\t\t\t\ts.simple_raftlog_length = msgSend.LogIndex - 1\n\t\t\t\t\tlogLock.Unlock()\n\t\t\t\t\tmsgRet.Success = 0\n\t\t\t\t}else{\n\t\t\t\t\tif msgSend.Type!=2{\n\t\t\t\t\t\t//log.Println(\"oh it is here:133\")\n\t\t\t\t\t}\n\t\t\t\t\tmsgRet.Success = 1//actually mgsSend.LogIndex = msgSend.Entry.Index - 1\n\t\t\t\t\tif msgSend.Type != 2 &&\n\t\t\t\t\t s.simple_raftlog_length >= msgSend.Entry.Index &&\n\t\t\t\t\t msgSend.Entry.Term != s.simple_raftlog_Term[msgSend.Entry.Index]{\n\t\t\t\t\t\t//unmatch the new one,conflict delete all,then append\n\t\t\t\t\t\t//log.Println(\"unmatch the new one,delete and then append\")\n\t\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\t\tlogLock.Lock()\n\t\t\t\t\t\ts.simple_raftlog_length = msgSend.LogIndex\n\t\t\t\t\t\tlogLock.Unlock()\n\t\t\t\t\t\ts.AddEntry(msgSend.Entry.Key,msgSend.Entry.Value,msgSend.Entry.Term)\n\t\t\t\t\t}else if msgSend.Type != 2 && \n\t\t\t\t\ts.simple_raftlog_length >= msgSend.Entry.Index && \n\t\t\t\t\tmsgSend.Entry.Term == s.simple_raftlog_Term[msgSend.Entry.Index]{\n\t\t\t\t\t\t//log.Println(\"not the new one,don't have to append\")\n\t\t\t\t\t\tlogLock.RUnlock()//not the new entry,and we don't need to delete\n\t\t\t\t\t}else if msgSend.Type != 2 && s.simple_raftlog_length == msgSend.LogIndex {\n\t\t\t\t\t\t//log.Println(\"yes it is a new one,append\")\n\t\t\t\t\t\tlogLock.RUnlock()//new one, and there is not conflict\n\t\t\t\t\t\ts.AddEntry(msgSend.Entry.Key,msgSend.Entry.Value,msgSend.Entry.Term)\n\t\t\t\t\t}else {//it is heartbeat\n\t\t\t\t\t\tif msgSend.Type != 2{\n\t\t\t\t\t\t\t//log.Println(\"bug:it is not heartbeat!!\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogLock.RUnlock()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if msgSend.Type!=2{\n\t\t\t\t//\tlog.Println(\"oh it is here:155\")\n\t\t\t\t//}\n\t\t\t}\n\t}\n\t//log.Println(\"Transback message\")\n\tend:=time.Now().UnixNano()\n\tTransMsgTime += (end - start)\n\treturn &msgRet,nil\n}", "func createMsgVpnFunc(d *schema.ResourceData, meta interface{}) error {\n\tstate := meta.(*ProviderState)\n\t// These are the only required fields, so init them upfront\n\tmsgVpn := semp_client.MsgVpn {\n\t\tMsgVpnName: d.Get(MSG_VPN_NAME).(string),\n\t}\n\tpopulateMsgVpnFromResource(&msgVpn, d)\n\n\tvpn, _, err := semp_client.MsgVpnApi{\n\t\tConfiguration: state.sempcfg,\n\t}.CreateMsgVpn(msgVpn, nil)\n\n\tif err != nil {\n\t\tlog.Println(\"MsgVpnApi.CreateMsgVpn ERROR\")\n\t\treturn err\n\t}\n\tlogSempMeta(\"Msg-VPN create\", vpn.Meta)\n\t// Must uniquely identify the resource within terraform\n\td.SetId( state.host + \"_\" + msgVpn.MsgVpnName )\n\n\treturn nil\n}", "func (z *SendGameFail) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 4 + msgp.StringPrefixSize + len(z.Msg) + 5 + msgp.Int32Size + 5 + msgp.Int32Size\n\treturn\n}", "func statusMsg(c cmd, t StatusType, msg string) string {\n\ts := c.name\n\tswitch t {\n\tcase StatusSuccess:\n\t\ts += \" succeeded\"\n\tcase StatusTransitioning:\n\t\ts += \" in progress\"\n\tcase StatusError:\n\t\ts += \" failed\"\n\t}\n\n\tif msg != \"\" {\n\t\t// append the original\n\t\ts += \": \" + msg\n\t}\n\treturn s\n}", "func (w *Watcher) GenerateAndMessage(params Parameters) (err error) {\n\t// TODO: remove tans functionality\n\treturn errors.New(\"GenerateAndMessage() method is deprecated\")\n\n\tlogger := w.logger.New(\"method\", \"GenerateAndMessage\")\n\tvar qty int64\n\n\tif params.Quantity > 0 {\n\t\tqty = int64(params.Quantity)\n\t} else {\n\t\tqty, err = w.settings.Int64(SettingTanGenerateQtyInt64)\n\t\tif nil != err {\n\t\t\tlogger.Error(\"tan watcher failed to retrieve setting tan_generate_qty\", \"error\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif params.NotificationMethod == \"\" {\n\t\tparams.NotificationMethod = NotificationMethodInternalMessage\n\t} else {\n\t\tif _, allowed := allowedNotificationMethods()[params.NotificationMethod]; !allowed {\n\t\t\tlogger.Error(\"tan watcher failed to send notification: notification method is not allowed\", \"notificationMethod\", params.NotificationMethod)\n\t\t\terr = errcodes.CreatePublicError(errcodes.CodeTanNotificationMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t}\n\n\tnotificationUrl, err := srvdiscovery.ResolveRPC(srvdiscovery.ServiceNameNotifications)\n\tif nil != err {\n\t\tlogger.Error(\"tan watcher failed to discover notifications service\", \"error\", err)\n\t\treturn\n\t}\n\tnotificationsClient := notificationspb.NewNotificationHandlerProtobufClient(notificationUrl.String(), http.DefaultClient)\n\n\tfor _, uid := range params.UserIds {\n\t\ttans, err := w.service.GenerateAndAdd(uid, uint(qty))\n\t\tif nil != err {\n\t\t\tlogger.Error(\"tan watcher failed to generate tans\", \"error\", err, \"uid\", uid)\n\t\t\treturn err\n\t\t}\n\n\t\tw.slots <- 1\n\t\tgo func(uid string, tans []string) {\n\t\t\tw.sendNotifications(notificationsClient, uid, strings.Join(tans, \"\\n\"), params.NotificationMethod)\n\t\t\t<-w.slots\n\t\t}(uid, tans)\n\t}\n\treturn\n}", "func putMsg(conn net.Conn, msg string){\n\tfmt.Printf(\"C %s\\n\", msg)\n\tio.WriteString(conn, msg)//send our message\n}", "func DecodeMsg(data []byte, expectedFlags uint8) (interface{}, error) {\n\tif len(data) < 1 {\n\t\treturn nil, fmt.Errorf(\"wrong message\")\n\t}\n\tvar ret Message\n\n\tmsgType := MessageType(data[0])\n\tif uint8(msgType)&expectedFlags == 0 {\n\t\treturn nil, fmt.Errorf(\"unexpected message\")\n\t}\n\n\tswitch msgType {\n\tcase msgTypeChunk:\n\t\tret = &MsgChunk{}\n\n\tcase msgTypePostTransaction:\n\t\tret = &MsgPostTransaction{}\n\n\tcase msgTypeSubscribe:\n\t\tret = &MsgUpdateSubscriptions{}\n\n\tcase msgTypeGetConfirmedTransaction:\n\t\tret = &MsgGetConfirmedTransaction{}\n\n\tcase msgTypeGetTxInclusionState:\n\t\tret = &MsgGetTxInclusionState{}\n\n\tcase msgTypeGetBacklog:\n\t\tret = &MsgGetBacklog{}\n\n\tcase msgTypeSetID:\n\t\tret = &MsgSetID{}\n\n\tcase msgTypeTransaction:\n\t\tret = &MsgTransaction{}\n\n\tcase msgTypeTxInclusionState:\n\t\tret = &MsgTxInclusionState{}\n\n\tcase msgTypeGetConfirmedOutput:\n\t\tret = &MsgGetConfirmedOutput{}\n\n\tcase msgTypeGetUnspentAliasOutput:\n\t\tret = &MsgGetUnspentAliasOutput{}\n\n\tcase msgTypeOutput:\n\t\tret = &MsgOutput{}\n\n\tcase msgTypeUnspentAliasOutput:\n\t\tret = &MsgUnspentAliasOutput{}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown message type %d\", msgType)\n\t}\n\tif err := ret.Read(marshalutil.New(data[1:])); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func MakeCode(size byte, bits uint32) Code {\n\treturn Code{Size: size, Bits: bits}\n}", "func (packet *SnmpPacket) marshalMsg() ([]byte, error) {\n\tvar err error\n\tbuf := new(bytes.Buffer)\n\n\t// version\n\tbuf.Write([]byte{2, 1, byte(packet.Version)})\n\n\tif packet.Version == Version3 {\n\t\tbuf, err = packet.marshalV3(buf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// community\n\t\tbuf.Write([]byte{4, uint8(len(packet.Community))})\n\t\tbuf.WriteString(packet.Community)\n\t\t// pdu\n\t\tpdu, err := packet.marshalPDU()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf.Write(pdu)\n\t}\n\n\t// build up resulting msg - sequence, length then the tail (buf)\n\tmsg := new(bytes.Buffer)\n\tmsg.WriteByte(byte(Sequence))\n\n\tbufLengthBytes, err2 := marshalLength(buf.Len())\n\tif err2 != nil {\n\t\treturn nil, err2\n\t}\n\tmsg.Write(bufLengthBytes)\n\tbuf.WriteTo(msg) // reverse logic - want to do msg.Write(buf)\n\n\tauthenticatedMessage, err := packet.authenticate(msg.Bytes())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn authenticatedMessage, nil\n}", "func (z Task) Msgsize() (s int) {\n\ts = 1 + 3 + msgp.Uint32Size + 8 + msgp.StringPrefixSize + len(z.Content) + 6 + msgp.StringPrefixSize + len(z.Token)\n\treturn\n}", "func msgInstance(L *lua.State) *qtiny.Message {\n\tif !L.IsNumber(1) {\n\t\tpanic(\"is not a reference in registry of message (not a number). lua unit index : \" + util.AsStr(L.GetData(\"luaunit_index\"), \"\"))\n\t}\n\tvar ptrvalue = L.ToInteger(1)\n\tvar ptr = unsafe.Pointer(uintptr(ptrvalue))\n\tvar message = (*qtiny.Message)(ptr)\n\treturn message\n}", "func (_L2CrossDomainMessenger *L2CrossDomainMessengerTransactor) SendMessage(opts *bind.TransactOpts, _target common.Address, _message []byte, _minGasLimit uint32) (*types.Transaction, error) {\n\treturn _L2CrossDomainMessenger.contract.Transact(opts, \"sendMessage\", _target, _message, _minGasLimit)\n}", "func YuntongxunSmsGo(accountSID string, applicationID string, token string, templateID int, tos string, content string) error {\n baseURL := \"https://app.cloopen.com:8883\"\n\n // filter number in blacklist\n tos = filter.BlackListFilter(tos)\n if tos == \"\" {\n log.Println(\"no receiver remain!\")\n return nil\n }\n\n // generate signature\n timestamp := time.Now().Format(\"20060102150405\")\n params := accountSID + token + timestamp\n md5Ctx := md5.New()\n md5Ctx.Write([]byte(params))\n signature := strings.ToUpper(hex.EncodeToString(md5Ctx.Sum(nil)))\n\n // generate reuqeust url\n requestURL := baseURL+\"/2013-12-26/Accounts/\"+accountSID+\"/SMS/TemplateSMS?sig=\"+signature\n\n // prepare request body\n contents := []string{content}\n data := &YuntongxunSmsData{To: tos, AppID: applicationID, TemplateID: strconv.Itoa(templateID), Datas: contents}\n dataJSON, err := json.Marshal(data)\n if err != nil {\n log.Printf(\"fail to prepare request data for %s: %s\", tos, err.Error())\n return err\n }\n\n // caculate content length\n contentLength := len(dataJSON) \n \n // generate authorization\n authorizationString := accountSID + \":\" + timestamp\n authorization := base64.StdEncoding.EncodeToString([]byte(authorizationString))\n\n // send\n timeout := time.Second * 5\n client := &http.Client{Timeout: timeout}\n request, err := http.NewRequest(\"POST\", requestURL, bytes.NewReader(dataJSON))\n request.Header.Add(\"Accept\", \"application/json\")\n request.Header.Add(\"Content-Type\", \"application/json;charset=utf-8\")\n request.Header.Add(\"Content-Length\",strconv.Itoa(contentLength))\n request.Header.Add(\"Authorization\", authorization)\n response, err := client.Do(request)\n if err != nil {\n log.Printf(\"fail to send message to %s: %s\", tos, err.Error())\n return err\n }\n defer response.Body.Close()\n body, err := ioutil.ReadAll(response.Body)\n if err != nil {\n log.Printf(\"fail to read response data for %s: %s\", tos, err.Error())\n return err\n }\n log.Printf(\"send message to %s successfully: %s\", tos, string(body))\n return nil\n}", "func handleMsgCreate(ctx sdk.Context, k Keeper, msg *MsgCreate) (*sdk.Result, error) {\n\tp, err := k.Create(ctx, msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\tsdk.EventTypeMessage,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, ModuleName),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeySender, msg.Owner.String()),\n\t\t),\n\t)\n\n\treturn &sdk.Result{\n\t\tData: p.Hash,\n\t\tEvents: ctx.EventManager().Events(),\n\t}, nil\n}", "func BuildSendFiatMsg(from sdk.AccAddress, to sdk.AccAddress, pegHash sdk.PegHash, amount int64) sdk.Msg {\n\n\tsendFiat := bank.NewSendFiat(from, to, pegHash, amount)\n\tmsg := bank.NewMsgBankSendFiats([]bank.SendFiat{sendFiat})\n\treturn msg\n}", "func createRTData(conn net.Conn, m message, tempType string) rtData {\n\tmessage, err := json.Marshal(m.Msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn rtData{tempType, message, conn}\n}", "func NewOperationMsg(msg sdk.Msg, ok bool, comment string) OperationMsg {\n\tmsgType := sdk.MsgTypeURL(msg)\n\tmoduleName := sdk.GetModuleNameFromTypeURL(msgType)\n\tif moduleName == \"\" {\n\t\tmoduleName = msgType\n\t}\n\tprotoBz, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"failed to marshal proto message: %w\", err))\n\t}\n\n\treturn NewOperationMsgBasic(moduleName, msgType, comment, ok, protoBz)\n}", "func (z *CreateContractParam) Msgsize() (s int) {\n\ts = 1 + 3 + z.PartyA.Msgsize() + 3 + z.PartyB.Msgsize() + 4 + msgp.ExtensionPrefixSize + z.Previous.Len() + 2 + msgp.ArrayHeaderSize\n\tfor za0001 := range z.Services {\n\t\ts += z.Services[za0001].Msgsize()\n\t}\n\ts += 3 + msgp.Int64Size + 3 + msgp.Int64Size + 3 + msgp.Int64Size\n\treturn\n}", "func createModeReply(buf []byte) *CreateModeReply {\n\tv := new(CreateModeReply)\n\tb := 1 // skip reply determinant\n\n\tb += 1 // padding\n\n\tv.Sequence = xgb.Get16(buf[b:])\n\tb += 2\n\n\tv.Length = xgb.Get32(buf[b:]) // 4-byte units\n\tb += 4\n\n\tv.Mode = Mode(xgb.Get32(buf[b:]))\n\tb += 4\n\n\tb += 20 // padding\n\n\treturn v\n}", "func ConstructP2pMessage(msgType byte, content []byte) []byte {\n\tmessage := make([]byte, 5+len(content))\n\tmessage[0] = 17 // messageType 0x11\n\tbinary.BigEndian.PutUint32(message[1:5], uint32(len(content)))\n\tcopy(message[5:], content)\n\treturn message\n}", "func (z ExitGameReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 5 + msgp.Int32Size\n\treturn\n}", "func messageToDiscordCreate(s *discordgo.Session, chID string, msg string) {\n\ts.ChannelMessageSend(\n\t\tchID,\n\t\tmsg,\n\t)\n\n}", "func (cl *Client) SendMsg(phone, msg string) error {\n\tsendBody := make(url.Values)\n\tsendBody.Set(\"nohp\", phone)\n\tsendBody.Set(\"pesan\", msg)\n\tsendBody.Set(\"captcha\", cl.captcha)\n\tsendBody.Set(\"key\", cl.key)\n\n\treq, err := http.NewRequest(\"POST\", \"https://\"+host+\"/send.php\", strings.NewReader(sendBody.Encode()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header = baseHeader()\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Set(\"origin\", \"https://alpha.payuterus.biz\")\n\treq.Header.Set(\"referer\", \"https://alpha.payuterus.biz/index.php\")\n\n\tfor _, c := range cl.cookies {\n\t\treq.AddCookie(c)\n\t}\n\n\thttpCl := http.DefaultClient\n\tif cl.prox != nil {\n\t\thttpCl.Transport = &http.Transport{Proxy: http.ProxyURL(cl.prox)}\n\t}\n\n\tresp, err := httpCl.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode > 200 {\n\t\treturn errors.New(resp.Status)\n\t}\n\n\traw, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp.Body.Close()\n\n\trawString := string(raw)\n\tif strings.Contains(rawString, \"Untuk Pengiriman Pesan Yang Sama\") {\n\t\tsplit := strings.Split(rawString, \"<br>Mohon Tunggu \")\n\t\tsplit = strings.Split(split[1], \" Menit Lagi\")\n\n\t\treturn errors.New(\"wait for \" + split[0] + \" minutes for sending the same message\")\n\t}\n\n\treturn nil\n}" ]
[ "0.6578145", "0.6516903", "0.61964613", "0.6109903", "0.6107194", "0.5852312", "0.584946", "0.5825267", "0.5729646", "0.5661675", "0.5618166", "0.561787", "0.5617706", "0.5576793", "0.555339", "0.55356306", "0.5535241", "0.54872227", "0.5469596", "0.54573846", "0.5453642", "0.54435337", "0.5418186", "0.5415716", "0.5414914", "0.5385633", "0.5370947", "0.5362575", "0.53623176", "0.5343896", "0.5341817", "0.5336626", "0.53190607", "0.5308782", "0.53043735", "0.5289205", "0.52676016", "0.52662873", "0.5237122", "0.52242607", "0.5220991", "0.52190584", "0.5217484", "0.52035457", "0.5201667", "0.51933116", "0.5188523", "0.51882166", "0.5181736", "0.51795566", "0.51758385", "0.51734996", "0.51657504", "0.5162932", "0.5160753", "0.5152343", "0.5146704", "0.5142494", "0.5132183", "0.5125594", "0.51206505", "0.5119398", "0.511034", "0.51100713", "0.5100631", "0.5097445", "0.5096864", "0.5092287", "0.5090435", "0.5089656", "0.50777394", "0.5072887", "0.5072099", "0.50691724", "0.50635916", "0.5057515", "0.50569504", "0.50559884", "0.50545037", "0.5051688", "0.50464314", "0.5039208", "0.50367236", "0.503468", "0.5032812", "0.5031807", "0.50260234", "0.5024714", "0.5024664", "0.5023148", "0.50182676", "0.5013011", "0.5007939", "0.50043666", "0.500295", "0.50024956", "0.5002125", "0.4994654", "0.49925223", "0.4991449" ]
0.71171874
0
validate login setup from the user, needs cardnumber on 16 digits and sifferkod on 4 digits everything thats Write from loginSetup uses makeMsg to convert the msg to 10 byte array Each msg will start with an opt code and followed by different msg in byte 110
func loginSetUp(connection net.Conn) { fmt.Println(lines[0]) //first line in the given lang file //infinit loop to read in correct cardnumber for { fmt.Print(lines[1]) card := strings.Replace(string(userInput()), " ", "", -1) //remooves space in cardnumber connection.Write(makeMsg(100, card)) //send msg to srv, first is opt code 100 for cardnumber to be validated ans := make([]byte, 10) //return value from srv connection.Read(ans) //read if it was validated from srv, 253 = true if ans[0] == 253 { break } else { fmt.Println(lines[6]) //received opt code 252 = fail } } //infinit loop to read password for { fmt.Print(lines[2]) password := userInput() //read input password from user connection.Write(makeMsg(101, password)) //makeMsg, opt code 101 for password, ans := make([]byte, 10) connection.Read(ans) //validate password from srv if ans[0] == 253 { break } else { fmt.Println(lines[6]) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}", "func validateGenerateSIPAuthVectorInputs(key []byte, opc []byte, sqn uint64) error {\n\tif len(key) != ExpectedKeyBytes {\n\t\treturn fmt.Errorf(\"incorrect key size. Expected %v bytes, but got %v bytes\", ExpectedKeyBytes, len(key))\n\t}\n\tif len(opc) != ExpectedOpcBytes {\n\t\treturn fmt.Errorf(\"incorrect opc size. Expected %v bytes, but got %v bytes\", ExpectedOpcBytes, len(opc))\n\t}\n\tif sqn > maxSqn {\n\t\treturn fmt.Errorf(\"sequence number too large, expected a number which can fit in 48 bits. Got: %v\", sqn)\n\t}\n\treturn nil\n}", "func validateToken(tokenObj token.StructToken) (string, bool) {\n\n\tvar errorfound string\n\t//validate token id ==100\n\t//if len(tokenObj.TokenID) != 100 {\n\t//\terrorfound = \"token ID must be 100 characters\"\n\t//\treturn errorfound, false\n\t//}\n\t//validate token name ==20\n\tif len(tokenObj.TokenName) < 4 || len(tokenObj.TokenName) > 20 {\n\t\terrorfound = \"token name must be more than 4 characters and less than or equal 20 characters\"\n\t\treturn errorfound, false\n\t}\n\t//validate token symbol <= 4\n\tif len(tokenObj.TokenSymbol) > 4 {\n\t\terrorfound = \"token symbol should less than or equal to 4 characters\"\n\t\treturn errorfound, false\n\t}\n\t// validate icon url if empty or ==100\n\t// if len(tokenObj.IconURL) == 0 || len(tokenObj.IconURL) <= 100 {\n\t// \terrorfound = \"\"\n\t// } else {\n\t// \terrorfound = \"Icon URL is optiaonal if enter it must be less or equal 100 characters\"\n\t// \treturn errorfound, false\n\t// }\n\t// validate description if empty or == 100\n\tif len(tokenObj.Description) == 0 || len(tokenObj.Description) <= 100 {\n\t\terrorfound = \"\"\n\t} else {\n\t\terrorfound = \"Description is optiaonal if enter it must be less or equal 100 characters\"\n\t\treturn errorfound, false\n\t}\n\t//validate initiator address if empty\n\tif tokenObj.InitiatorAddress == \"\" {\n\t\terrorfound = \"please enter initiator address (Public key)\"\n\t\treturn errorfound, false\n\t}\n\t//validate initiator address if exist in account data\n\taccountobj := account.GetAccountByAccountPubicKey(tokenObj.InitiatorAddress)\n\tfmt.Println(\"------------------ \", accountobj)\n\tif accountobj.AccountPublicKey == \"\" {\n\t\terrorfound = \"please enter valid initiator address (Public key)\"\n\t\treturn errorfound, false\n\t}\n\tif accountobj.AccountPassword != tokenObj.Password {\n\t\terrorfound = \"The given password is incorrect.\"\n\t\treturn errorfound, false\n\t}\n\n\t//validate Tokens Total Supply less than or equal zero\n\tif tokenObj.TokensTotalSupply < 1 {\n\t\terrorfound = \"please enter Tokens Total Supply more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens value less than or equal zero\n\tif tokenObj.TokenValue <= 0.0 {\n\t\terrorfound = \"please enter Tokens value more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate token precision from 0 to 5\n\tif tokenObj.Precision < 0 || tokenObj.Precision > 5 {\n\t\terrorfound = \"please enter Precision range from 0 to 5 \"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens UsageType is mandatory security or utility\n\tif tokenObj.UsageType == \"security\" || tokenObj.UsageType == \"utility\" {\n\t\terrorfound = \"\"\n\t} else {\n\t\terrorfound = \"please enter UsageType security or utility\"\n\t\treturn errorfound, false\n\t}\n\tif tokenObj.UsageType == \"security\" && tokenObj.Precision != 0 {\n\t\terrorfound = \"UsageType security and must precision equal zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens TokenType is mandatory public or private\n\tif tokenObj.TokenType == \"public\" || tokenObj.TokenType == \"private\" {\n\t\t// check type token is public, validating for enter contact ID\n\t\tif tokenObj.TokenType == \"public\" {\n\t\t\t// validate ContractID if empty or ==60\n\t\t\tif len(tokenObj.ContractID) < 4 || len(tokenObj.ContractID) > 60 {\n\t\t\t\terrorfound = \"enter ContractID must be more than 4 character and less than or equal 60 characters\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t\t// check type token is Private , validating for enter pentential PK ,\n\t\t// enter the potential users public keys which can use this token\n\t\taccountList := accountdb.GetAllAccounts()\n\t\tif tokenObj.TokenType == \"private\" {\n\t\t\t//enter pentential PK which can use this token\n\t\t\tif len(tokenObj.UserPublicKey) != 0 {\n\t\t\t\tfor _, pk := range tokenObj.UserPublicKey {\n\t\t\t\t\tif pk == tokenObj.InitiatorAddress {\n\t\t\t\t\t\terrorfound = \"user create token can't be in user public key \"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t\tif !containspk(accountList, pk) {\n\t\t\t\t\t\terrorfound = \"this public key is not associated with any account\"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorfound = \"enter the potential users public keys which can use this token\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorfound = \"please enter TokenType is public or private\"\n\t\treturn errorfound, false\n\t}\n\n\t// Dynamic price\tIf the price of token is dynamic it gets its value from bidding platform.\n\t// Bidding platform API URL.\n\t// based on ValueDynamic True or false\n\tif tokenObj.ValueDynamic == true {\n\t\t//for example value\n\t\tbiddingplatformValue := 5.5\n\t\ttokenObj.Dynamicprice = biddingplatformValue\n\t}\n\treturn \"\", true\n}", "func validateNewUFA(who string, payload string) string {\r\n\r\n\t//As of now I am checking if who is of proper role\r\n\tvar validationMessage bytes.Buffer\r\n\tvar ufaDetails map[string]string\r\n\r\n\tlogger.Info(\"validateNewUFA\")\r\n\tif who == \"SELLER\" || who == \"BUYER\" {\r\n\t\tjson.Unmarshal([]byte(payload), &ufaDetails)\r\n\t\t//Now check individual fields\r\n\t\tnetChargeStr := ufaDetails[\"netCharge\"]\r\n\t\tfmt.Println(\"netcharge is :\" + netChargeStr)\r\n\t\ttolerenceStr := ufaDetails[\"chargTolrence\"]\r\n\t\tnetCharge := validateNumber(netChargeStr)\r\n\t\tif netCharge <= 0.0 {\r\n\t\t\tvalidationMessage.WriteString(\"\\nInvalid net charge\")\r\n\t\t}\r\n\t\ttolerence := validateNumber(tolerenceStr)\r\n\t\tif tolerence < 0.0 || tolerence > 10.0 {\r\n\t\t\tvalidationMessage.WriteString(\"\\nTolerence is out of range. Should be between 0 and 10\")\r\n\t\t}\r\n\r\n\t} else {\r\n\t\tvalidationMessage.WriteString(\"\\nUser is not authorized to create a UFA\")\r\n\t}\r\n\tlogger.Info(\"Validation messagge \" + validationMessage.String())\r\n\treturn validationMessage.String()\r\n}", "func TestMalformedPacket(t *testing.T) {\n\t// copied as bytes from Wireshark, then modified the RelayMessage option length\n\tbytes := []byte{\n\t\t0x0c, 0x00, 0x24, 0x01, 0xdb, 0x00, 0x30, 0x10, 0xb0, 0x8a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x0a, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0b, 0xab, 0xff, 0xfe, 0x8a,\n\t\t0x6d, 0xf2, 0x00, 0x09, 0x00, 0x50 /*was 0x32*/, 0x01, 0x8d, 0x3e, 0x24, 0x00, 0x01, 0x00, 0x0e, 0x00, 0x01,\n\t\t0x00, 0x01, 0x0c, 0x71, 0x3d, 0x0e, 0x00, 0x0b, 0xab, 0x8a, 0x6d, 0xf2, 0x00, 0x08, 0x00, 0x02,\n\t\t0x00, 0x00, 0x00, 0x03, 0x00, 0x0c, 0xee, 0xbf, 0xfb, 0x6e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n\t\t0xff, 0xff, 0x00, 0x06, 0x00, 0x02, 0x00, 0x17, 0x00, 0x25, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x09,\n\t\t0x00, 0x03, 0x08, 0x00, 0xf0, 0x7f, 0x06, 0xd6, 0x4c, 0x3c, 0x00, 0x12, 0x00, 0x04, 0x09, 0x01,\n\t\t0x08, 0x5a,\n\t}\n\tpacket := Packet6(bytes)\n\t_, err := packet.dhcp6message()\n\tif err == nil {\n\t\tt.Fatalf(\"Should be unable to extract dhcp6message, but did not fail\")\n\t}\n}", "func isValidPart1(line string) bool {\n\tcharMin, charMax, charRequired, password := parseLine(line)\n\tcharCount := 0\n\tfor _, char := range password {\n\t\tif string(char) == charRequired {\n\t\t\tcharCount += 1\n\t\t}\n\t}\n\tif (charMin <= charCount) && (charCount <= charMax) {\n\t\treturn true\n\t}\n\treturn false\n}", "func bytesRecvRspFn_Login(me interface{}, hd c2s_packet.Header, rbody []byte) error {\n\trobj, err := c2s_json.UnmarshalPacket(hd, rbody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Packet type miss match %v\", rbody)\n\t}\n\trecved, ok := robj.(*c2s_obj.RspLogin_data)\n\tif !ok {\n\t\treturn fmt.Errorf(\"packet mismatch %v\", robj)\n\t}\n\treturn fmt.Errorf(\"Not implemented %v\", recved)\n}", "func validateGenerateSIPAuthVectorWithRandInputs(rand []byte, key []byte, opc []byte, sqn uint64) error {\n\tif len(rand) != RandChallengeBytes {\n\t\treturn fmt.Errorf(\"incorrect rand size. Expected %v bytes, but got %v bytes\", RandChallengeBytes, len(rand))\n\t}\n\tif len(key) != ExpectedKeyBytes {\n\t\treturn fmt.Errorf(\"incorrect key size. Expected %v bytes, but got %v bytes\", ExpectedKeyBytes, len(key))\n\t}\n\tif len(opc) != ExpectedOpcBytes {\n\t\treturn fmt.Errorf(\"incorrect opc size. Expected %v bytes, but got %v bytes\", ExpectedOpcBytes, len(opc))\n\t}\n\tif sqn > maxSqn {\n\t\treturn fmt.Errorf(\"sequence number too large, expected a number which can fit in 48 bits. Got: %v\", sqn)\n\t}\n\treturn nil\n}", "func validateNewUFAData(args []string) []byte {\r\n\tvar output string\r\n\tmsg := validateNewUFA(args[0], args[1])\r\n\r\n\tif msg == \"\" {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\r\n\t} else {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\r\n\t}\r\n\treturn []byte(output)\r\n}", "func bytesRecvRspFn_Login(me interface{}, hd w3d_packet.Header, rbody []byte) error {\n\trobj, err := w3d_json.UnmarshalPacket(hd, rbody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Packet type miss match %v\", rbody)\n\t}\n\trecved, ok := robj.(*w3d_obj.RspLogin_data)\n\tif !ok {\n\t\treturn fmt.Errorf(\"packet mismatch %v\", robj)\n\t}\n\treturn fmt.Errorf(\"Not implemented %v\", recved)\n}", "func validateTokenForUpdating(tokenObj token.StructToken) (string, bool) {\n\n\tvar errorfound string\n\t//validate initiator address if exist in account data\n\taccountobj := account.GetAccountByAccountPubicKey(tokenObj.InitiatorAddress)\n\tif accountobj.AccountPublicKey == \"\" {\n\t\terrorfound = \"please enter valid initiator address (Public key)\"\n\t\treturn errorfound, false\n\t}\n\tif accountobj.AccountPassword != tokenObj.Password {\n\t\terrorfound = \"The given password is incorrect.\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens Total Supply less than or equal zero\n\tif tokenObj.TokensTotalSupply < 1 {\n\t\terrorfound = \"please enter Tokens Total Supply more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens value less than or equal zero\n\tif tokenObj.TokenValue <= 0.0 {\n\t\terrorfound = \"please enter Tokens value more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate token precision from 0 to 5\n\tif tokenObj.Precision < 0 || tokenObj.Precision > 5 {\n\t\terrorfound = \"please enter Precision range from 0 to 5 \"\n\t\treturn errorfound, false\n\t}\n\n\t//validate Tokens TokenType is mandatory public or private\n\tif tokenObj.TokenType == \"public\" || tokenObj.TokenType == \"private\" {\n\t\t// check type token is public, optianal enter contact ID\n\t\tif tokenObj.TokenType == \"public\" {\n\t\t\t// validate ContractID if empty or ==60\n\t\t\tif len(tokenObj.ContractID) < 4 || len(tokenObj.ContractID) > 60 {\n\t\t\t\terrorfound = \"enter ContractID must be more than 4 character and less than or equal 60 characters\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t\t// check type token is Private , optianal enter pentential PK ,enter the potential users public keys which can use this token\n\t\taccountList := accountdb.GetAllAccounts()\n\t\tif tokenObj.TokenType == \"private\" {\n\t\t\t//enter pentential PK which can use this token\n\t\t\tif len(tokenObj.UserPublicKey) != 0 {\n\t\t\t\tfor _, pk := range tokenObj.UserPublicKey {\n\t\t\t\t\tif pk == tokenObj.InitiatorAddress {\n\t\t\t\t\t\terrorfound = \"user create token can't be in user public key \"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t\tif !containspk(accountList, pk) {\n\t\t\t\t\t\terrorfound = \"this public key is not associated with any account\"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorfound = \"enter the potential users public keys which can use this token\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorfound = \"please enter TokenType is public or private\"\n\t\treturn errorfound, false\n\t}\n\n\treturn \"\", true\n}", "func validateNewUFA(who string, payload string) string {\n\n\t//As of now I am checking if who is of proper role\n\tvar validationMessage bytes.Buffer\n\tvar ufaDetails interface{}\n\n\tlogger.Info(\"validateNewUFA\")\n\tif who == \"SELLER\" || who == \"BUYER\" {\n\t\tlogger.Info(\"validateNewUFA WHO\")\n\n\t\tjson.Unmarshal([]byte(payload), &ufaDetails)\n\t\t//Now check individual fields\n\t\tufaRecordMap := ufaDetails.(map[string]interface{})\n\t\tnetChargeStr := getSafeString(ufaRecordMap[\"netCharge\"])\n\t\ttolerenceStr := getSafeString(ufaRecordMap[\"chargTolrence\"])\n\t\tnetCharge := validateNumber(netChargeStr)\n\t\tif netCharge <= 0.0 {\n\t\t\tvalidationMessage.WriteString(\"\\nInvalid net charge\")\n\t\t}\n\t\ttolerence := validateNumber(tolerenceStr)\n\t\tif tolerence < 0.0 || tolerence > 10.0 {\n\t\t\tvalidationMessage.WriteString(\"\\nTolerence is out of range. Should be between 0 and 10\")\n\t\t}\n\n\t} else {\n\t\tvalidationMessage.WriteString(\"\\nUser is not authorized to create a UFA\")\n\t}\n\tlogger.Info(\"Validation messagge \" + validationMessage.String())\n\treturn validationMessage.String()\n}", "func validateNewUFAData(args []string) []byte {\n\tvar output string\n\tmsg := validateNewUFA(args[0], args[1])\n\n\tif msg == \"\" {\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\n\t} else {\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\n\t}\n\treturn []byte(output)\n}", "func (c *Conn) writeInitHandshake() error {\n\n data := make([]byte, 4, 128)\n\n // 1 byte 协议版本号\n\n data = append(data, 10)\n\n // n bytes 服务版本号[00]\n\n data = append(data, constant.ServerVersion...)\n data = append(data, 0)\n\n // 4 bytes 线程id\n data = append(data, byte(c.connectionId), byte(c.connectionId>>8), byte(c.connectionId>>16), byte(c.connectionId>>24) )\n\n // 8 bytes 随机数\n\n data = append(data, c.salt[0:8]...)\n\n // 1 bytes 填充值 0x00\n data = append(data, 0)\n\n\n // 2 bytes 服务器权能标志\n data = append(data, byte(DEFAULT_CAPABILITY), byte(DEFAULT_CAPABILITY>>8))\n\n // 1 bytes 字符编码\n data = append(data, uint8(DEFAULT_COLLATION_ID))\n\n // 2 bytes 服务器状态\n data = append(data, byte(c.status), byte(c.status>>8))\n\n // 2 bytes 服务器权能标志(高16位)\n data = append(data, byte(DEFAULT_CAPABILITY>>16), byte(DEFAULT_COLLATION_ID>>24))\n\n // 1 bytes 挑战长度\n data = append(data, 0x15)\n\n // 10 bytes 填充数据\n data = append(data, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\n // n bytes 挑战随机数\n data = append(data, c.salt[8:]...)\n\n // 1 byte 结尾0x00\n data = append(data,0)\n\n return c.pkg.WritePacket(data)\n\n}", "func validateGenerateEutranVectorInputs(key []byte, opc []byte, sqn uint64, plmn []byte) error {\n\tif err := validateGenerateSIPAuthVectorInputs(key, opc, sqn); err != nil {\n\t\treturn err\n\t}\n\tif len(plmn) != ExpectedPlmnBytes {\n\t\treturn fmt.Errorf(\"incorrect plmn size. Expected 3 bytes, but got %v bytes\", len(plmn))\n\t}\n\treturn nil\n}", "func handleAuth(b []byte) bool {\n\tlogin := strings.Split(string(b), \" \")\n\t// Validate login packet\n\tif len(login) < 4 {\n\t\treturn false\n\t}\n\tif login[0] != \"user\" {\n\t\treturn false\n\t}\n\tif login[2] != \"pass\" {\n\t\treturn false\n\t}\n\tlog.Info().Str(\"user\", login[1]).Msg(\"new login\")\n\treturn true\n}", "func onHandshake(data []byte) (err error) {\n\tif !(bytes.Equal(handshakePrefix[:20], data[:20]) && data[25]&0x10 != 0) {\n\t\terr = errors.New(\"invalid handshake response\")\n\t}\n\treturn\n}", "func (z *LoginGameReq) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 6 + msgp.Int32Size + 5 + msgp.Int32Size + 5 + msgp.StringPrefixSize + len(z.Args)\n\treturn\n}", "func (z *SQLChainUser) Msgsize() (s int) {\n\ts = 1 + 8 + z.Address.Msgsize() + 15 + hsp.Uint64Size + 8 + hsp.Uint64Size + 8 + hsp.Uint64Size + 11\n\tif z.Permission == nil {\n\t\ts += hsp.NilSize\n\t} else {\n\t\ts += 1 + 5 + hsp.Int32Size + 9 + hsp.ArrayHeaderSize\n\t\tfor za0001 := range z.Permission.Patterns {\n\t\t\ts += hsp.StringPrefixSize + len(z.Permission.Patterns[za0001])\n\t\t}\n\t}\n\ts += 7 + hsp.Int32Size\n\treturn\n}", "func Decode(msg string) MessageTemp {\n var r = make([]string,15)\n r = strings.Split(msg, \";\")\n var result = MessageTemp{}\n for _,v := range r {\n key_value := strings.Split(v,\"=\")\n switch key_value[0] {\n case \"35\":\n if key_value[1]==\"8\"{ // 35=8; 股票交易相关信息\n result.order_type = \"trade\"\n } else if key_value[1]==\"9\"{ // 35=9; 用户相关信息\n result.order_type = \"user\"\n } else if key_value[1]==\"10\"{ //35=10; 查询order book\n result.order_type = \"view\"\n }\n case \"44\":\n result.price, _ = strconv.Atoi(key_value[1])\n case \"11\":\n result.stock_id, _ = strconv.Atoi(key_value[1])\n case \"38\":\n result.quantity, _ = strconv.Atoi(key_value[1])\n case \"54\":\n if key_value[1]==\"1\"{\n result.trade_type = \"buy\"\n } else if key_value[1]==\"2\"{\n result.trade_type = \"sell\"\n }\n case \"5001\":\n result.username = key_value[1]\n case \"5002\":\n result.password = key_value[1]\n }\n }\n //fmt.Println(result)\n return result\n}", "func isBDS05V0Valid(t *testing.T, msg MessageBDS05V0) {\n\n\tif msg.GetRegister().GetId() != bds.BDS05.GetId() {\n\t\tt.Errorf(\"Expected Register \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tbds.BDS05.GetId(),\n\t\t\tmsg.GetRegister().GetId())\n\t}\n\n\tif msg.GetSurveillanceStatus() != fields.SSTemporaryAlert {\n\t\tt.Errorf(\"Expected Time \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tfields.SSTemporaryAlert.ToString(),\n\t\t\tmsg.GetSurveillanceStatus().ToString())\n\t}\n\n\tif msg.GetSingleAntennaFlag() != fields.SAFSingle {\n\t\tt.Errorf(\"Expected Time \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tfields.SAFSingle.ToString(),\n\t\t\tmsg.GetSingleAntennaFlag().ToString())\n\t}\n\n\tif msg.GetAltitude().AltitudeInFeet != 33250 {\n\t\tt.Errorf(\"Expected Altitude In Feet to be 33250, got \\\"%v\\\"\",\n\t\t\tmsg.GetAltitude().AltitudeInFeet)\n\t}\n\n\tif msg.GetTime() != fields.TSynchronizedUTC {\n\t\tt.Errorf(\"Expected Time \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tfields.TSynchronizedUTC.ToString(),\n\t\t\tmsg.GetTime().ToString())\n\t}\n\n\tif msg.GetCPRFormat() != fields.CPRFormatOdd {\n\t\tt.Errorf(\"Expected CPR Format \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tfields.CPRFormatOdd.ToString(),\n\t\t\tmsg.GetCPRFormat().ToString())\n\t}\n\n\tif msg.GetEncodedLatitude() != 43722 {\n\t\tt.Errorf(\"Expected Latitude to be 43722, got \\\"%v\\\"\",\n\t\t\tmsg.GetEncodedLatitude())\n\t}\n\n\tif msg.GetEncodedLongitude() != 87466 {\n\t\tt.Errorf(\"Expected Longitude to be 87466, got \\\"%v\\\"\",\n\t\t\tmsg.GetEncodedLatitude())\n\t}\n\n\tif len(msg.ToString()) <= 0 {\n\t\tt.Error(\"Expected a printable message, but get nothing\")\n\t}\n}", "func validate2(in line) bool {\n\tcount := 0\n\tif in.password[in.i-1] == in.char {\n\t\tcount++\n\t}\n\tif in.password[in.j-1] == in.char {\n\t\tcount++\n\t}\n\treturn count == 1\n}", "func (c *Connection) readInitPacket() error {\n\tvar packetHeader *PacketHeader\n\tvar err error\n\n\tpacketHeader, err = ReadPacketHeader(c.reader)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif packetHeader.Seq != 0 {\n\t\t// The sequence number of the initial packet must be a zero.\n\t\treturn errors.New(\"Unexpected Sequence Number\")\n\t}\n\n\tspew.Printf(\"=== packetHeader\\n\")\n\tspew.Dump(packetHeader)\n\n\t// ProtocolVersion [1 byte]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ProtocolVersion)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ProtocolVersion\\n\")\n\tspew.Dump(c.ProtocolVersion)\n\n\t// ServerVersion [null terminated string]\n\tc.ServerVersion, err = c.reader.ReadString('\\x00')\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ServerVersion\\n\")\n\tspew.Dump(c.ServerVersion)\n\n\t// ConnectionID [4 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ConnectionID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ConnectionID\\n\")\n\tspew.Dump(c.ConnectionID)\n\n\t// ScramblePart1 [8 bytes]\n\tc.ScramblePart1 = make([]byte, 8)\n\n\terr = ReadPacket(c.reader, c.ScramblePart1[0:8])\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ScramblePart1\\n\")\n\tspew.Dump(c.ScramblePart1)\n\n\t// Reserved byte [1 byte]\n\tIgnoreBytes(c.reader, 1)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerCapabilitiesPart1 (lower 2 bytes) [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerCapabilitiesPart1)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerDefaultCollation [1 byte]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerDefaultCollation)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// StatusFlags [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.StatusFlags)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerCapabilitiesPart2 (upper 2 bytes) [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerCapabilitiesPart2)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// LenOfScramblePart2 [1 byte]\n\t//err = binary.Read(c.reader, binary.LittleEndian, &c.LenOfScramblePart2)\n\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t//spew.Dump(c.LenOfScramblePart2)\n\n\t// PLUGIN_AUTH [1 byte]\n\t// Filler [6 bytes]\n\t// Filler [4 bytes]\n\tIgnoreBytes(c.reader, 1+6+4)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ScramblePart2 [12 bytes]\n\t// The web documentation is ambiguous about the length.\n\t// Reference:\n\t// https://github.com/go-sql-driver/mysql/blob/master/packets.go\n\tc.ScramblePart2 = make([]byte, 12)\n\n\terr = ReadPacket(c.reader, c.ScramblePart2[0:12])\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ScramblePart2\\n\")\n\tspew.Dump(c.ScramblePart2)\n\n\t// ScramblePart2 0x00\n\tIgnoreBytes(c.reader, 1)\n\n\t// AuthenticationPluginName [null terminated string]\n\tc.AuthenticationPluginName, err = c.reader.ReadString('\\x00')\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== AuthenticationPluginName\\n\")\n\tspew.Dump(c.AuthenticationPluginName)\n\tspew.Dump([]byte(c.AuthenticationPluginName))\n\n\t//\n\treturn nil\n}", "func MakeSRPVerifier(b string) (*SRP, *Verifier, error) {\n\tv := strings.Split(b, \":\")\n\tif len(v) != 4 {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: malformed fields exp 4, saw %d\", len(v))\n\t}\n\n\t/*ss := v[0]\n\tsz, err := strconv.Atoi(ss)\n\tif err != nil || sz <= 0 {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: malformed field size %s\", ss)\n\t}\n\n\tss = v[1]\n\tp, ok := big.NewInt(0).SetString(ss, 16)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: malformed prime %s\", ss)\n\t}\n\n\tss = v[2]\n\tg, ok := big.NewInt(0).SetString(ss, 16)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: malformed generator %s\", ss)\n\t}\n\n\tss = v[3]\n\th, err := strconv.Atoi(ss)\n\tif err != nil || h <= 0 {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: malformed hash type %s\", ss)\n\t}\n\n\thf := crypto.Hash(h)\n\tif !hf.Available() {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: hash algorithm %d unavailable\", h)\n\t}*/\n\n\tss := v[0]\n\ti, err := hex.DecodeString(ss)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: invalid identity: %s\", ss)\n\t}\n\n\tss = v[1]\n\ts, err := hex.DecodeString(ss)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: invalid salt: %s\", ss)\n\t}\n\n\tss = v[2]\n\tvx, err := hex.DecodeString(ss)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"verifier: invalid verifier: %s\", ss)\n\t}\n\n\tss = v[3]\n\tver, err := strconv.Atoi(ss)\n\tif err != nil || ver <= 0 {\n\t\treturn nil, nil, fmt.Errorf(\"malformed version: %v\", ss)\n\t}\n\tsr := versionMap[int32(ver)]\n\t/*sr := &SRP{\n\t\th: hf,\n\t\tpf: &primeField{\n\t\t\tn: sz,\n\t\t\tN: p,\n\t\t\tg: g,\n\t\t},\n\t}*/\n\n\tvf := &Verifier{\n\t\tver: int32(ver),\n\t\ti: i,\n\t\ts: s,\n\t\tv: vx,\n\t\th: sr.h,\n\t\tpf: sr.pf,\n\t}\n\n\treturn sr, vf, nil\n}", "func (s Sentence) validate(parse_err error) error {\n\tidentifiers := []string{\n\t\t\"ABVD\", \"ADVD\", \"AIVD\", \"ANVD\", \"ARVD\",\n\t\t\"ASVD\", \"ATVD\", \"AXVD\", \"BSVD\", \"SAVD\",\n\t} // last is M for over the air, O from ourself/ownship (kystverket transmits a few of those)\n\tif parse_err != nil {\n\t\treturn parse_err\n\t}\n\tvalid := false\n\tfor _, id := range identifiers {\n\t\tif string(s.identifier[:4]) == id {\n\t\t\tvalid = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !valid || (s.identifier[4] != byte('M') && s.identifier[4] != byte('O')) {\n\t\treturn fmt.Errorf(\"Unrecognized identifier: %s\", s.identifier)\n\t} else if s.part_index >= s.parts { // unly used if parts != 1\n\t\treturn fmt.Errorf(\"part is not a digit or too high\")\n\t} else if s.smid_i > 10 { // only used if parts != 1\n\t\treturn fmt.Errorf(\"smid is not a digit but %c\", s.smid_b)\n\t} else if s.Padding > 5 { // sometimes 6, only used for messages we want to decode\n\t\treturn fmt.Errorf(\"padding is not a digit but %c\", byte(s.Padding)+byte('0'))\n\t} else if s.smid_b == byte('*') && s.parts != 1 { // pretty common\n\t\treturn fmt.Errorf(\"multipart message without smid\")\n\t} else if s.smid_b != byte('*') && s.parts == 1 { // pretty common\n\t\treturn fmt.Errorf(\"standalone sentence with smid\")\n\t} else if s.smid_b != byte('*') && s.smid_i == 10 {\n\t\treturn fmt.Errorf(\"smid is kinda wrong: %c\", s.smid_b)\n\t} else if s.channel != byte('A') && s.channel != byte('B') {\n\t\tif s.channel == byte('1') || s.channel == byte('2') {\n\t\t\ts.channel = s.channel - byte('1') + byte('A')\n\t\t} else if s.channel != byte('*') {\n\t\t\treturn fmt.Errorf(\"Unrecognized channel: %c\", s.channel)\n\t\t}\n\t} else if s.Padding < byte('0') || s.Padding > byte('9') {\n\t\treturn fmt.Errorf(\"padding is not a number but %c\", s.Padding)\n\t}\n\temptySmid := 0\n\tif s.smid_b == byte('*') {\n\t\temptySmid = 1\n\t}\n\tempty := emptySmid\n\tif s.channel == byte('*') {\n\t\tempty++\n\t}\n\t// The parser doesn't check if there is a comma when the preceeding value is fixed width.\n\tfor n, at := range []int{0, 6, 8, 10, 12 - emptySmid, 14 - empty, -7, -5, -2, -1} {\n\t\texpect := []byte(\"!,,,,,,*\\r\\n\")[n]\n\t\tif at < 0 {\n\t\t\tat += len(s.Text)\n\t\t}\n\t\tif s.Text[at] != expect {\n\t\t\treturn fmt.Errorf(\"Expected '%c' at index %d, got '%c'. (channel: %c)\",\n\t\t\t\texpect, at, s.Text[at], s.channel)\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Rfm12b) read() {\n\n\tdev, err := rs232.Open(r.portName, rs232.Options{BitRate: r.baud, DataBits: 8, StopBits: 1})\n\tgotError(err)\n\tr.device = dev\n\tdefer dev.Close()\n\n\tlineScanner := bufio.NewScanner(r.device)\n\tfor lineScanner.Scan() {\n\n\t\tvar out []byte\n\t\tline := lineScanner.Text()\n\t\toa := strings.Split(line, ` `)\n\n\t\t// If Logging path is proved Log output to logger\n\t\tif r.loggerPath != \"\" {\n\t\t\tr.logger.Log(line)\n\t\t}\n\n\t\t//If msgs are valid pass to channel -minus the \"OK\"\n\t\tif oa[0] == \"OK\" {\n\t\t\tfor i := 1; i < len(oa); i++ {\n\t\t\t\tv, err := strconv.ParseInt(oa[i], 10, 16)\n\t\t\t\tif err == nil {\n\t\t\t\t\t//Added this code to remove CTL, DST and Ack bits from header. 24/01/15\n\t\t\t\t\tif i == 1 {\n\t\t\t\t\t\tv = int64(byte(v) & 0x1F)\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, byte(v))\n\t\t\t\t}\n\t\t\t}\n\t\t\tr.chOut <- out\n\t\t}\n\t}\n\tgotError(lineScanner.Err())\n}", "func Handshake(code int) []string {\n\tif code <= 0 || code > 31 {\n\t\t// Unsupported inputs\n\t\treturn nil\n\t}\n\t// For determining order of secret handshake steps\n\tvar start int\n\tvar end int\n\tvar increment int\n\tif code&16 > 0 {\n\t\t// 10000 = Reversed order\n\t\tstart = 3\n\t\tend = -1\n\t\tincrement = -1\n\t} else {\n\t\t// Normal order\n\t\tstart = 0\n\t\tend = 4\n\t\tincrement = 1\n\t}\n\t// Now append handshake steps in previously determined order\n\tvar secretHandshake []string\n\tfor i := start; i != end; i += increment {\n\t\tvar step string\n\t\tswitch i {\n\t\tcase 0:\n\t\t\tstep = \"wink\"\n\t\tcase 1:\n\t\t\tstep = \"double blink\"\n\t\tcase 2:\n\t\t\tstep = \"close your eyes\"\n\t\tcase 3:\n\t\t\tstep = \"jump\"\n\t\t}\n\t\t// Test ith bit with respect to bit positions ...3210\n\t\ttestBitmap := getTestBitmap(i)\n\t\tif code&testBitmap > 0 {\n\t\t\tsecretHandshake = append(secretHandshake, step)\n\t\t}\n\t}\n\treturn secretHandshake\n}", "func Read4(\n\tconn *websocket.Conn,\n\tnetworkKey,\n\tsecretab,\n\tsecretaB,\n\tsecretAb,\n\tclientLongTermPublicIdentity,\n\tserverLongTermPublicIdentity [32]byte,\n\tsignatureA []byte) (msg4, finalKey []byte, success bool) {\n\t// detached_signature_B = assert_nacl_secretbox_open(\n\t// ciphertext: msg4,\n\t// nonce: 24_bytes_of_zeros,\n\t// key: sha256(\n\t// concat(\n\t// \t network_identifier,\n\t// \t shared_secret_ab,\n\t// \t shared_secret_aB,\n\t// \t shared_secret_Ab\n\t// \t )\n\t// )\n\t// )\n //\n\t// assert_nacl_sign_verify_detached(\n\t// sig: detached_signature_B,\n\t// msg: concat(\n\t// \t network_identifier,\n\t// \t detached_signature_A,\n\t// \t client_longterm_pk,\n\t// \t sha256(shared_secret_ab)\n\t// ),\n\t// key: server_longterm_pk\n\t// )\n\n\t_, msg4, err := conn.ReadMessage()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tconn.Close()\n\t\treturn nil, nil, false\n\t}\n\tif len(msg4) != 80 {\n\t\tlog.Printf(\"handshake read: fail length, must be 80 bytes\\n\")\n\t\tconn.Close()\n\t\treturn nil, nil, false\n\t}\n\n\t// calculate naclbox key\n\th := sha256.New()\n\th.Write(networkKey[:])\n\th.Write(secretab[:])\n\th.Write(secretaB[:])\n\th.Write(secretAb[:])\n\tfinalKey = h.Sum(nil)\n\tkey := [32]byte{}\n\tcopy(key[:], finalKey)\n\n\t// nonce\n\tnonce := [24]byte{}\n\n\t// open box msg4, using nonce and key, reveiling sigB \n\tserverSignatureB := []byte{}\n\tserverSignatureB, ok := box.OpenAfterPrecomputation(serverSignatureB, msg4, &nonce, &key)\n\tif !ok {\n\t\tlog.Printf(\"open box fail\\n\")\n\t\tconn.Close()\n\t\treturn nil, nil, false\n\t}\n\t// verify server signature\n\tmsg := append(networkKey[:], signatureA...)\n\tmsg = append(msg, clientLongTermPublicIdentity[:]...)\n\th = sha256.New()\n\th.Write(secretab[:])\n\tmsg = append(msg, h.Sum(nil)...)\n\tok = ed25519.Verify(serverLongTermPublicIdentity[:], msg, serverSignatureB)\n\tif !ok {\n\t\tlog.Printf(\"ed25519 verify server signature fail\\n\")\n\t\tconn.Close()\n\t\treturn nil, nil, false\n\t}\n\treturn msg4, finalKey, true\n}", "func SetupDecode(r io.Reader) (string, error) {\n\tb := make([]byte, LenTotal)\n\n\tif n, _ := r.Read(b); n != LenTotal {\n\t\treturn \"\", fmt.Errorf(\"did not receive the correct amount of info, got %d, want %d\", n, LenTotal)\n\t}\n\tif !uuidRE.Match(b) {\n\t\treturn \"\", fmt.Errorf(\"did not contain a valid UUIDv4\")\n\t}\n\treturn string(b), nil\n}", "func (s *udtSocket) checkValidHandshake(m *multiplexer, p *packet.HandshakePacket, from *net.UDPAddr) bool {\n\tif s.udtVer != 4 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (pr *PJProjector) checkAuthentication(response []string) (seed string) {\n\tif response[0] != \"PJLINK\" {\n\t\treturn \"\"\n\t}\n\tif response[1] == \"0\" {\n\t\treturn \"\"\n\t} else if response[1] == \"1\" {\n\t\treturn response[2]\n\t}\n\n\treturn \"\"\n}", "func validate1(in line) bool {\n\tcount := 0\n\tfor i := 0; i < len(in.password); i++ {\n\t\tif in.password[i] == in.char {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count >= in.i && count <= in.j\n}", "func authenticateUsernamePassword(conn *socks5ClientConn, authenticator authenticator.Authenticator) bool {\n\t/* https://tools.ietf.org/html/rfc1929#section-2\n\n\t2. Initial negotiation\n\n\t Once the SOCKS V5 server has started, and the client has selected the\n\t Username/Password Authentication protocol, the Username/Password\n\t subnegotiation begins. This begins with the client producing a\n\t Username/Password request:\n\n\t +----+------+----------+------+----------+\n\t |VER | ULEN | UNAME | PLEN | PASSWD |\n\t +----+------+----------+------+----------+\n\t | 1 | 1 | 1 to 255 | 1 | 1 to 255 |\n\t +----+------+----------+------+----------+\n\n\t The VER field contains the current version of the subnegotiation,\n\t which is X'01'. The ULEN field contains the length of the UNAME field\n\t that follows. The UNAME field contains the username as known to the\n\t source operating system. The PLEN field contains the length of the\n\t PASSWD field that follows. The PASSWD field contains the password\n\t association with the given UNAME.\n\n\t The server verifies the supplied UNAME and PASSWD, and sends the\n\t following response:\n\n\t +----+--------+\n\t |VER | STATUS |\n\t +----+--------+\n\t | 1 | 1 |\n\t +----+--------+\n\n\t A STATUS field of X'00' indicates success. If the server returns a\n\t `failure' (STATUS value other than X'00') status, it MUST close the\n\t connection.\n\n\t*/\n\n\tverLen := make([]uint8, 2)\n\tn, _ := io.ReadFull(conn, verLen)\n\tconn.AddRead(int64(n))\n\tif n != len(verLen) {\n\t\treturn false\n\t}\n\n\tif verLen[0] != 0x01 {\n\t\treturn false\n\t}\n\n\tusernameLen := make([]uint8, verLen[1]+1)\n\tn, _ = io.ReadFull(conn, usernameLen)\n\tconn.AddRead(int64(n))\n\tif n != len(usernameLen) {\n\t\treturn false\n\t}\n\n\tpassword := make([]uint8, usernameLen[verLen[1]])\n\tn, _ = io.ReadFull(conn, password)\n\tconn.AddRead(int64(n))\n\tif n != len(password) {\n\t\treturn false\n\t}\n\n\tok := authenticator.Authenticate(string(usernameLen[0:len(usernameLen)-1]), string(password), conn.GetClientAddr(), conn.GetInternalAddr())\n\n\tif ok {\n\t\tn, _ = conn.Write([]byte{0x01, 0x00})\n\t\tconn.AddWritten(int64(n))\n\t\treturn true\n\t}\n\n\tn, _ = conn.Write([]byte{0x01, 0x01})\n\tconn.AddWritten(int64(n))\n\treturn false\n}", "func HKRegisterResetPassword(username string, phoneNumber string, newPassWD string) (s1 string, err error) {\n\t// nhập số phone , và password lưu tạm\n\totpPhone, err := dataCenter.GetOtpPhone()\n\tif err != nil {\n\t\tlog.LogSerious(\"err insert otp_code %v,phoneNumber %v\", err, phoneNumber)\n\t\treturn \"\", errors.New(\"Hệ thông hiện đang nâng cấp tính năng này!\")\n\t}\n\tphoneNumber = utils.NormalizePhoneNumber(phoneNumber)\n\tfmt.Println(phoneNumber)\n\tplayerInstance := player.FindPlayerWithPhoneNumber(phoneNumber)\n\tif playerInstance == nil {\n\t\treturn \"\", errors.New(\"Số điện thoại này không có trong hệ thống\")\n\t}\n\n\tif !playerInstance.IsVerify() {\n\t\treturn \"\", errors.New(\"Bạn chưa xác nhận số điện thoại này\")\n\t}\n\tif strings.ToLower(playerInstance.Username()) != strings.ToLower(username) {\n\t\treturn \"\", errors.New(\"Tên đăng nhập và số điện thoại không khớp!\")\n\t}\n\totp := hkCanRequestNewOtpCode(playerInstance.Id())\n\tif otp != \"\" {\n\t\treturn fmt.Sprintf(\"sms:%s?body=%s\", otpPhone, otp),\n\t\t\terrors.New(fmt.Sprintf(\"Để đặt lại mật khẩu bạn vui lòng gửi tin nhắn %s đến số điện thoại %s!\", otp, otpPhone))\n\t}\n\tplayerInstance.SetNewPassWD(newPassWD)\n\t//player.newPasswd = newPassWD\n\totpCodeString := utils.RandSeqLowercase(4)\n\n\trow := dataCenter.Db().QueryRow(\"INSERT INTO otp_code (player_id, phone_number, reason, otp_code, status, expired_at, created_at,passwd) \"+\n\t\t\" VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id\",\n\t\tplayerInstance.Id(),\n\t\tphoneNumber,\n\t\t\"reset_password\",\n\t\totpCodeString,\n\t\tkStatusWaitingForUser,\n\t\ttime.Now().Add(game_config.OtpExpiredAfter()).UTC(), time.Now().UTC(),\n\t\tnewPassWD)\n\tvar id int64\n\terr = row.Scan(&id)\n\tif err != nil {\n\t\tlog.LogSerious(\"err insert otp_code %v,playerId %d\", err, playerInstance.Id())\n\t\treturn \"\", errors.New(\"Hệ thông hiện đang nâng cấp tính năng này!\")\n\t}\n\n\treturn fmt.Sprintf(\"sms:%s?body=%s\", otpPhone, otpCodeString),\n\t\terrors.New(fmt.Sprintf(\"Để đặt lại mật khẩu bạn vui lòng gửi tin nhắn %s đến số điện thoại %s!\", otpCodeString, otpPhone))\n}", "func decode(packet []byte) (interface{}, error) {\n\tvar msg interface{}\n\tswitch packet[0] {\n\tcase msgDisconnect:\n\t\tmsg = new(disconnectMsg)\n\tcase msgServiceRequest:\n\t\tmsg = new(serviceRequestMsg)\n\tcase msgServiceAccept:\n\t\tmsg = new(serviceAcceptMsg)\n\tcase msgExtInfo:\n\t\tmsg = new(extInfoMsg)\n\tcase msgKexInit:\n\t\tmsg = new(kexInitMsg)\n\tcase msgKexDHInit:\n\t\tmsg = new(kexDHInitMsg)\n\tcase msgKexDHReply:\n\t\tmsg = new(kexDHReplyMsg)\n\tcase msgUserAuthRequest:\n\t\tmsg = new(userAuthRequestMsg)\n\tcase msgUserAuthSuccess:\n\t\treturn new(userAuthSuccessMsg), nil\n\tcase msgUserAuthFailure:\n\t\tmsg = new(userAuthFailureMsg)\n\tcase msgUserAuthPubKeyOk:\n\t\tmsg = new(userAuthPubKeyOkMsg)\n\tcase msgGlobalRequest:\n\t\tmsg = new(globalRequestMsg)\n\tcase msgRequestSuccess:\n\t\tmsg = new(globalRequestSuccessMsg)\n\tcase msgRequestFailure:\n\t\tmsg = new(globalRequestFailureMsg)\n\tcase msgChannelOpen:\n\t\tmsg = new(channelOpenMsg)\n\tcase msgChannelData:\n\t\tmsg = new(channelDataMsg)\n\tcase msgChannelOpenConfirm:\n\t\tmsg = new(channelOpenConfirmMsg)\n\tcase msgChannelOpenFailure:\n\t\tmsg = new(channelOpenFailureMsg)\n\tcase msgChannelWindowAdjust:\n\t\tmsg = new(windowAdjustMsg)\n\tcase msgChannelEOF:\n\t\tmsg = new(channelEOFMsg)\n\tcase msgChannelClose:\n\t\tmsg = new(channelCloseMsg)\n\tcase msgChannelRequest:\n\t\tmsg = new(channelRequestMsg)\n\tcase msgChannelSuccess:\n\t\tmsg = new(channelRequestSuccessMsg)\n\tcase msgChannelFailure:\n\t\tmsg = new(channelRequestFailureMsg)\n\tcase msgUserAuthGSSAPIToken:\n\t\tmsg = new(userAuthGSSAPIToken)\n\tcase msgUserAuthGSSAPIMIC:\n\t\tmsg = new(userAuthGSSAPIMIC)\n\tcase msgUserAuthGSSAPIErrTok:\n\t\tmsg = new(userAuthGSSAPIErrTok)\n\tcase msgUserAuthGSSAPIError:\n\t\tmsg = new(userAuthGSSAPIError)\n\tdefault:\n\t\treturn nil, unexpectedMessageError(0, packet[0])\n\t}\n\tif err := Unmarshal(packet, msg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn msg, nil\n}", "func echo(port serial.Port) bool {\n\n\tsend := make([]byte, 32)\n\tsend[0] = 0xaa\n\tsend[1] = 0x55\n\tsend[2] = 0x01\n\tsend[3] = 0x00\n\tsend[4] = 0x00\n\tsend[5] = 0xF0\n\tsend[6] = 0x80\n\tret := util.CRC16(send, 7)\n\tsend[7] = byte((ret >> 8) & 0xff)\n\tsend[8] = byte(ret & 0xff)\n\n\tn, err := port.Write(send[:9])\n\tif err != nil || n != 9 {\n\t\tlog.Info(err)\n\t\treturn false\n\t}\n\treturn true\n\t//fmt.Printf(\"Handshake echo, % d bytes:% X \\n\", n, send[:9])\n}", "func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\r\n\tvar output string\r\n\tmsg := validateInvoiceDetails(stub, args)\r\n\r\n\tif msg == \"\" {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\r\n\t} else {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\r\n\t}\r\n\treturn []byte(output)\r\n}", "func (hdr msgHdr) verify(buf []byte) error {\n\tif (hdr.Magic != NETMAGIC) {\n\t\tfmt.Printf(\"Unmatched magic number 0x%d\\n\", hdr.Magic)\n\t\treturn errors.New(\"Unmatched magic number\")\n\t}\n\n\tcheckSum := checkSum(buf)\n\tif (bytes.Equal(hdr.Checksum[:], checkSum[:]) == false) {\n\t\tstr1 := hex.EncodeToString(hdr.Checksum[:])\n\t\tstr2 := hex.EncodeToString(checkSum[:])\n\t\tfmt.Printf(\"Message Checksum error, Received checksum %s Wanted checksum: %s\\n\",\n\t\t\tstr1, str2)\n\t\treturn errors.New(\"Message Checksum error\")\n\t}\n\n\treturn nil\n}", "func JCBCard(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\n\ts = stripNonNumeric(s)\n\n\tif len(s) != 15 && len(s) != 16 {\n\t\treturn false\n\t}\n\n\tif s[0:4] != \"2131\" && s[0:4] != \"1800\" && s[0:2] != \"35\" {\n\t\treturn false\n\t}\n\n\tif (s[0:4] == \"2131\" || s[0:4] == \"1800\") && len(s) != 15 {\n\t\treturn false\n\t}\n\n\tif s[0:2] == \"35\" && len(s) != 16 {\n\t\treturn false\n\t}\n\n\treturn luhn(s)\n}", "func MasterCard(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\n\ts = stripNonNumeric(s)\n\n\tif len(s) != 16 {\n\t\treturn false\n\t}\n\n\tft, _ := strconv.Atoi(s[0:2])\n\tff, _ := strconv.Atoi(s[0:4])\n\n\tif s[0:1] != \"5\" && (55 < ft || ft < 51) && (2720 < ff || ft < 2221) {\n\t\treturn false\n\t}\n\n\treturn luhn(s)\n}", "func(t* SimpleChaincode) consignmentDetail(stub shim.ChaincodeStubInterface,args []string) pb.Response {\n \n var err error\n if len(args) != 20 {\n return shim.Error(\" hi Incorrect number of arguments. Expecting 20\")\n }\n //input sanitation\n fmt.Println(\"- start filling policy detail\")\n if len(args[0])<= 0{\n return shim.Error(\"1st argument must be a non-empty string\")\n }\n if len(args[1]) <= 0 {\n return shim.Error(\"2st argument must be a non-empty string\")\n }\n if len(args[2]) <= 0 {\n return shim.Error(\"3rd argument must be a non-empty string\")\n }\n if len(args[3]) <= 0 {\n return shim.Error(\"4th argument must be a non-empty string\")\n }\n if len(args[4]) <= 0 {\n return shim.Error(\"5th argument must be a non-empty string\")\n }\n if len(args[5]) <= 0{\n return shim.Error(\"6th argument must be a non-empty string\")\n }\n if len(args[6]) <= 0{\n return shim.Error(\"7th argument must be a non-empty string\")\n }\n if len(args[7]) <= 0{\n return shim.Error(\"8th argument must be a non-empty string\")\n }\n if len(args[8]) <= 0{\n return shim.Error(\"9th argument must be a non-empty string\")\n }\n if len(args[9]) <= 0{\n return shim.Error(\"10th argument must be a non-empty string\")\n }\n if len(args[10]) <= 0{\n return shim.Error(\"11th argument must be a non-empty string\")\n }\n if len(args[11]) <= 0{\n return shim.Error(\"12th argument must be a non-empty string\")\n }\n if len(args[12]) <= 0{\n return shim.Error(\"13th argument must be a non-empty string\")\n }\n if len(args[13]) <= 0{\n return shim.Error(\"14th argument must be a non-empty string\")\n }\n if len(args[14]) <= 0{\n return shim.Error(\"15th argument must be a non-empty string\")\n }\n if len(args[15]) <= 0{\n return shim.Error(\"16th argument must be a non-empty string\")\n }\n\tif len(args[16]) <= 0{\n return shim.Error(\"17th argument must be a non-empty string\")\n }\n if len(args[17]) <= 0{\n return shim.Error(\"18th argument must be a non-empty string\")\n }\n if len(args[18]) <= 0{\n return shim.Error(\"19th argument must be a non-empty string\")\n }\n if len(args[19]) <= 0{\n return shim.Error(\"20th argument must be a non-empty string\")\n }\n \n consignment:=Consignment{}\n consignment.UserId = args[0]\n \n \n consignment.ConsignmentWeight, err = strconv.Atoi(args[1])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentWeight as cannot convert it to int\")\n }\n consignment.ConsignmentValue, err = strconv.Atoi(args[2])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentValue as cannot convert it to int\")\n }\n consignment.PolicyName=args[3]\n fmt.Println(\"consignment\", consignment)\n consignment.SumInsured, err = strconv.Atoi(args[4])\n if err != nil {\n return shim.Error(\"Failed to get SumInsured as cannot convert it to int\")\n }\n consignment.PremiumAmount, err = strconv.Atoi(args[5])\n if err != nil {\n return shim.Error(\"Failed to get Arun as cannot convert it to int\")\n }\n \n consignment.ModeofTransport=args[6]\n fmt.Println(\"consignment\", consignment)\n consignment.PackingMode=args[7]\n fmt.Println(\"consignment\", consignment)\n consignment.ConsignmentType=args[8]\n fmt.Println(\"consignment\", consignment)\n consignment.ContractType=args[9]\n fmt.Println(\"consignment\", consignment)\n consignment.PolicyType=args[10]\n fmt.Println(\"consignment\", consignment)\n \n consignment.Email=args[11]\n fmt.Println(\"consignment\", consignment)\n \n consignment.PolicyHolderName=args[12]\n fmt.Println(\"consignment\", consignment)\n consignment.UserType=args[13]\n fmt.Println(\"consignment\", consignment)\n consignment.InvoiceNo, err = strconv.Atoi(args[14])\n if err != nil {\n return shim.Error(\"Failed to get InvoiceNo as cannot convert it to int\")\n }\n consignment.PolicyNumber, err = strconv.Atoi(args[15])\n if err != nil {\n return shim.Error(\"Failed to get PolicyNumber as cannot convert it to int\")\n }\n\tconsignment.PolicyIssueDate = args[16]\n\tconsignment.PolicyEndDate = args[17]\n\tconsignment.VoyageStartDate = args[18]\n\tconsignment.VoyageEndDate = args[19]\n \n consignmentAsBytes, err := stub.GetState(\"getconsignment\")\n if err != nil {\n return shim.Error(\"Failed to get consignment\")\n }\n \n var allconsignment AllConsignment\n json.Unmarshal(consignmentAsBytes, &allconsignment) //un stringify it aka JSON.parse()\n allconsignment.Consignmentlist = append(allconsignment.Consignmentlist, consignment)\n fmt.Println(\"allconsignment\", allconsignment.Consignmentlist) //append to allconsignment\n fmt.Println(\"! appended policy to allconsignment\")\n \n jsonAsBytes, _ := json.Marshal(allconsignment)\n fmt.Println(\"json\", jsonAsBytes)\n err = stub.PutState(\"getconsignment\", jsonAsBytes) //rewrite allconsignment\n if err != nil {\n return shim.Error(err.Error())\n }\n \n fmt.Println(\"- end of the consignmentdetail\")\n return shim.Success(nil)\n \n}", "func checkDecode(input string, curve CurveID) (result []byte, err error) {\n\tdecoded := base58.Decode(input)\n\tif len(decoded) < 5 {\n\t\treturn nil, fmt.Errorf(\"invalid format\")\n\t}\n\tvar cksum [4]byte\n\tcopy(cksum[:], decoded[len(decoded)-4:])\n\t///// WARN: ok the ripemd160checksum should include the prefix in CERTAIN situations,\n\t// like when we imported the PubKey without a prefix ?! tied to the string representation\n\t// or something ? weird.. checksum shouldn't change based on the string reprsentation.\n\tif bytes.Compare(ripemd160checksum(decoded[:len(decoded)-4], curve), cksum[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid checksum\")\n\t}\n\t// perhaps bitcoin has a leading net ID / version, but EOS doesn't\n\tpayload := decoded[:len(decoded)-4]\n\tresult = append(result, payload...)\n\treturn\n}", "func validateUserStr(prefix []byte, userFAddr string) bool {\n\tif len(userFAddr) != 52 {\n\t\treturn false\n\n\t}\n\tv := base58.Decode(userFAddr)\n\tif bytes.Compare(prefix, v[:2]) != 0 {\n\t\treturn false\n\n\t}\n\tsha256d := Sha(Sha(v[:34]).Bytes()).Bytes()\n\tif bytes.Compare(sha256d[:4], v[34:]) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func TestMsgParseTortureWsinv(t *testing.T) {\n\tstr := \"INVITE sip:[email protected];unknownparam SIP/2.0\\r\\n\" +\n\t\t\"TO :\\r\\n sip:[email protected] ; tag = 1918181833n\\r\\n\" +\n\t\t`from : \"J Rosenberg \\\\\\\"\" <sip:[email protected]>` +\n\t\t\"\\r\\n ;\\r\\n\" +\n\t\t\" tag = 98asjd8\\r\\n\" +\n\t\t\"MaX-fOrWaRdS: 0068\\r\\n\" +\n\t\t\"Call-ID: [email protected]\\r\\n\" +\n\t\t\"Content-Length : 150\\r\\n\" +\n\t\t\"cseq: 0009\\r\\n\" +\n\t\t\" INVITE\\r\\n\" +\n\t\t\"Via : SIP / 2.0\\r\\n\" +\n\t\t\" /UDP\\r\\n 192.0.2.2;branch=390skdjuw\\r\\n\" +\n\t\t\"s :\\r\\n\" +\n\t\t\"NewFangledHeader: newfangled value\\r\\n\" +\n\t\t\" continued newfangled value\\r\\n\" +\n\t\t\"UnknownHeaderWithUnusualValue: ;;,,;;,;\\r\\n\" +\n\t\t\"Content-Type: application/sdp\\r\\n\" +\n\t\t\"Route:\\r\\n\" +\n\t\t\" <sip:services.example.com;lr;unknownwith=value;unknown-no-value>\\r\\n\" +\n\t\t\"v: SIP / 2.0 / TCP spindle.example.com ;\\r\\n\" +\n\t\t\" branch = z9hG4bK9ikj8 ,\\r\\n\" +\n\t\t\" SIP / 2.0 / UDP 192.168.255.111 ; branch=\\r\\n\" +\n\t\t\" z9hG4bK30239\\r\\n\" +\n\t\t`m:\"Quoted string \\\"\\\"\" <sip:[email protected]> ; newparam =` +\n\t\t\"\\r\\n newvalue ;\\r\\n\" +\n\t\t\" secondparam ; q = 0.33\\r\\n\\r\\n\"\n\tmsg, err := MsgParse([]byte(str))\n\tassert.Nil(t, err)\n\tassert.True(t, msg.IsRequest())\n\tassert.Equal(t, \"sip:[email protected];unknownparam\",\n\t\tmsg.ReqLine.RequestURI())\n\tassert.Equal(t, \"sip:[email protected]\", msg.To.Addr())\n\tassert.Equal(t, \"1918181833n\", msg.To.Tag())\n\tassert.Equal(t, `\"J Rosenberg \\\\\\\"\"`, msg.From.DisplayName())\n\tassert.Equal(t, \"sip:[email protected]\", msg.From.Addr())\n\tassert.Equal(t, \"98asjd8\", msg.From.Tag())\n\tassert.EqualValues(t, 68, msg.MaxFwd)\n\tassert.EqualValues(t, 9, msg.CSeq.Num)\n\tassert.EqualValues(t, \"INVITE\", msg.CSeq.Method)\n\tassert.Equal(t, 3, msg.Vias.Count())\n\tassert.Equal(t, 1, msg.Routes.Count())\n\tassert.Equal(t, 1, msg.Contacts.Count())\n\tassert.Equal(t, \"sip:[email protected]\", msg.Contacts.First().Location())\n\n\th := msg.Headers.FindByName(\"s\")\n\tassert.NotNil(t, h)\n\tassert.Equal(t, \"\", h.Value())\n\n\th = msg.Headers.FindByName(\"NewFangledHeader\")\n\tassert.NotNil(t, h)\n\tassert.Equal(t, \"newfangled value\\r\\n continued newfangled value\", h.Value())\n\n\th = msg.Headers.FindByName(\"UnknownHeaderWithUnusualValue\")\n\tassert.NotNil(t, h)\n\tassert.Equal(t, \";;,,;;,;\", h.Value())\n\n\th = msg.Headers.FindByName(\"Content-type\")\n\tassert.NotNil(t, h)\n\tassert.Equal(t, \"application/sdp\", h.Value())\n\n\th = msg.Headers.Find(SIPHdrCSeq)\n\tassert.NotNil(t, h)\n\tassert.Equal(t, \"0009\\r\\n INVITE\", h.Value())\n\n\tassert.Equal(t, 14, msg.Headers.Count())\n}", "func TestSenderToReceiverSwiftLineSixAlphaNumeric(t *testing.T) {\n\tsr := mockSenderToReceiver()\n\tsr.CoverPayment.SwiftLineSix = \"®\"\n\n\terr := sr.Validate()\n\n\trequire.EqualError(t, err, fieldError(\"SwiftLineSix\", ErrNonAlphanumeric, sr.CoverPayment.SwiftLineSix).Error())\n}", "func (s *ESSHKexinitRecord) decodeFromBytes(data []byte, pad uint8, df gopacket.DecodeFeedback) error {\n\tvar l uint32\n\t//fmt.Printf(\"cookie: %02x\\n\", data[0:16])\n\tbptr := uint32(16) // Skip cookie\n\n\t// kex_algorithms\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.KexAlgos = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// server_host_key_algorithms\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.ServerHostKeyAlgos = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// encryption_algorithms_client_to_server\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.CiphersClientServer = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// encryption_algorithms_server_to_client\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.CiphersServerClient = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// mac_algorithms_client_to_server\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.MACsClientServer = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// mac_algorithms_server_to_client\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.MACsServerClient = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// compression_algorithms_client_to_server\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.CompressionClientServer = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// compression_algorithms_server_to_client\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.CompressionServerClient = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// languages_client_to_server\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.LanguagesClientServer = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// languages_server_to_client\n\tl = binary.BigEndian.Uint32(data[bptr:(bptr + 4)])\n\tbptr += 4\n\tif l > 0 {\n\t\ts.LanguagesServerClient = string((data[bptr:(bptr + l)])[:])\n\t\tbptr += l\n\t}\n\n\t// first_kex_packet_follows\n\ts.FirstKexFollows = data[bptr] != 0\n\tbptr += 1\n\n\t// reserved, skip\n\tbptr += 4\n\n\t// Padding\n\tp := uint8(uint32(len(data)) - bptr)\n\tif p != pad {\n\t\treturn fmt.Errorf(\"Misaligned padding, expected %d, got %d\", pad, p)\n\t}\n\n\treturn nil\n}", "func inputIsValid(s string) bool {\n\tpattern := `^send [0-4]{1} `\n\tmatched, err := regexp.MatchString(pattern, s)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn matched\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 verify(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tif len(args) != 2 {\n\t\tmessage = \"NOTICE \" + channel + \" :ERROR: Invalid number of arguments\"\n\t} else {\n\t\tuname := args[0]\n\t\tpin := args[1]\n\t\treply := cmdDb.Cmd(\"get\", uname+\"Pin\")\n\t\tpinDb, err := (reply.Bytes())\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif string(pinDb) == pin {\n\t\t\tmessage += \"You are now verified as \" + uname\n\t\t\tcmdDb.Cmd(\"set\", uname+\"Host\", hostname)\n\t\t\tcmdDb.Cmd(\"set\", uname+\"Pin\", fmt.Sprintf(\"%06d\", rand.Intn(1000000)))\n\t\t} else {\n\t\t\tmessage += \"PIN does not match that of \" + uname\n\t\t}\n\t}\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func ValidBufferLength(l uint16, converted []byte) bool {\n\ttotal := uint16(11) //size of just framing in characters (colon, 2 len chars, 4 addr chars, 2 type chars, 2 checksum chars)\n\tif uint16(l) < total {\n\t\tprint(\"!bad buffer length, can't be smaller than\", total, \":\", l, \"\\n\")\n\t\treturn false\n\t}\n\ttotal += uint16(converted[0]) * 2\n\tif l != total {\n\t\tprint(\"!bad buffer length, expected \", total, \" but got\", l, \" based on \", total*2, \"\\n\")\n\t\treturn false\n\t}\n\treturn true\n}", "func authServerDialogSwitchData() []byte {\n\tresult := make([]byte, len(mysqlDialogMessage)+2)\n\tresult[0] = mysqlDialogAskPassword\n\twriteNullString(result, 1, mysqlDialogMessage)\n\treturn result\n}", "func ValidBufferLength(l uint16, converted []byte) bool {\n\ttotal := uint16(11) //size of just framing in characters (colon, 2 len chars, 4 addr chars, 2 type chars, 2 checksum chars)\n\tif uint16(l) < total {\n\t\tprint(\"!bad buffer length, can't be smaller than\", total, \":\", l, \"\\n\")\n\t\treturn false\n\t}\n\ttotal += uint16(converted[0]) * 2\n\tif l != total {\n\t\tprint(\"!bad buffer length, expected\", total, \"but got\", l, \" based on \", converted[0], \"\\n\")\n\t\treturn false\n\t}\n\treturn true\n}", "func DiscoverCard(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\n\ts = stripNonNumeric(s)\n\n\tif len(s) != 16 {\n\t\treturn false\n\t}\n\n\tif s[0:2] != \"65\" && s[0:4] != \"6011\" {\n\t\treturn false\n\t}\n\n\treturn luhn(s)\n}", "func (s *Samil) readNext() (msg message, err error) {\n\tstart := make([]byte, 2)\n\t_, err = io.ReadFull(s.conn, start)\n\tif err != nil {\n\t\treturn\n\t}\n\tif start[0] != 0x55 || start[1] != 0xaa {\n\t\tpanic(\"Invalid message, not starting with 55 aa bytes\")\n\t}\n\t_, err = io.ReadFull(s.conn, msg.header[:])\n\tif err != nil {\n\t\treturn\n\t}\n\tsizeBytes := make([]byte, 2)\n\t_, err = io.ReadFull(s.conn, sizeBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\tsize := int(binary.BigEndian.Uint16(sizeBytes))\n\tmsg.payload = make([]byte, size)\n\t_, err = io.ReadFull(s.conn, msg.payload)\n\tif err != nil {\n\t\treturn\n\t}\n\tchksumBytes := make([]byte, 2)\n\t_, err = io.ReadFull(s.conn, chksumBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\tchksum := int(binary.BigEndian.Uint16(chksumBytes))\n\tif chksum != checksum(start)+checksum(msg.header[:])+checksum(sizeBytes)+checksum(msg.payload) {\n\t\tpanic(\"Invalid message, incorrect checksum\")\n\t}\n\treturn\n}", "func (FileGenerated_zebra_test_go) ZebraSchemaInMsgpack2Format() []byte {\n\treturn []byte{\n\t\t0x85, 0xaa, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x61,\n\t\t0x74, 0x68, 0xb3, 0x62, 0x65, 0x6e, 0x63, 0x68, 0x5f, 0x7a,\n\t\t0x65, 0x62, 0x72, 0x61, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x2e,\n\t\t0x67, 0x6f, 0xad, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50,\n\t\t0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0xa6, 0x71, 0x73, 0x74,\n\t\t0x65, 0x73, 0x74, 0xad, 0x5a, 0x65, 0x62, 0x72, 0x61, 0x53,\n\t\t0x63, 0x68, 0x65, 0x6d, 0x61, 0x49, 0x64, 0x00, 0xa7, 0x53,\n\t\t0x74, 0x72, 0x75, 0x63, 0x74, 0x73, 0x81, 0xa9, 0x5a, 0x65,\n\t\t0x62, 0x72, 0x61, 0x44, 0x61, 0x74, 0x61, 0x82, 0xaa, 0x53,\n\t\t0x74, 0x72, 0x75, 0x63, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0xa9,\n\t\t0x5a, 0x65, 0x62, 0x72, 0x61, 0x44, 0x61, 0x74, 0x61, 0xa6,\n\t\t0x46, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x93, 0x86, 0xa3, 0x5a,\n\t\t0x69, 0x64, 0x00, 0xab, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x47,\n\t\t0x6f, 0x4e, 0x61, 0x6d, 0x65, 0xa6, 0x55, 0x73, 0x65, 0x72,\n\t\t0x69, 0x64, 0xac, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x54, 0x61,\n\t\t0x67, 0x4e, 0x61, 0x6d, 0x65, 0xa6, 0x55, 0x73, 0x65, 0x72,\n\t\t0x69, 0x64, 0xac, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x54, 0x79,\n\t\t0x70, 0x65, 0x53, 0x74, 0x72, 0xa9, 0x5a, 0x65, 0x62, 0x72,\n\t\t0x61, 0x55, 0x55, 0x49, 0x44, 0xad, 0x46, 0x69, 0x65, 0x6c,\n\t\t0x64, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x1b,\n\t\t0xad, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x46, 0x75, 0x6c, 0x6c,\n\t\t0x54, 0x79, 0x70, 0x65, 0x84, 0xa4, 0x4b, 0x69, 0x6e, 0x64,\n\t\t0x1b, 0xa3, 0x53, 0x74, 0x72, 0xa5, 0x41, 0x72, 0x72, 0x61,\n\t\t0x79, 0xa6, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x82, 0xa4,\n\t\t0x4b, 0x69, 0x6e, 0x64, 0x10, 0xa3, 0x53, 0x74, 0x72, 0xa2,\n\t\t0x31, 0x36, 0xa5, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x82, 0xa4,\n\t\t0x4b, 0x69, 0x6e, 0x64, 0x0c, 0xa3, 0x53, 0x74, 0x72, 0xa4,\n\t\t0x62, 0x79, 0x74, 0x65, 0x87, 0xa3, 0x5a, 0x69, 0x64, 0x01,\n\t\t0xab, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x47, 0x6f, 0x4e, 0x61,\n\t\t0x6d, 0x65, 0xa8, 0x55, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d,\n\t\t0x65, 0xac, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x54, 0x61, 0x67,\n\t\t0x4e, 0x61, 0x6d, 0x65, 0xa8, 0x55, 0x73, 0x65, 0x72, 0x6e,\n\t\t0x61, 0x6d, 0x65, 0xac, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x54,\n\t\t0x79, 0x70, 0x65, 0x53, 0x74, 0x72, 0xa6, 0x73, 0x74, 0x72,\n\t\t0x69, 0x6e, 0x67, 0xad, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x43,\n\t\t0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x17, 0xae, 0x46,\n\t\t0x69, 0x65, 0x6c, 0x64, 0x50, 0x72, 0x69, 0x6d, 0x69, 0x74,\n\t\t0x69, 0x76, 0x65, 0x02, 0xad, 0x46, 0x69, 0x65, 0x6c, 0x64,\n\t\t0x46, 0x75, 0x6c, 0x6c, 0x54, 0x79, 0x70, 0x65, 0x82, 0xa4,\n\t\t0x4b, 0x69, 0x6e, 0x64, 0x02, 0xa3, 0x53, 0x74, 0x72, 0xa6,\n\t\t0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x87, 0xa3, 0x5a, 0x69,\n\t\t0x64, 0x02, 0xab, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x47, 0x6f,\n\t\t0x4e, 0x61, 0x6d, 0x65, 0xa4, 0x4e, 0x6f, 0x74, 0x65, 0xac,\n\t\t0x46, 0x69, 0x65, 0x6c, 0x64, 0x54, 0x61, 0x67, 0x4e, 0x61,\n\t\t0x6d, 0x65, 0xa4, 0x4e, 0x6f, 0x74, 0x65, 0xac, 0x46, 0x69,\n\t\t0x65, 0x6c, 0x64, 0x54, 0x79, 0x70, 0x65, 0x53, 0x74, 0x72,\n\t\t0xa6, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0xad, 0x46, 0x69,\n\t\t0x65, 0x6c, 0x64, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72,\n\t\t0x79, 0x17, 0xae, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x50, 0x72,\n\t\t0x69, 0x6d, 0x69, 0x74, 0x69, 0x76, 0x65, 0x02, 0xad, 0x46,\n\t\t0x69, 0x65, 0x6c, 0x64, 0x46, 0x75, 0x6c, 0x6c, 0x54, 0x79,\n\t\t0x70, 0x65, 0x82, 0xa4, 0x4b, 0x69, 0x6e, 0x64, 0x02, 0xa3,\n\t\t0x53, 0x74, 0x72, 0xa6, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67,\n\t\t0xa7, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x73, 0x90,\n\t}\n}", "func TestSenderToReceiverSwiftLineFourAlphaNumeric(t *testing.T) {\n\tsr := mockSenderToReceiver()\n\tsr.CoverPayment.SwiftLineFour = \"®\"\n\n\terr := sr.Validate()\n\n\trequire.EqualError(t, err, fieldError(\"SwiftLineFour\", ErrNonAlphanumeric, sr.CoverPayment.SwiftLineFour).Error())\n}", "func (b *BitcoinClient) checkAuthentication(resStr string) error {\n\tif len(resStr) == 0 {\n\t\treturn ErrFailedAuthentication\n\t}\n\n\treturn nil\n}", "func keysFromPreMasterSecret11(preMasterSecret, clientRandom, serverRandom []byte, macLen, keyLen int) (masterSecret, clientMAC, serverMAC, clientKey, serverKey []byte) {\n\tvar seed [tlsRandomLength * 2]byte;\n\tbytes.Copy(seed[0:len(clientRandom)], clientRandom);\n\tbytes.Copy(seed[len(clientRandom):len(seed)], serverRandom);\n\tmasterSecret = make([]byte, masterSecretLength);\n\tpRF11(masterSecret, preMasterSecret, masterSecretLabel, seed[0:len(seed)]);\n\n\tbytes.Copy(seed[0:len(clientRandom)], serverRandom);\n\tbytes.Copy(seed[len(serverRandom):len(seed)], clientRandom);\n\n\tn := 2*macLen + 2*keyLen;\n\tkeyMaterial := make([]byte, n);\n\tpRF11(keyMaterial, masterSecret, keyExpansionLabel, seed[0:len(seed)]);\n\tclientMAC = keyMaterial[0:macLen];\n\tserverMAC = keyMaterial[macLen : macLen*2];\n\tclientKey = keyMaterial[macLen*2 : macLen*2+keyLen];\n\tserverKey = keyMaterial[macLen*2+keyLen : len(keyMaterial)];\n\treturn;\n}", "func validateNMEAChecksum(s string) (string, bool) {\n\t//validate format. NMEA sentences start with \"$\" and end in \"*xx\" where xx is the XOR value of all bytes between\n\tif !(strings.HasPrefix(s, \"$\") && strings.Contains(s, \"*\")) {\n\t\treturn \"Invalid NMEA message\", false\n\t}\n\n\t// strip leading \"$\" and split at \"*\"\n\ts_split := strings.Split(strings.TrimPrefix(s, \"$\"), \"*\")\n\ts_out := s_split[0]\n\ts_cs := s_split[1]\n\n\tif len(s_cs) < 2 {\n\t\treturn \"Missing checksum. Fewer than two bytes after asterisk\", false\n\t}\n\n\tcs, err := strconv.ParseUint(s_cs[:2], 16, 8)\n\tif err != nil {\n\t\treturn \"Invalid checksum\", false\n\t}\n\n\tcs_calc := byte(0)\n\tfor i := range s_out {\n\t\tcs_calc = cs_calc ^ byte(s_out[i])\n\t}\n\n\tif cs_calc != byte(cs) {\n\t\treturn fmt.Sprintf(\"Checksum failed. Calculated %#X; expected %#X\", cs_calc, cs), false\n\t}\n\n\treturn s_out, true\n}", "func (x *pwBreakerState) receiveLoginSendResponse(c net.Conn, server *PWBreaker) error {\n\tvar clientEmail, clientPub string\n\tif _, err := fmt.Fscanf(c, \"email: %s\\npublic key: %s\\n\", &clientEmail, &clientPub); err != nil {\n\t\treturn err\n\t}\n\t// Record the client's email address.\n\tserver.clientEmail = clientEmail\n\n\t// Record the client's public key.\n\tvar ok bool\n\tif server.clientPub, ok = new(big.Int).SetString(clientPub, 16); !ok {\n\t\treturn errors.New(\"receiveLoginSendResponse: invalid public key\")\n\t}\n\tif _, err := fmt.Fprintf(c, \"salt: 00\\npublic key: %s\\n\",\n\t\thex.EncodeToString(server.y.Bytes())); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SMB1ExtractNativeFieldsFromSessionSetupReply(blob []byte, info map[string]string) {\n\n\tsmbOffset := bytes.Index(blob, []byte{0xff, 'S', 'M', 'B'})\n\tif smbOffset < 0 {\n\t\treturn\n\t}\n\n\tdata := blob[smbOffset:]\n\tif len(data) < 41 {\n\t\treturn\n\t}\n\n\t// Read the Security Blob Length and then skip past it\n\tsbl := int(binary.LittleEndian.Uint16(data[39:]))\n\tnbi := sbl + 39 + 4\n\tif len(data) < nbi {\n\t\treturn\n\t}\n\n\tdata = data[nbi:]\n\tbits := strings.Split(string(data), \"\\x00\\x00\")\n\tif len(bits) < 3 {\n\t\treturn\n\t}\n\n\t// Extract the last three elements\n\tinfo[\"smb.NativeOS\"] = TrimName(bits[0])\n\tinfo[\"smb.NativeLM\"] = TrimName(bits[1])\n\tinfo[\"smb.Domain\"] = TrimName(bits[2])\n}", "func validPass(client interfaces.Client) (interfaces.Client, error) {\n\tlength := len(client.GetPass())\n\tif length < 4 || length > 8 {\n\t\treturn client, errors.New(\"Pass must be between 4 and 8 characters\")\n\t}\n\treturn client, nil\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 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 CompletePackage(msg []byte, data_len int) int {\n //fmt.Println(\"data_len\", data_len)\n if data_len <= 8 {\n return 0\n }\n /*\n magic_byte:= msg[0:4]\n magic_num := binary.BigEndian.Uint32(magic_byte)\n if magic_num != MAGIC_NUM {\n return -1\n } \n */\n\n len_byte := msg[4:8]\n parse_len := binary.BigEndian.Uint32(len_byte)\n \n if int(parse_len) <= data_len {\n return int(parse_len)\n }\n return -1\n}", "func (r *MFRC522) selectLevel(clevel int /* Cascade level */, duration time.Duration) (uid []byte, sak byte, err error) {\n\n\tlog.Printf(\" selectLevel %d\\n\", clevel)\n\n\tvar selByte byte\n\n\tswitch clevel {\n\tcase 1:\n\t\tselByte = PICC_CMD_SEL_CL1\n\tcase 2:\n\t\tselByte = PICC_CMD_SEL_CL2\n\tcase 3:\n\t\tselByte = PICC_CMD_SEL_CL3\n\tdefault:\n\t\terr = CommonError(fmt.Sprintf(\"Wrong cascade level %d\\n\", clevel))\n\t}\n\n\tnvb := byte(0x20)\n\n\tdataToSend := []byte{selByte, nvb}\n\n\tvalidBits := byte(0)\n\n\tvar result []byte\n\tlog.Printf(\" send [% x]\\n\", dataToSend)\n\tif result, err = r.PCD_CommunicateWithPICC(PCD_Transceive, dataToSend, &validBits, duration); err != nil {\n\t\treturn\n\t}\n\n\tif len(result) != 5 {\n\t\t// UIDcl + BC\n\t\terr = CommonError(fmt.Sprintf(\"Unexpected result length: level %d, len(result): %d\\n\", clevel, len(result)))\n\t\treturn\n\t}\n\n\t// Check collision\n\tvar collOccr bool\n\tif collOccr, err = r.PCD_IsCollisionOccure(); err != nil {\n\t\treturn\n\t} else {\n\t\tif !collOccr { // CollErr is 0!!\n\t\t\tlog.Printf(\" CollErr is 0\\n\")\n\t\t\tlog.Printf(\" validBits: %d\\n\", validBits)\n\t\t\tvar crc_a []byte\n\t\t\tnvb = byte(0x70)\n\t\t\t// Calculate CRC\n\t\t\tdataToSend = append([]byte{selByte, nvb}, result...)\n\t\t\tif crc_a, err = r.PCD_CalculateCRC(ISO_14443_CRC_RESET, dataToSend, INTERUPT_TIMEOUT); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuid = result[:4]\n\t\t\tdataToSend = append(dataToSend, crc_a...)\n\t\t\tlog.Printf(\" send [% x]\\n\", dataToSend)\n\t\t\tif result, err = r.PCD_CommunicateWithPICC(PCD_Transceive, dataToSend, &validBits, duration); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif len(result) != 3 { // SAK must be exactly 24 bits (1 byte + CRC_A)\n\t\t\t\terr = CommonError(fmt.Sprintf(\"SAK must be exactly 24 bits (1 byte + CRC_A). Received %d\\n\", len(result)))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar crcRes []byte\n\t\t\tif crcRes, err = r.PCD_CalculateCRC(ISO_14443_CRC_RESET, result[:1], duration); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif bytes.Compare(crcRes, result[1:]) != 0 {\n\t\t\t\terr = CommonError(fmt.Sprintf(\"CRC check SAK CRC_A error: \\n\"+\n\t\t\t\t\t\"calucated: [% x]\\n received [% x]\\n\", crcRes, result[:2]))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsak = result[0]\n\t\t\treturn\n\t\t} else {\n\t\t\terr = CommonError(\"COLLISION CYCLE NOT SUPPORTED YET\\n\")\n\t\t}\n\t}\n\n\treturn\n}", "func TestUnpackX2SetupFailureResponseAndExtract(t *testing.T) {\n\tInfoLevel := int8(3)\n\tlogger, _ := logger.InitLogger(InfoLevel)\n\n\tvar testCases = []struct {\n\t\tresponse string\n\t\tpackedPdu string\n\t\tfailure error\n\t}{\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED network_layer_cause:HANDOVER_DESIRABLE_FOR_RADIO_REASONS time_to_wait:V1S criticality_diagnostics:{procedure_code:33 triggering_message:UNSUCCESSFUL_OUTCOME procedure_criticality:NOTIFY information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t radioNetwork_t = 0\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x16\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t TimeToWait = 0\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t procedureCode_t = 0x21\n\t\t\t\t triggeringMessage_t = 0x2\n\t\t\t\t procedureCriticality_t = 0x2\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t*/\n\t\t\tpackedPdu: \"4006001a0000030005400200000016400100001140087821a00000008040\"},\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED transport_layer_cause:TRANSPORT_RESOURCE_UNAVAILABLE criticality_diagnostics:{procedure_code:33 triggering_message:UNSUCCESSFUL_OUTCOME procedure_criticality:NOTIFY information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t transport_t = 0\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t procedureCode_t = 0x21\n\t\t\t\t triggeringMessage_t = 0x2\n\t\t\t\t procedureCriticality_t = 0x2\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t*/\n\t\t\tpackedPdu: \"400600140000020005400120001140087821a00000008040\"},\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED protocol_cause:ABSTRACT_SYNTAX_ERROR_IGNORE_AND_NOTIFY criticality_diagnostics:{triggering_message:UNSUCCESSFUL_OUTCOME procedure_criticality:NOTIFY information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t protocol_t = 0x2\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t triggeringMessage_t = 0x2\n\t\t\t\t procedureCriticality_t = 0x2\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t*/\n\t\t\tpackedPdu: \"400600130000020005400144001140073a800000008040\"},\n\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED miscellaneous_cause:UNSPECIFIED criticality_diagnostics:{procedure_criticality:NOTIFY information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t misc_t = 0x4\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t procedureCriticality_t = 0x2\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t*/\n\t\t\tpackedPdu: \"400600120000020005400168001140061a0000008040\"},\n\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED miscellaneous_cause:UNSPECIFIED criticality_diagnostics:{information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING} information_element_criticality_diagnostics:{ie_criticality:NOTIFY ie_id:255 type_of_error:NOT_UNDERSTOOD}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t misc_t = 0x4\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0x2\n\t\t\t\t iE_ID_t = 0xff\n\t\t\t\t typeOfError_t = 0\n\t\t\t*/\n\t\t\tpackedPdu: \"4006001500000200054001680011400908010000804800ff00\"},\n\n\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED miscellaneous_cause:UNSPECIFIED criticality_diagnostics:{procedure_code:33}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t misc_t = 0x4\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t procedureCode_t = 0x21\n\t\t\t*/\n\t\t\tpackedPdu: \"4006000e0000020005400168001140024021\"},\n\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED miscellaneous_cause:UNSPECIFIED\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t misc_t = 0x4\n\t\t\t*/\n\t\t\tpackedPdu: \"400600080000010005400168\"},\n\t\t{\n\t\t\tresponse: \"CONNECTED_SETUP_FAILED network_layer_cause:HANDOVER_DESIRABLE_FOR_RADIO_REASONS time_to_wait:V1S criticality_diagnostics:{procedure_code:33 triggering_message:UNSUCCESSFUL_OUTCOME procedure_criticality:NOTIFY information_element_criticality_diagnostics:{ie_criticality:REJECT ie_id:128 type_of_error:MISSING}}\",\n\t\t\t/*\n\t\t\t\tE2AP-PDU:\n\t\t\t\t unsuccessfulOutcome_t\n\t\t\t\t procedureCode_t = 0x6\n\t\t\t\t criticality_t = 0\n\t\t\t\t X2SetupFailure\n\t\t\t\t protocolIEs_t:\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x5\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t Cause:\n\t\t\t\t radioNetwork_t = 0\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x16\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t TimeToWait = 0\n\t\t\t\t ProtocolIE_Container_elm\n\t\t\t\t id_t = 0x11\n\t\t\t\t criticality_t = 0x1\n\t\t\t\t CriticalityDiagnostics\n\t\t\t\t procedureCode_t = 0x21\n\t\t\t\t triggeringMessage_t = 0x2\n\t\t\t\t procedureCriticality_t = 0x2\n\t\t\t\t iEsCriticalityDiagnostics_t:\n\t\t\t\t CriticalityDiagnostics_IE_List_elm\n\t\t\t\t iECriticality_t = 0\n\t\t\t\t iE_ID_t = 0x80\n\t\t\t\t typeOfError_t = 0x1\n\t\t\t*/\n\t\t\tpackedPdu: \"4006001a0000030005400200000016400100001140087821a00000008040\",\n\t\t\t//failure: fmt.Errorf(\"getAtom for path [unsuccessfulOutcome_t X2SetupFailure protocolIEs_t ProtocolIE_Container_elm Cause radioNetwork_t] failed, rc = 2\" /*NO_SPACE_LEFT*/),\n\t\t},\n\t}\n\n\tconverter := NewX2SetupFailureResponseConverter(logger)\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.packedPdu, func(t *testing.T) {\n\n\t\t\tvar payload []byte\n\t\t\t_, err := fmt.Sscanf(tc.packedPdu, \"%x\", &payload)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"convert inputPayloadAsStr to payloadAsByte. Error: %v\\n\", err)\n\t\t\t}\n\n\t\t\tresponse, err := converter.UnpackX2SetupFailureResponseAndExtract(payload)\n\n\t\t\tif err != nil {\n\t\t\t\tif tc.failure == nil {\n\t\t\t\t\tt.Errorf(\"want: success, got: error: %v\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tif strings.Compare(err.Error(), tc.failure.Error()) != 0 {\n\t\t\t\t\t\tt.Errorf(\"want: %s, got: %s\", tc.failure, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif response == nil {\n\t\t\t\tif tc.failure == nil {\n\t\t\t\t\tt.Errorf(\"want: response=%s, got: empty response\", tc.response)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnb := &entities.NodebInfo{}\n\t\t\t\tnb.ConnectionStatus = entities.ConnectionStatus_CONNECTED_SETUP_FAILED\n\t\t\t\tnb.SetupFailure = response\n\t\t\t\tnb.FailureType = entities.Failure_X2_SETUP_FAILURE\n\t\t\t\trespStr := fmt.Sprintf(\"%s %s\", nb.ConnectionStatus, response)\n\n\t\t\t\tspace := regexp.MustCompile(`\\s+`)\n\t\t\t\ts1 := space.ReplaceAllString(respStr, \" \")\n\t\t\t\ts2 := space.ReplaceAllString(tc.response,\" \")\n\n\t\t\t\tif !strings.EqualFold(s1, s2) {\n\t\t\t\t\tt.Errorf(\"want: [%s], got: [%s]\", tc.response, respStr)\n\t\t\t\t}\n\n\t\t\t}\n\t\t})\n\t}\n}", "func ParseLoginStart(data *bufio.Reader) (result LoginStart, err error) {\n\tusername, err := ReadString(data, 16)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = LoginStart {\n\t\tClientsideUsername: username,\n\t}\n\treturn\n}", "func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\n\tvar output string\n\tmsg := validateInvoiceDetails(stub, args)\n\n\tif msg == \"\" {\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\n\t} else {\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\n\t}\n\treturn []byte(output)\n}", "func (z *MinerInfo) Msgsize() (s int) {\n\ts = 1 + 8 + z.Address.Msgsize() + 8 + hsp.Uint64Size + 14 + hsp.StringPrefixSize + len(z.EncryptionKey) + 5 + hsp.StringPrefixSize + len(z.Name) + 7 + z.NodeID.Msgsize() + 14 + hsp.Uint64Size + 15 + hsp.Uint64Size + 7 + hsp.Int32Size + 12 + hsp.ArrayHeaderSize\n\tfor za0001 := range z.UserArrears {\n\t\tif z.UserArrears[za0001] == nil {\n\t\t\ts += hsp.NilSize\n\t\t} else {\n\t\t\ts += 1 + 5 + z.UserArrears[za0001].User.Msgsize() + 8 + hsp.Uint64Size\n\t\t}\n\t}\n\treturn\n}", "func (z *ZebraData) Msgsize() (s int) {\n\ts = 1 + 7 + msgp.ArrayHeaderSize + (16 * (msgp.ByteSize)) + 9 + msgp.StringPrefixSize + len(z.Username) + 5 + msgp.StringPrefixSize + len(z.Note)\n\treturn\n}", "func TestMsgParseTortureLongreq(t *testing.T) {\n\tstr := \"INVITE sip:[email protected] SIP/2.0\\r\\n\" +\n\t\t// <allOneLine>\n\t\t\"To: \\\"I have a user name of \" + strings.Repeat(\"extreme\", 10) +\n\t\t\" proportion\\\"<sip:[email protected]:6000;\" +\n\t\t\"unknownparam1=very\" + strings.Repeat(\"long\", 20) + \"value;\" +\n\t\t\"longparam\" + strings.Repeat(\"name\", 25) + \"=shortvalue;\" +\n\t\t\"very\" + strings.Repeat(\"long\", 25) + \"ParameterNameWithNoValue>\\r\\n\" +\n\t\t// </allOneLine>\n\t\t// <allOneLine>\n\t\t\"F: sip:\" + strings.Repeat(\"amazinglylongcallername\", 5) + \"@example.net\" +\n\t\t\";tag=12\" + strings.Repeat(\"982\", 50) + \"424\" +\n\t\t\";unknownheaderparam\" + strings.Repeat(\"name\", 20) + \"=\" +\n\t\t\"unknowheaderparam\" + strings.Repeat(\"value\", 15) +\n\t\t\";unknownValueless\" + strings.Repeat(\"paramname\", 10) + \"\\r\\n\" +\n\t\t// </allOneLine>\n\t\t\"Call-ID: longreq.one\" + strings.Repeat(\"really\", 20) + \"longcallid\\r\\n\" +\n\t\t\"CSeq: 3882340 INVITE\\r\\n\" +\n\t\t// <allOneLine>\n\t\t\"Unknown-\" + strings.Repeat(\"Long\", 20) + \"-Name:\" +\n\t\t\"unknown-\" + strings.Repeat(\"long\", 20) + \"-value;\" +\n\t\t\"unknown-\" + strings.Repeat(\"long\", 20) + \"-parameter-name =\" +\n\t\t\"unknown-\" + strings.Repeat(\"long\", 20) + \"-parameter-value\\r\\n\" +\n\t\t// </allOneLine>\n\n\t\t\"Via: SIP/2.0/TCP sip33.example.com\\r\\n\" +\n\t\t\"v: SIP/2.0/TCP sip32.example.com\\r\\n\" +\n\t\t\"V: SIP/2.0/TCP sip31.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip30.example.com\\r\\n\" +\n\t\t\"ViA: SIP/2.0/TCP sip29.example.com\\r\\n\" +\n\t\t\"VIa: SIP/2.0/TCP sip28.example.com\\r\\n\" +\n\t\t\"VIA: SIP/2.0/TCP sip27.example.com\\r\\n\" +\n\t\t\"via: SIP/2.0/TCP sip26.example.com\\r\\n\" +\n\t\t\"viA: SIP/2.0/TCP sip25.example.com\\r\\n\" +\n\t\t\"vIa: SIP/2.0/TCP sip24.example.com\\r\\n\" +\n\t\t\"vIA: SIP/2.0/TCP sip23.example.com\\r\\n\" +\n\t\t\"V : SIP/2.0/TCP sip22.example.com\\r\\n\" +\n\t\t\"v : SIP/2.0/TCP sip21.example.com\\r\\n\" +\n\t\t\"V : SIP/2.0/TCP sip20.example.com\\r\\n\" +\n\t\t\"v : SIP/2.0/TCP sip19.example.com\\r\\n\" +\n\t\t\"Via : SIP/2.0/TCP sip18.example.com\\r\\n\" +\n\t\t\"Via : SIP/2.0/TCP sip17.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip16.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip15.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip14.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip13.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip12.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip11.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip10.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip9.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip8.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip7.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip6.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip5.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip4.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip3.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip2.example.com\\r\\n\" +\n\t\t\"Via: SIP/2.0/TCP sip1.example.com\\r\\n\" +\n\t\t// <allOneLine>\n\t\t\"Via: SIP/2.0/TCP host.example.com;received=192.0.2.5;\" +\n\t\t\"branch=very\" + strings.Repeat(\"long\", 50) + \"branchvalue\\r\\n\" +\n\t\t// </allOneLine>\n\t\t\"Max-Forwards: 70\\r\\n\" +\n\t\t// <allOneLine>\n\t\t\"Contact: <sip:\" + strings.Repeat(\"amazinglylongcallername\", 5) +\n\t\t\"@host5.example.net>\\r\\n\" +\n\t\t// </allOneLine>\n\t\t\"Content-Type: application/sdp\\r\\n\" +\n\t\t\"l: 150\\r\\n\\r\\n\"\n\tmsg, err := MsgParse([]byte(str))\n\tassert.Nil(t, err)\n\tassert.True(t, msg.IsRequest())\n\tassert.Equal(t, 34, msg.Vias.Count())\n\tassert.Equal(t, 1, msg.Contacts.Count())\n\tassert.Equal(t, \"longreq.one\"+strings.Repeat(\"really\", 20)+\"longcallid\",\n\t\tmsg.CallID)\n\n}", "func TestMsgParseTortureLwsStart(t *testing.T) {\n\tstr := \"INVITE sip:[email protected] SIP/2.0\\r\\n\" +\n\t\t\"Max-Forwards: 8\\r\\n\" +\n\t\t\"To: sip:[email protected]\\r\\n\" +\n\t\t\"From: sip:[email protected];tag=8814\\r\\n\" +\n\t\t\"Call-ID: [email protected]\\r\\n\" +\n\t\t\"CSeq: 1893884 INVITE\\r\\n\" +\n\t\t\"Via: SIP/2.0/UDP host1.example.com;branch=z9hG4bKkdjuw3923\\r\\n\" +\n\t\t\"Contact: <sip:[email protected]>\\r\\n\" +\n\t\t\"Content-Type: application/sdp\\r\\n\" +\n\t\t\"Content-Length: 150\\r\\n\\r\\n\"\n\t_, err := MsgParse([]byte(str))\n\tassert.NotNil(t, err)\n\tassert.Contains(t, err.Error(), \"INVITE sip:[email protected] SIP/2.0\")\n}", "func b58checkdecode(s string) (ver uint8, b []byte, err error) {\n\t/* Decode base58 string */\n\tb, err = b58decode(s)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\t/* Add leading zero bytes */\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] != '1' {\n\t\t\tbreak\n\t\t}\n\t\tb = append([]byte{0x3f}, b...)\n\t}\n\n\t/* Verify checksum */\n\tif len(b) < 5 {\n\t\treturn 0, nil, fmt.Errorf(\"Invalid base-58 check string: missing checksum.\")\n\t}\n\n\t/* Create a new SHA256 context */\n\tsha256_h := sha256.New()\n\n\t/* SHA256 Hash #1 */\n\tsha256_h.Reset()\n\tsha256_h.Write(b[:len(b)-4])\n\thash1 := sha256_h.Sum(nil)\n\n\t/* SHA256 Hash #2 */\n\tsha256_h.Reset()\n\tsha256_h.Write(hash1)\n\thash2 := sha256_h.Sum(nil)\n\n\t/* Compare checksum */\n\tif bytes.Compare(hash2[0:4], b[len(b)-4:]) != 0 {\n\t\treturn 0, nil, fmt.Errorf(\"Invalid base-58 check string: invalid checksum.\")\n\t}\n\n\t/* Strip checksum bytes */\n\tb = b[:len(b)-4]\n\n\t/* Extract and strip version */\n\tver = b[0]\n\tb = b[1:]\n\n\treturn ver, b, nil\n}", "func TestSenderToReceiverSwiftLineFiveAlphaNumeric(t *testing.T) {\n\tsr := mockSenderToReceiver()\n\tsr.CoverPayment.SwiftLineFive = \"®\"\n\n\terr := sr.Validate()\n\n\trequire.EqualError(t, err, fieldError(\"SwiftLineFive\", ErrNonAlphanumeric, sr.CoverPayment.SwiftLineFive).Error())\n}", "func TestParseSenderToReceiverWrongLength(t *testing.T) {\n\tvar line = \"{7072}SwiftSwift Line One Swift Line Two Swift Line Three Swift Line Four Swift Line Five Swift Line Six \"\n\tr := NewReader(strings.NewReader(line))\n\tr.line = line\n\n\terr := r.parseSenderToReceiver()\n\n\trequire.EqualError(t, err, r.parseError(fieldError(\"SwiftLineSix\", ErrValidLength)).Error())\n}", "func receiverVerify (userInput ,digest string)bool{\n\tsecretKey := \"2ab9eb0\"\n\tplainText := secretKey+userInput\n\tdigest_local := Sha1(plainText)\n\tif strings.Compare(digest,digest_local)==0{\n\t\treturn true\n\t}\n\treturn false\n}", "func (c parser) IsLogin(command []byte) bool {\n\tif len(command) == 0 {\n\t\treturn false\n\t}\n\n\tloginByte := command[25:27]\n\thexReportNumber, err := convert.FromByteToHex(loginByte)\n\n\tif hexReportNumber == \"0x1001\" && err == nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestMsgParseTortureNcl(t *testing.T) {\n\tstr := \"INVITE sip:[email protected] SIP/2.0\\r\\n\" +\n\t\t\"Max-Forwards: 254\\r\\n\" +\n\t\t\"To: sip:[email protected]\\r\\n\" +\n\t\t\"From: sip:[email protected];tag=32394234\\r\\n\" +\n\t\t\"Call-ID: ncl.0ha0isndaksdj2193423r542w35\\r\\n\" +\n\t\t\"CSeq: 0 INVITE\\r\\n\" +\n\t\t\"Via: SIP/2.0/UDP 192.0.2.53;branch=z9hG4bKkdjuw\\r\\n\" +\n\t\t\"Contact: <sip:[email protected]>\\r\\n\" +\n\t\t\"Content-Type: application/sdp\\r\\n\" +\n\t\t\"Content-Length: -999\\r\\n\\r\\n\"\n\t_, err := MsgParse([]byte(str))\n\tassert.NotNil(t, err)\n\tassert.Contains(t, err.Error(), \"Content-Length: -999\")\n}", "func checkUserInfo(info userInfo) responseMsg {\n\tr := responseMsg{}\n\tif info.password != info.password2 {\n\t\tr.success = false\n\t\tr.Message = \"Passwords do not match\"\n\t\treturn r\n\t}\n\n\tif checkPassword(info.password) == false {\n\t\tr.success = false\n\t\tr.Message = \"Password is not strong enough.It should contain at least one capital letter and one special character\"\n\t\treturn r\n\t}\n\t//Check if a user with this username already exists\n\tif getUser(info.Username).Username != \"\" {\n\t\tr.success = false\n\t\tr.Message = \"A user with this username already exists!\"\n\t\treturn r\n\t}\n\tr.success = true\n\tr.Message = \"Open your terminal and join a room!\"\n\treturn r\n}", "func validSentence(sentence string) error {\n\tif len(sentence) < minimumNMEALength || sentence[0] != startingDelimiter || sentence[len(sentence)-3] != checksumDelimiter {\n\t\treturn errInvalidNMEASentenceLength\n\t}\n\tvar cs byte = 0\n\tfor i := 1; i < len(sentence)-3; i++ {\n\t\tcs ^= sentence[i]\n\t}\n\tchecksum := strings.ToUpper(hex.EncodeToString([]byte{cs}))\n\tif checksum != sentence[len(sentence)-2:len(sentence)] {\n\t\treturn newGPSError(errInvalidNMEAChecksum, sentence,\n\t\t\t\"expected \"+sentence[len(sentence)-2:len(sentence)]+\n\t\t\t\t\" got \"+checksum)\n\t}\n\n\treturn nil\n}", "func isCreditCard(fl FieldLevel) bool {\n\tval := fl.Field().String()\n\tvar creditCard bytes.Buffer\n\tsegments := strings.Split(val, \" \")\n\tfor _, segment := range segments {\n\t\tif len(segment) < 3 {\n\t\t\treturn false\n\t\t}\n\t\tcreditCard.WriteString(segment)\n\t}\n\n\tccDigits := strings.Split(creditCard.String(), \"\")\n\tsize := len(ccDigits)\n\tif size < 12 || size > 19 {\n\t\treturn false\n\t}\n\n\treturn digitsHaveLuhnChecksum(ccDigits)\n}", "func Decode(msg []byte) (Message, error) {\n\tvar m Message\n\n\tl := len(msg)\n\n\t// trim trailing carriage return if present\n\tif l > 0 && msg[l-1] == '\\r' {\n\t\tl--\n\t\tmsg = msg[:l]\n\t}\n\n\tif l < 2 {\n\t\treturn m, errors.New(\"Decode: message too short\")\n\t}\n\n\tm.typ = codeToMsg[string(msg[:2])]\n\tif m.typ == MsgUnknown {\n\t\treturn m, fmt.Errorf(\"Decode: unknown message code: %q\", string(msg[:2]))\n\t}\n\n\tif l < minMsgLength[m.typ] {\n\t\treturn m, fmt.Errorf(\"Decode: message too short to contain required fields for %v: %d < %d\", m.typ, len(msg), minMsgLength[m.typ])\n\t}\n\n\tm.fields = make(map[fieldType]string)\n\tm.repeateableFields = make(map[fieldType][]string)\n\n\t// Parse fixed-length fields:\n\tp := 2 // byte position in message\n\tfor _, f := range msgDefinitions[m.typ].RequiredFixed {\n\t\tend := p + fixedFieldLengths[f] // end of token\n\t\tm.fields[f] = string(msg[p:end])\n\t\tp = end\n\t}\n\n\t// Parse variable-length fields:\nouter:\n\tfor len(msg) > p {\n\t\tstart := p + 2 // start of current field\n\t\tf := codeToField[string(msg[p:start])]\n\t\tp = start\n\t\tif f == FieldUnknown {\n\t\t\t// store unknown codes in message value\n\t\t\tstart -= 2\n\t\t}\n\n\t\tfor {\n\t\t\tr, w := utf8.DecodeRune(msg[p:])\n\t\t\tp += w\n\t\t\tif r == '|' {\n\t\t\t\tif repeatableField[f] {\n\t\t\t\t\tm.repeateableFields[f] = append(m.repeateableFields[f], string(msg[start:p-1]))\n\t\t\t\t} else {\n\t\t\t\t\tm.fields[f] = string(msg[start : p-1])\n\t\t\t\t}\n\t\t\t\tif p == l {\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t\tcontinue outer\n\t\t\t} else if p == l {\n\t\t\t\tif repeatableField[f] {\n\t\t\t\t\tm.repeateableFields[f] = append(m.repeateableFields[f], string(msg[start:l]))\n\t\t\t\t} else {\n\t\t\t\t\tm.fields[f] = string(msg[start:l])\n\t\t\t\t}\n\t\t\t\tbreak outer\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn m, nil\n}", "func scanFields(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\tif atEOF {\n\t\treturn 0, nil, io.EOF\n\t}\n\n\tif len(data) < 4 {\n\t\treturn 0, nil, nil\n\t}\n\n\ttotalSize := int(binary.BigEndian.Uint32(data[:4])) + 4\n\n\tif totalSize > len(data) {\n\t\treturn 0, nil, nil\n\t}\n\n\t// msgBytes := make([]byte, totalSize-4, totalSize-4)\n\t// copy(msgBytes, data[4:totalSize])\n\t// not copy here, copied by callee more reasonable\n\treturn totalSize, data[4:totalSize], nil\n}", "func validateTransactionToken(tokenTransactionObj transaction.DigitalwalletTransaction) (string, bool) {\n\n\tvar errorfound string\n\n\t//validate token id ==100\n\t//if len(tokenTransactionObj.TokenID) != 100 {\n\t//\terrorfound = \"token ID must be 100 characters\"\n\t//\treturn errorfound, false\n\t//}\n\t//validate fields not fields\n\tif tokenTransactionObj.Sender == \"\" || tokenTransactionObj.Amount == 0.0 || tokenTransactionObj.Signature == \"\" {\n\t\terrorfound = \"please enter required data Sender PK,Receiver PK,Amount,Sender sign\"\n\t\treturn errorfound, false\n\t}\n\n\t//validate send signature ==200\n\t//if len(tokenTransactionObj.Signature) != 200 {\n\t//\terrorfound = \"Sender sign must be 200 characters\"\n\t//\treturn errorfound, false\n\t//}\n\n\terrorfound = transactionModule.ValidateTransaction(tokenTransactionObj)\n\tif errorfound != \"\" {\n\t\treturn errorfound, false\n\t}\n\n\treturn \"\", true\n}", "func validateFieldServicePaddingInitial(fl validator.FieldLevel) bool {\n\tv, err := strconv.ParseInt(fl.Field().String(), 10, 32)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif v < paddingInitialServiceMin {\n\t\treturn false\n\t}\n\tif v > paddingInitialServiceMax {\n\t\treturn false\n\t}\n\treturn true\n}", "func (header *ConnectHeader) parse(b []byte) error {\n\theader.PackType = int(b[0] >> 4)\n\tremainLenDigits, err := ParseRemainLenDigits(b[1:5])\n\tif err != nil {\n\t\treturn err\n\t}\n\tremainLen, err := DecodeRemainLen(remainLenDigits)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"remain_len_parsed => \", remainLen)\n\theaderLen := 1 + len(remainLenDigits) + VarHeaderLen\n\tvarHeaderStartIdx := 1 + len(remainLenDigits)\n\theader.RemainLen = remainLen\n\theader.ProtocNameLenLSB = int(b[varHeaderStartIdx])\n\theader.ProtocNameLenMSB = int(b[varHeaderStartIdx+1])\n\theader.ProtocName = string(b[varHeaderStartIdx+2 : varHeaderStartIdx+6])\n\theader.ProtocLevel = int(b[varHeaderStartIdx+6])\n\theader.Flags = int(b[varHeaderStartIdx+7])\n\theader.KeepAliveMSB = int(b[varHeaderStartIdx+8])\n\tlog.Println(\"len(b) => \", len(b), \"varHeaderStartIdx+9 => \", varHeaderStartIdx+9)\n\theader.KeepAliveLSB = int(b[varHeaderStartIdx+9])\n\theader.KeepAlive = int(binary.BigEndian.Uint16(b[varHeaderStartIdx+8 : headerLen]))\n\tfmt.Printf(\"parsed_header => %#v\\n\", header)\n\treturn nil\n}", "func processRequest(req *CustomProtocol.Request) {\n\n\tpayload := CustomProtocol.ParsePayload(req.Payload)\n\tswitch req.OpCode {\n\tcase CustomProtocol.ActivateGPS:\n\t\tflagStolen(\"gps\", payload[0])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.FlagStolen:\n\t\tflagStolen(\"laptop\", payload[0])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.FlagNotStolen:\n\t\t//TODO: temp fix < 12\n\t\tif len(payload[0]) < 12 {\n\t\t\tflagNotStolen(\"gps\", payload[0])\n\t\t} else {\n\t\t\tflagNotStolen(\"laptop\", payload[0])\n\t\t}\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1 //TO DO CHANGE\n\t\treq.Response <- res\n\tcase CustomProtocol.NewAccount:\n\t\tSignUp(payload[0], payload[1], payload[2], payload[3], payload[4])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.NewDevice:\n\t\tregisterNewDevice(payload[0], payload[1], payload[2], payload[3])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateDeviceGPS:\n\t\tupdated := updateDeviceGps(payload[0], payload[1], payload[2])\n\t\tres := make([]byte, 2)\n\t\tif updated == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.VerifyLoginCredentials:\n\t\taccountValid, passwordValid := VerifyAccountInfo(payload[0], payload[1])\n\t\tres := make([]byte, 2)\n\t\tif accountValid {\n\t\t\tres[0] = 1\n\t\t\tif passwordValid {\n\t\t\t\tres[1] = 1\n\t\t\t} else {\n\t\t\t\tres[0] = 0\n\t\t\t}\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t\tres[1] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.SetAccount:\n\t\taccSet := updateAccountInfo(payload[0], payload[1], payload[2])\n\t\tres := make([]byte, 1)\n\t\tif accSet == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.GetDevice:\n\t\tres := make([]byte, 5)\n\n\t\tif payload[0] == \"gps\" {\n\t\t\tres = getGpsDevices(payload[1])\n\t\t} else if payload[0] == \"laptop\" {\n\t\t\tres = getLaptopDevices(payload[1])\n\t\t} else {\n\t\t\tfmt.Println(\"CustomProtocol.GetDevice payload[0] must be either gps or laptop\")\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.SetDevice:\n\tcase CustomProtocol.GetDeviceList:\n\t\tres := []byte{}\n\t\tres = append(res, getLaptopDevices(payload[0])...)\n\t\tres = append(res, 0x1B)\n\t\tres = append(res, getGpsDevices(payload[0])...)\n\t\treq.Response <- res\n\tcase CustomProtocol.CheckDeviceStolen:\n\t\tisStolen := IsDeviceStolen(payload[0])\n\t\tres := make([]byte, 1)\n\t\tif isStolen == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateUserKeylogData:\n\t\tboolResult := UpdateKeylog(payload[0], payload[1])\n\t\tres := make([]byte, 1)\n\t\tif boolResult == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateUserIPTraceData:\n\t\tboolResult := UpdateTraceRoute(payload[0], payload[1])\n\t\tres := make([]byte, 1)\n\t\tif boolResult == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tdefault:\n\t}\n}", "func validateAuthFromCloud(token string) (bool, string) {\n\tvar userId UserId\n\tvar reqData imdosReq\n\tvar strslice []string\n\n\treqId := \"NQE1PiLi\"\n\ttimeStamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)\n\tfmt.Println(timeStamp)\n\tnonce := \"H7SG5XW6\"\n\tmchId := \"1\"\n\tmethod := \"CheckToken\"\n\n\timdosUrl := \"http://app.ccipfs.cn/dake/interface.aspx\"\n\n\tuserId.UserId = \"wenkun\"\n\tdata, errs := json.Marshal(userId)\n\tif errs != nil {\n\t\tfmt.Println(errs.Error())\n\t}\n\tstrslice = append(strslice, \"/dake/Interface.aspx\", token)\n\tstrslice = append(strslice, reqId, timeStamp, nonce, mchId, method)\n\tstrslice = append(strslice, string(data))\n\tsort.Strings(strslice)\n\n\tnetStr := strings.Join(strslice, \",\")\n\tfmt.Println(netStr)\n\treqData.Data = string(data)\n\treqData.Method = method\n\treqData.Time = timeStamp\n\treqData.ReqId = reqId\n\treqData.Nonce = nonce\n\treqData.MchId = mchId\n\treqData.Token = token\n\treqData.Sign = MD5(netStr)\n\n\tfmt.Println(reqData)\n\trequest_info, errs := json.Marshal(reqData)\n\tif errs != nil {\n\t\tfmt.Println(errs.Error())\n\t}\n\n\tfmt.Println(string(request_info))\n\treqBody := bytes.NewBuffer(request_info)\n\tresp, err := http.Post(imdosUrl, \"json\", reqBody)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\tvar ret imdosRsp\n\terr = json.NewDecoder(resp.Body).Decode(&ret)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\tif ret.Code != \"200\" {\n\n\t}\n\tfmt.Println(ret.Code, ret.Msg)\n\treturn true, \"OK\"\n}", "func (z *LoginGameAck) Msgsize() (s int) {\n\ts = 1 + 5 + msgp.Int32Size + 5 + msgp.Int32Size + 5 + msgp.Int32Size + 4 + msgp.StringPrefixSize + len(z.Msg)\n\treturn\n}", "func validateInvoiceDetails(stub shim.ChaincodeStubInterface, args []string) string {\n\tvar output string\n\tvar errorMessages []string\n\tvar invoices []map[string]interface{}\n\tvar ufaDetails map[string]interface{}\n\t//I am assuming the invoices would sent as an array and must be multiple\n\tpayload := args[1]\n\tjson.Unmarshal([]byte(payload), &invoices)\n\tif len(invoices) < 2 {\n\t\terrorMessages = append(errorMessages, \"Invalid number of invoices\")\n\t} else {\n\t\t//Now checking the ufa number\n\t\tfirstInvoice := invoices[0]\n\t\tufanumber := getSafeString(firstInvoice[\"ufanumber\"])\n\t\tif ufanumber == \"\" {\n\t\t\terrorMessages = append(errorMessages, \"UFA number not provided\")\n\t\t} else {\n\t\t\trecBytes, err := stub.GetState(ufanumber)\n\t\t\tif err != nil || recBytes == nil {\n\t\t\t\terrorMessages = append(errorMessages, \"Invalid UFA number provided\")\n\t\t\t} else {\n\t\t\t\tjson.Unmarshal(recBytes, &ufaDetails)\n\t\t\t\t//Rasied invoice shoul not be exhausted\n\t\t\t\traisedTotal := getSafeNumber(ufaDetails[\"raisedInvTotal\"])\n\t\t\t\ttotalCharge := getSafeNumber(ufaDetails[\"netCharge\"])\n\t\t\t\ttolerance := getSafeNumber(ufaDetails[\"chargTolrence\"])\n\t\t\t\tmaxCharge := totalCharge + (totalCharge * tolerance / 100)\n\t\t\t\tif raisedTotal == maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"All charges exhausted. Invoices can not raised\")\n\t\t\t\t}\n\t\t\t\t//Now check if invoice is already raised for the period or not\n\t\t\t\tbillingPerid := getSafeString(firstInvoice[\"billingPeriod\"])\n\t\t\t\tif billingPerid == \"\" {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid billing period\")\n\t\t\t\t}\n\t\t\t\tif ufaDetails[\"invperiod_\"+billingPerid] != nil {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice already raised for the month\")\n\t\t\t\t}\n\t\t\t\t//Now check the sum of invoice amount\n\t\t\t\trunningTotal := 0.0\n\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\tfor _, invoice := range invoices {\n\t\t\t\t\tinvoiceNumber := getSafeString(invoice[\"invoiceNumber\"])\n\t\t\t\t\tamount := getSafeNumber(invoice[\"invoiceAmt\"])\n\t\t\t\t\tif amount < 0 {\n\t\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid invoice amount in \"+invoiceNumber)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.WriteString(invoiceNumber)\n\t\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t\t\trunningTotal = runningTotal + amount\n\t\t\t\t}\n\t\t\t\tif (raisedTotal + runningTotal/2) >= maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice value is exceeding total allowed charge\")\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\tif len(errorMessages) == 0 {\n\t\toutput = \"\"\n\t} else {\n\t\toutputBytes, _ := json.Marshal(errorMessages)\n\t\toutput = string(outputBytes)\n\t}\n\treturn output\n}", "func parseClientHello(data []byte) (*tls.ClientHelloInfo, error) {\n\t// The implementation of this function is based on crypto/tls.clientHelloMsg.unmarshal\n\tvar info tls.ClientHelloInfo\n\ts := cryptobyte.String(data)\n\n\t// Skip message type, length, version, and random.\n\tif !s.Skip(43) {\n\t\treturn nil, errors.New(\"too short\")\n\t}\n\n\tvar sessionID cryptobyte.String\n\tif !s.ReadUint8LengthPrefixed(&sessionID) {\n\t\treturn nil, errors.New(\"bad session ID\")\n\t}\n\n\tvar cipherSuites cryptobyte.String\n\tif !s.ReadUint16LengthPrefixed(&cipherSuites) {\n\t\treturn nil, errors.New(\"bad cipher suites\")\n\t}\n\n\tvar compressionMethods cryptobyte.String\n\tif !s.ReadUint8LengthPrefixed(&compressionMethods) {\n\t\treturn nil, errors.New(\"bad compression methods\")\n\t}\n\n\tif s.Empty() {\n\t\t// no extensions\n\t\treturn &info, nil\n\t}\n\n\tvar extensions cryptobyte.String\n\tif !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {\n\t\treturn nil, errors.New(\"bad extensions\")\n\t}\n\n\tfor !extensions.Empty() {\n\t\tvar extension uint16\n\t\tvar extData cryptobyte.String\n\t\tif !extensions.ReadUint16(&extension) || !extensions.ReadUint16LengthPrefixed(&extData) {\n\t\t\treturn nil, errors.New(\"bad extension\")\n\t\t}\n\n\t\tswitch extension {\n\t\tcase 0: // server name\n\t\t\tvar nameList cryptobyte.String\n\t\t\tif !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() {\n\t\t\t\treturn nil, errors.New(\"bad name list\")\n\t\t\t}\n\t\t\tfor !nameList.Empty() {\n\t\t\t\tvar nameType uint8\n\t\t\t\tvar serverName cryptobyte.String\n\t\t\t\tif !nameList.ReadUint8(&nameType) || !nameList.ReadUint16LengthPrefixed(&serverName) || serverName.Empty() {\n\t\t\t\t\treturn nil, errors.New(\"bad entry in name list\")\n\t\t\t\t}\n\t\t\t\tif nameType != 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif info.ServerName != \"\" {\n\t\t\t\t\treturn nil, errors.New(\"multiple server names\")\n\t\t\t\t}\n\t\t\t\tinfo.ServerName = string(serverName)\n\t\t\t\tif strings.HasSuffix(info.ServerName, \".\") {\n\t\t\t\t\treturn nil, errors.New(\"server name ends with dot\")\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase 16: // ALPN\n\t\t\tvar protoList cryptobyte.String\n\t\t\tif !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {\n\t\t\t\treturn nil, errors.New(\"bad ALPN protocol list\")\n\t\t\t}\n\t\t\tfor !protoList.Empty() {\n\t\t\t\tvar proto cryptobyte.String\n\t\t\t\tif !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {\n\t\t\t\t\treturn nil, errors.New(\"bad ALPN protocol list entry\")\n\t\t\t\t}\n\t\t\t\tinfo.SupportedProtos = append(info.SupportedProtos, string(proto))\n\t\t\t}\n\n\t\tdefault:\n\t\t\t// ignore\n\t\t\tcontinue\n\t\t}\n\n\t\tif !extData.Empty() {\n\t\t\treturn nil, errors.New(\"extra data at end of extension\")\n\t\t}\n\t}\n\n\treturn &info, nil\n}", "func (hand *Handshake) buildC1Data() ([]byte, int) {\n\tbuf := new(bytes.Buffer)\n\n\ttimeBt := GetTimestampByte()\n\tbuf.Write(timeBt) // time (4 bytes)\n\tbuf.Write(FlashPlayerVersion) //version (4 bytes)\n\n\t//初始化1536个随机byte\n\tfor i := 8; i < 1536; i++ {\n\t\tbuf.WriteByte(byte(rand.Int() % 256))\n\t}\n\tbts := buf.Bytes()\n\t//todo: 其实按照adobe 官方的,可以不用这些的步骤,只要能保证 剩下的1528个bt保持唯一就行\n\t// base = time(4) version(4) offset(4)\n\treturn buildC1Digest(bts, GenuineFpKey[:30])\n\n\t/**\n\tRandom data (1528 bytes): This field can contain any arbitrary\n\t values. Since each endpoint has to distinguish between the\n\t response to the handshake it has initiated and the handshake\n\t initiated by its peer,this data SHOULD send something sufficiently\n\t random. But there is no need for cryptographically-secure\n\t randomness, or even dynamic values.\n\t*/\n\t//计算offset\n\t//通过随机bt 计算出 Digest的 偏移量 base is len(time)+len(version)+len(offset)\n\t//这里偏移量是8 4位time 4位version\n\t//offset := calOffset(bts, 8, 12)\n\t//tmpBuf := new(bytes.Buffer)\n\t//tmpBuf.Write(bts[:offset])\n\t//tmpBuf.Write(bts[offset+RtmpSha256DigestLength:])\n\t//\n\t////计算hash 内容为偏移量后的之前的数据 和 偏移量之后+32位的所有 byte\n\t////客户端的key 为 rtmp 协议内容\n\t//tempHash, err := HMACSha256(tmpBuf.Bytes(), GenuineFpKey[:30])\n\t//if err != nil {\n\t//\thand.setError(\"hash cal error\", err)\n\t//\treturn nil, 0\n\t//}\n\t//\n\t////将计算结果填充到 offset后32位\n\t//copy(bts[offset:], tempHash)\n\t//return bts, offset\n\n}", "func isValidLogin(usr string, pass string) string {\n\tcanLogin := canLogin(usr)\n\tif canLogin == LOGIN_TIME {\n\t\treturn RATE_MSG\n\t}\n\taddLoginAttempt(usr) //record this as a login attempt\n\tusr_info := GetUser(usr)\n\t// check if a user was found\n\tif len(usr_info) != 0 {\n\t\t// gather user info\n\t\tsalt := usr_info[USR_INFO_SALT]\n\t\tpassword := usr_info[USR_INFO_PASSWORD]\n\t\thashed_password := Hash256(pass, salt)\n\t\t// compare passwords\n\t\tif strings.Compare(hashed_password, password) == 0 {\n\t\t\treturn VALID_MSG\n\t\t}\n\t}\n\treturn RATE_MSG;\n}", "func checkMessageStringFields(msg *rainslib.RainsMessage) bool {\n\tif msg == nil || !checkCapabilites(msg.Capabilities) {\n\t\treturn false\n\t}\n\tfor _, s := range msg.Content {\n\t\tif !checkStringFields(s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (z *SQLChainProfile) Msgsize() (s int) {\n\ts = 1 + 8 + z.Address.Msgsize() + 15 + hsp.BytesPrefixSize + len(z.EncodedGenesis) + 9 + hsp.Uint64Size + 3 + z.ID.Msgsize() + 18 + hsp.Uint32Size + 5 + z.Meta.Msgsize() + 7 + hsp.ArrayHeaderSize\n\tfor za0001 := range z.Miners {\n\t\tif z.Miners[za0001] == nil {\n\t\t\ts += hsp.NilSize\n\t\t} else {\n\t\t\ts += z.Miners[za0001].Msgsize()\n\t\t}\n\t}\n\ts += 6 + z.Owner.Msgsize() + 7 + hsp.Uint64Size + 10 + z.TokenType.Msgsize() + 6 + hsp.ArrayHeaderSize\n\tfor za0002 := range z.Users {\n\t\tif z.Users[za0002] == nil {\n\t\t\ts += hsp.NilSize\n\t\t} else {\n\t\t\ts += z.Users[za0002].Msgsize()\n\t\t}\n\t}\n\treturn\n}", "func createFormat(message string) big.Int {\n\t//*Takes as input the message that the user has typed in.\n\t//*Creates a correctly padded message block, given some message.\n\t//*Return the decimal version of the correctly padded message block.\n\tfmt.Println(\"########################################################################---CREATING FORMAT---########################################################################\")\n\tfmt.Println(\"\")\n\tvar padding string\n\n\tzeroTwoAsString := []byte{0x00, 0x02} //Sets the two first bytes in the padding format to \"00\" and \"02\".\n\tzeroAsString := []byte{0x00} //Sets the seperator byte in the padding format to \"00\".\n\tencodedStr := hex.EncodeToString([]byte(zeroTwoAsString)) //Encodes the \"00\" and \"02\" bytes into a hex string.\n\tencodedzeroStr := hex.EncodeToString([]byte(zeroAsString)) //Encodes the seporator byte \"00\" into a hex string.\n\tencodedmessage := hex.EncodeToString([]byte(message)) //Encodes the message into a hex string\n\tmesLength := len(encodedmessage) //Sets the length of the message.\n\n\tpadToAdd := keyLengthInt - mesLength - 6 //Calculate how much padding is needed.\n\tfmt.Println(\"Padding to add: \" + strconv.Itoa(padToAdd))\n\tpadding = RandomString(padToAdd) //Creates the random padding using the RandomString method with\n\t//the amount from the above line.\n\tpkcsStr := encodedStr + padding + encodedzeroStr + encodedmessage //Construct a full message block such as: \"00|02|padding|00|message\"\n\n\tfmt.Println(\"Message block: \" + pkcsStr)\n\tstartMessageBlock = pkcsStr\n\thex2intEncode := HexToDec(pkcsStr) //Convert this message block from hexadecimal to decimal.\n\treturn hex2intEncode\n}", "func (drc *DeviceRequestCreate) check() error {\n\tif _, ok := drc.mutation.UserCode(); !ok {\n\t\treturn &ValidationError{Name: \"user_code\", err: errors.New(`db: missing required field \"DeviceRequest.user_code\"`)}\n\t}\n\tif v, ok := drc.mutation.UserCode(); ok {\n\t\tif err := devicerequest.UserCodeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"user_code\", err: fmt.Errorf(`db: validator failed for field \"DeviceRequest.user_code\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := drc.mutation.DeviceCode(); !ok {\n\t\treturn &ValidationError{Name: \"device_code\", err: errors.New(`db: missing required field \"DeviceRequest.device_code\"`)}\n\t}\n\tif v, ok := drc.mutation.DeviceCode(); ok {\n\t\tif err := devicerequest.DeviceCodeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"device_code\", err: fmt.Errorf(`db: validator failed for field \"DeviceRequest.device_code\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := drc.mutation.ClientID(); !ok {\n\t\treturn &ValidationError{Name: \"client_id\", err: errors.New(`db: missing required field \"DeviceRequest.client_id\"`)}\n\t}\n\tif v, ok := drc.mutation.ClientID(); ok {\n\t\tif err := devicerequest.ClientIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"client_id\", err: fmt.Errorf(`db: validator failed for field \"DeviceRequest.client_id\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := drc.mutation.ClientSecret(); !ok {\n\t\treturn &ValidationError{Name: \"client_secret\", err: errors.New(`db: missing required field \"DeviceRequest.client_secret\"`)}\n\t}\n\tif v, ok := drc.mutation.ClientSecret(); ok {\n\t\tif err := devicerequest.ClientSecretValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"client_secret\", err: fmt.Errorf(`db: validator failed for field \"DeviceRequest.client_secret\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := drc.mutation.Expiry(); !ok {\n\t\treturn &ValidationError{Name: \"expiry\", err: errors.New(`db: missing required field \"DeviceRequest.expiry\"`)}\n\t}\n\treturn nil\n}", "func parseClientHello(data []byte) (ret *ClientHello, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = errors.New(\"Malformed ClientHello\")\n\t\t}\n\t}()\n\n\tif !bytes.Equal(data[0:3], []byte{0x16, 0x03, 0x01}) {\n\t\treturn ret, errors.New(\"wrong TLS1.3 handshake magic bytes\")\n\t}\n\n\tpeeled := make([]byte, len(data)-5)\n\tcopy(peeled, data[5:])\n\tpointer := 0\n\t// Handshake Type\n\thandshakeType := peeled[pointer]\n\tif handshakeType != 0x01 {\n\t\treturn ret, errors.New(\"Not a ClientHello\")\n\t}\n\tpointer += 1\n\t// Length\n\tlength := int(binary.BigEndian.Uint32(append([]byte{0x00}, peeled[pointer:pointer+3]...)))\n\tpointer += 3\n\tif length != len(peeled[pointer:]) {\n\t\treturn ret, errors.New(\"Hello length doesn't match\")\n\t}\n\t// Client Version\n\tclientVersion := peeled[pointer : pointer+2]\n\tpointer += 2\n\t// Random\n\trandom := peeled[pointer : pointer+32]\n\tpointer += 32\n\t// Session ID\n\tsessionIdLen := int(peeled[pointer])\n\tpointer += 1\n\tsessionId := peeled[pointer : pointer+sessionIdLen]\n\tpointer += sessionIdLen\n\t// Cipher Suites\n\tcipherSuitesLen := int(binary.BigEndian.Uint16(peeled[pointer : pointer+2]))\n\tpointer += 2\n\tcipherSuites := peeled[pointer : pointer+cipherSuitesLen]\n\tpointer += cipherSuitesLen\n\t// Compression Methods\n\tcompressionMethodsLen := int(peeled[pointer])\n\tpointer += 1\n\tcompressionMethods := peeled[pointer : pointer+compressionMethodsLen]\n\tpointer += compressionMethodsLen\n\t// Extensions\n\textensionsLen := int(binary.BigEndian.Uint16(peeled[pointer : pointer+2]))\n\tpointer += 2\n\textensions, err := parseExtensions(peeled[pointer:])\n\tret = &ClientHello{\n\t\thandshakeType,\n\t\tlength,\n\t\tclientVersion,\n\t\trandom,\n\t\tsessionIdLen,\n\t\tsessionId,\n\t\tcipherSuitesLen,\n\t\tcipherSuites,\n\t\tcompressionMethodsLen,\n\t\tcompressionMethods,\n\t\textensionsLen,\n\t\textensions,\n\t}\n\treturn\n}", "func protocolToMessage(c net.Conn, s string) {\n\tfmt.Print(\"Recieved: \" + s) // Used to verify what was being received\n\tmessage := strings.Split(s, \"\\t\") // Split the received message into an array of strings by \\t\n\tusername := \"\" // Empty string that will contain the specified username\n\tregisterCount := 0 // Counter for the amount of times TCCHAT_REGISTER is received\n\t\n\tif len(message) > 1 { // If message has only one string in it, it's necessarily a disconnect call\n\t\t// Replace \"\\n\" in message by \"\" as many times as necessary (-1)\n\t\t// if -1 was 'n', it would replace \"\\n\" only 'n' times, no more\n\t\tusername = strings.Replace(message[1], \"\\n\", \"\", -1)\n\t}\n\t\n\t// Check if the connection has only sent 1 TCCHAT_REGISTER\n\tif registerCount > 1 {\n\t\tfmt.Println(\"Corrupted connection detected !\")\n\t\tc.Close()\n\t\tfmt.Println(\"Connection closed\")\n\t}\n\t// Prettier if else if loop checking the contents of message[0] which contains the prefix\n\t// of the protocol message\n\tswitch message[0] {\n\tcase \"TCCHAT_REGISTER\": // A new user has joined the server\n\t\tregisterUser(c, username)\n\t\tregisterCount += 1 // Increment counter by 1\n\t\t\n\tcase \"TCCHAT_MESSAGE\": // A message has been received from a connected client\n\t\tsendMessageAll(c, message[1])\n\n\tcase \"TCCHAT_DISCONNECT\\n\": // In case of a disconnect, the \\n will still be part of the message\n\t\tuserDisconnect(userMap[c])\n\t\t\n\tdefault: // Message received is not of the correct form, close the connection\n\t\tif err := c.Close(); err == nil {\n\t\t\tc.Close()\n\t\t}\n\t}\n}" ]
[ "0.6723285", "0.54596674", "0.5294594", "0.52536565", "0.51366204", "0.5085916", "0.5051011", "0.5046358", "0.5041267", "0.5021834", "0.4987268", "0.49794912", "0.49775088", "0.49362358", "0.49338272", "0.48983753", "0.4854109", "0.48525935", "0.48380697", "0.48374146", "0.48324272", "0.48163348", "0.4814855", "0.48063746", "0.4802162", "0.47986025", "0.4797061", "0.4787658", "0.47791338", "0.4769519", "0.47691986", "0.47532058", "0.4752772", "0.47455505", "0.47399482", "0.47373974", "0.47339562", "0.4732966", "0.47295094", "0.47240534", "0.47182813", "0.47143334", "0.4713206", "0.47111976", "0.47077596", "0.470217", "0.46924782", "0.46915996", "0.46867526", "0.46855167", "0.46797433", "0.46696657", "0.46662554", "0.46646616", "0.46602532", "0.4656226", "0.4653132", "0.46474868", "0.46457267", "0.46456027", "0.46423963", "0.4636705", "0.46324468", "0.46250942", "0.46208698", "0.4620645", "0.46164155", "0.46130005", "0.4612249", "0.4608837", "0.46077555", "0.460341", "0.46020117", "0.45961636", "0.45927694", "0.4585896", "0.45808572", "0.4577761", "0.4576241", "0.45706388", "0.45696044", "0.4565731", "0.4565683", "0.4565337", "0.456067", "0.4554036", "0.45524392", "0.45511997", "0.45464468", "0.45408016", "0.45402622", "0.45349196", "0.4531137", "0.45297164", "0.4528798", "0.45275936", "0.45232782", "0.4516785", "0.4514209", "0.4509083" ]
0.676011
0
decode converts byte array to string and returns it.
func decode(array []byte) string { var tmp string for _, elem := range array { tmp += strconv.Itoa(int(elem)) } return tmp }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Decode(s []byte) string {\n\ts, _ = decode(s)\n\treturn string(s)\n}", "func (enc *simpleEncoding) Decode(raw []byte) string {\n\tdata, _ := enc.NewDecoder().Bytes(raw)\n\treturn string(data)\n}", "func StringBytes(b []byte) string { return *(*string)(Pointer(&b)) }", "func (b *baseSemanticUTF8Base64) Decode() string {\n\treturn b.decoded\n}", "func StringDecode(ctx context.Context, b []byte, obj interface{}) error {\n\tv := obj.(*string)\n\t*v = string(b)\n\treturn nil\n}", "func (d *Decoder) Decode(input []byte) ([]byte, Encoding) {\n\tif len(input) == 0 {\n\t\treturn []byte{}, None\n\t}\n\n\tunmarshalled := &protodec.Empty{}\n\n\tif d.proto {\n\t\tif err := proto.Unmarshal(input, unmarshalled); err == nil {\n\t\t\t// TODO: remove control characters (unfortunately, they are all valid strings here)\n\t\t\treturn []byte(unmarshalled.String()), Proto\n\t\t}\n\t}\n\n\tif d.bitDec {\n\t\tbyteIn := strings.Trim(string(input), \"[]\") // [32 87 111 114 108 100] -> 32 87 111 114 108 100\n\n\t\tif b, err := Base2AsBytes(byteIn); err == nil {\n\t\t\treturn b, Bit\n\t\t}\n\t}\n\n\t// byte before hex, hex might contains letters, which are not valid in byte dec\n\tif d.byteDec {\n\t\tbyteIn := strings.Trim(string(input), \"[]\") // [32 87 111 114 108 100] -> 32 87 111 114 108 100\n\n\t\tif b, err := Base10AsBytes(byteIn); err == nil {\n\t\t\treturn b, Byte\n\t\t}\n\t}\n\n\t// hex after byte\n\tif d.hex {\n\t\thexIn := strings.TrimSpace(string(input)) // e.g. new line\n\t\thexIn = strings.TrimPrefix(hexIn, \"0x\") // hex prefix\n\t\thexIn = strings.Replace(hexIn, \" \", \"\", -1) // bd b2 3d bc 20 e2 8c 98 -> bdb23dbc20e28c98\n\n\t\tif b, err := hex.DecodeString(hexIn); err == nil {\n\t\t\treturn b, Hex\n\t\t}\n\t}\n\n\t// TODO: many false-positives. Decodes it when no base64 was given.\n\t// Keep it as one of the last decodings.\n\tif d.base64 {\n\t\tif b, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(input))); err == nil {\n\t\t\treturn b, Base64\n\t\t}\n\t}\n\n\treturn input, None\n}", "func String(b []byte) (s string) {\n\treturn string(b)\n}", "func decodeByteArray(s *Stream, val reflect.Value) error {\n\t// getting detailed information on encoded data\n\tkind, size, err := s.Kind()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// getting the length of declared ByteArray\n\tvlen := val.Len()\n\n\tswitch kind {\n\t// put a byte in a byte array\n\tcase Byte:\n\t\tif vlen == 0 {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif vlen > 1 {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// get the content and stores in the index 0\n\t\tbv, _ := s.Uint()\n\t\tval.Index(0).SetUint(bv)\n\n\t// put string in a byte array\n\tcase String:\n\t\tif uint64(vlen) < size {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif uint64(vlen) > size {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// transfer the byte array to byte slice and place string content inside\n\t\tslice := val.Slice(0, vlen).Interface().([]byte)\n\t\tif err := s.readFull(slice); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// reject cases where single byte encoding should have been used\n\t\tif size == 1 && slice[0] < 128 {\n\t\t\treturn wrapStreamError(ErrCanonSize, val.Type())\n\t\t}\n\t// byte array should not contain any list\n\tcase List:\n\t\treturn wrapStreamError(ErrExpectedString, val.Type())\n\t}\n\treturn nil\n}", "func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }", "func convertBytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func decodeString(b byteReader) (string, error) {\n\tlength, err := binary.ReadVarint(b)\n\tif length < 0 {\n\t\terr = fmt.Errorf(\"found negative string length during decoding: %d\", length)\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf := getBuf(int(length))\n\tdefer putBuf(buf)\n\n\tif _, err := io.ReadFull(b, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}", "func Decode(in string) (string, error) {\n\tout, err := Client().Decode(in)\n\tTrace(\"Decode\", err, logrus.Fields{\"in\": in, \"out\": out})\n\treturn string(out), err\n}", "func (b *Bytes) Decode(value string) error {\n\tv, err := humanize.ParseBytes(value)\n\t*b = Bytes(v)\n\treturn err\n}", "func Decode(value []byte) ([]byte, error) {\n var length int = len(value)\n decoded := make([]byte, base64.URLEncoding.DecodedLen(length))\n\n n, err := base64.URLEncoding.Decode(decoded, value)\n if err != nil {\n return nil, err\n }\n return decoded[:n], nil\n}", "func DecodeToString(src string) (retVal string, err error) {\n\tretBytes, err := coder.DecodeString(src)\n\tretVal = string(retBytes)\n\treturn\n}", "func String(b []byte) string {\n\treturn string(b)\n}", "func decode(s string) string {\n\tr := s\n\tfor _, tr := range codecValues {\n\t\tif strings.Index(r, tr.encoded) >= 0 {\n\t\t\tr = strings.Replace(r, tr.encoded, tr.decoded, -1)\n\t\t}\n\t}\n\treturn r\n}", "func DecodeToString(data string) (string, error) {\n\tb, err := DecodeString(data)\n\treturn string(b), err\n}", "func String(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func ByteToString(b *[]byte) string {\n\tresult := *b\n\treturn string(result[:])\n}", "func decodeSimpleString(r BytesReader) (interface{}, error) {\n\tv, err := r.ReadBytes('\\r')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Presume next byte was \\n\n\t_, err = r.ReadByte()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(v[:len(v)-1]), nil\n}", "func Decode(src []byte) (dst [10]byte)", "func (d *Decoder) String() string {\n\tdata := d.Bytes()\n\treturn unsafe.BytesToString(data)\n}", "func Decode(b string) ([]byte, error) {\n\treturn DecodeAlphabet(b, BTCAlphabet)\n}", "func (d LEByteDecoder) DecodeString(buf *bytes.Reader) (string, error) {\n\tvar err error\n\tvar strSize uint32\n\t// String format is: [size|string] where size is a u32.\n\tif strSize, err = d.DecodeUint32(buf); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decoding string\")\n\t}\n\tvar value []uint8\n\tif value, err = d.DecodeUint8Array(buf, int(strSize)); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decoding string\")\n\t}\n\treturn string(value), nil\n}", "func ByteToStr(inputBytes []byte) string {\r\n\treturn string(inputBytes[:])\r\n}", "func decode(k *KeyValue) {\n\tif k.Encoding == \"binary\" {\n\t\tdecoded, err := base64.StdEncoding.DecodeString(k.Data)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error decoding base64 key/value\")\n\t\t}\n\t\tk.Data = string(decoded)\n\t}\n}", "func base64Decode(b string) string {\n\tdata, err := base64.StdEncoding.DecodeString(b)\n\tif err != nil {\n\t\treturn string(b)\n\t}\n\treturn string(data)\n}", "func decodeByteSlice(s *Stream, val reflect.Value) error {\n\t// b = byte slice contained string content\n\tb, err := s.Bytes()\n\tif err != nil {\n\t\treturn wrapStreamError(err, val.Type())\n\t}\n\tval.SetBytes(b)\n\treturn nil\n}", "func (cdc OctetsCodec) Decode(b []byte) (v interface{}, s string, err error) {\n\treturn b, string(b), nil\n}", "func DecodeToString(payload string) string {\n\tsDec, _ := b64.StdEncoding.DecodeString(payload)\n\treturn string(sDec)\n}", "func Decode(str string) string {\n\trs := []rune(str)\n\tvar b []uint8\n\tfor _, r := range rs {\n\t\tb1 := r & ((1 << 8) - 1)\n\t\tb = append(b, uint8(b1))\n\n\t\tb2val := r - b1\n\t\tif b2val != unknownByteCodePoint {\n\t\t\tb2 := decodeMap[b2val]\n\t\t\tb = append(b, b2)\n\t\t}\n\t}\n\ts := string(b)\n\treturn s\n}", "func parseString(content []byte) string {\n return string(content)\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func bytesToStr(data []byte) string {\n\treturn string(data)\n}", "func (s String) Decode(r io.Reader) (interface{}, error) {\n\tstr, err := util.ReadString(r)\n\treturn String(str), err\n}", "func StringFromBytes(b []byte) String {\n\treturn StringFromString(string(b))\n}", "func (s RawSnapshot) DecodeToString() (string, error) {\n\t// Base64 decode\n\tb64, err := base64.StdEncoding.DecodeString(s.Data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// ZStandard decompression\n\tdecomp, err := ioutil.ReadAll(zstd.NewReader(bytes.NewReader(b64)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decomp), err\n}", "func BytesToStr(in []byte, decoder *encoding.Decoder) (string, error) {\n\ti := bytes.NewReader(in)\n\to := transform.NewReader(i, decoder)\n\td, e := ioutil.ReadAll(o)\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\treturn string(d), nil\n}", "func ByteArrayToString(buf []byte) string {\n\treturn *(*string)(unsafe.Pointer(&buf))\n}", "func Base64Decode(encoded string) (string, error) {\n\tresult, err := base64.StdEncoding.DecodeString(encoded)\n\treturn string(result), err\n}", "func DecodeString(data string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(data)\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func Bytes2str(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func B64Decode(data string) []byte {\n\tdec, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn dec\n}", "func (b ByteArray) Decode(r io.Reader) (interface{}, error) {\n\tl, err := util.ReadVarInt(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := make([]byte, int(l))\n\t_, err = io.ReadFull(r, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func bytesToString(value []byte) string {\n\tn := bytes.IndexByte(value, 0)\n\tif n < 0 {\n\t\treturn \"\"\n\t}\n\n\treturn strn(value, n)\n}", "func decodeString(s *Stream, val reflect.Value) error {\n\t// get the content of the string\n\tb, err := s.Bytes()\n\tif err != nil {\n\t\treturn wrapStreamError(err, val.Type())\n\t}\n\n\t// stringify the content, and passed in to val\n\tval.SetString(string(b))\n\treturn nil\n}", "func base64decode(v string) string {\n\tdata, err := base64.StdEncoding.DecodeString(v)\n\tif err != nil {\n\t\tLogger.Println(\"[ERROR] Failed decoding base64 encoded string\", err)\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}", "func byteSliceToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func Decode(message string) string {\n\t// Stage 1, unreverse the letters\n\t// we'll need to create a temporary slice to help us with that\n\ttmpSlice := []byte{}\n\t// we'll also need to extract the length of the original string, we do that by getting the last part of the string after the _\n\tcharacters, _ := strconv.Atoi(strings.Split(message, \"_\")[1])\n\t// then we loop backwards\n\tfor i := characters - 1; i >= 0; i-- {\n\t\t// add each letter backwards to the slice\n\t\ttmpSlice = append(tmpSlice, message[i])\n\t}\n\t// then we loop again and shift each letter back 1\n\tfor i := 0; i < characters; i++ {\n\t\ttmpSlice[i] = tmpSlice[i] - 1\n\t}\n\t// then we return it as a string\n\treturn string(tmpSlice)\n}", "func DecodeB64(msg []byte) ([]byte, error) {\n\tb64 := base64.StdEncoding\n\tencoded := bytes.TrimSpace(msg)\n\trest := make([]byte, b64.DecodedLen(len(encoded)))\n\tif n, err := b64.Decode(rest, encoded); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\trest = rest[:n]\n\t}\n\treturn rest, nil\n}", "func ByteSlice2String(bs []byte) string {\n\treturn *(*string)(unsafe.Pointer(&bs))\n}", "func ToString(byteStr []byte) string {\n\tn := bytes.IndexByte(byteStr, 0)\n\treturn string(byteStr[:n])\n}", "func DecodeString(b []byte) (*String, error) {\n\ts := &String{}\n\tif err := s.DecodeFromBytes(b); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func Decode(in string) ([]byte, error) {\n\to, err := b64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\t// maybe it's in the URL variant?\n\t\to, err = b64.URLEncoding.DecodeString(in)\n\t\tif err != nil {\n\t\t\t// ok, just give up...\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn o, nil\n}", "func (s *String) decode(b []byte) error {\n\tobj, err := DecodeObject(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif IsExpired(obj, Now()) {\n\t\treturn ErrKeyNotFound\n\t}\n\n\tif obj.Type != ObjectString {\n\t\treturn ErrTypeMismatch\n\t}\n\n\tif obj.Encoding != ObjectEncodingRaw {\n\t\treturn ErrTypeMismatch\n\t}\n\ts.Meta.Object = *obj\n\tif len(b) >= ObjectEncodingLength {\n\t\ts.Meta.Value = b[ObjectEncodingLength:]\n\t}\n\treturn nil\n}", "func Decode(value string) (string, error) {\n\tvalue = value\n\tdecoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))\n\tb, err := base64.URLEncoding.Decode(decoded, []byte(value))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded[:b]), nil\n}", "func DecodeString(encode, content string) (string, error) {\n\tif strings.EqualFold(\"base64\", encode) {\n\t\tdecode, err := base64.StdEncoding.DecodeString(content)\n\t\treturn string(decode), err\n\t}\n\n\treturn content, nil\n}", "func base64Decode(value string) (string, error) {\n\tres, err := base64.StdEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(res), nil\n}", "func bytesToString(bs []byte) string {\n\treturn *(*string)(unsafe.Pointer(&bs))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func ByteToString(b []byte) string {\n\tn := bytes.IndexByte(b, 0)\n\tif n == -1 {\n\t\treturn string(b[:])\n\t}\n\treturn string(b[:n])\n\n}", "func ConvertBase64StrToBytes(key string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(key)\n}", "func UnsafeBytesToStr(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func UnsafeBytesToStr(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func UnsafeBytesToStr(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func Decode(key []byte, b []byte) (m Message, err error) {\n\tif key != nil {\n\t\tb, err = crypt.Decrypt(b, key)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tb = compress.Decompress(b)\n\terr = json.Unmarshal(b, &m)\n\tif err == nil {\n\t\tif key != nil {\n\t\t\tlog.Debugf(\"read %s message (encrypted)\", m.Type)\n\t\t} else {\n\t\t\tlog.Debugf(\"read %s message (unencrypted)\", m.Type)\n\t\t}\n\t}\n\treturn\n}", "func (cdc AddressCodec) Decode(b []byte) (v interface{}, s string, err error) {\n\tip := net.IP(b)\n\treturn ip, ip.String(), nil\n\n}", "func DecodeBytes(in []byte, objs ...interface{}) (err error) {\n\tbuf := bytes.NewBuffer(in)\n\terr = Decode(buf, objs...)\n\treturn\n}", "func (t *RawStringTranscoder) Decode(bytes []byte, flags uint32, out interface{}) error {\n\tvalueType, compression := gocbcore.DecodeCommonFlags(flags)\n\n\t// Make sure compression is disabled\n\tif compression != gocbcore.NoCompression {\n\t\treturn errors.New(\"unexpected value compression\")\n\t}\n\n\t// Normal types of decoding\n\tif valueType == gocbcore.BinaryType {\n\t\treturn errors.New(\"only string datatype is supported by RawStringTranscoder\")\n\t} else if valueType == gocbcore.StringType {\n\t\tswitch typedOut := out.(type) {\n\t\tcase *string:\n\t\t\t*typedOut = string(bytes)\n\t\t\treturn nil\n\t\tcase *interface{}:\n\t\t\t*typedOut = string(bytes)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn errors.New(\"you must encode a string in a string or interface\")\n\t\t}\n\t} else if valueType == gocbcore.JSONType {\n\t\treturn errors.New(\"only string datatype is supported by RawStringTranscoder\")\n\t}\n\n\treturn errors.New(\"unexpected expectedFlags value\")\n}", "func decode(field reflect.Value, value string) error {\n\tif !canDecode(field) {\n\t\treturn errors.New(\"value cannot decode itself\")\n\t}\n\n\td, ok := field.Interface().(Decoder)\n\tif !ok && field.CanAddr() {\n\t\td, ok = field.Addr().Interface().(Decoder)\n\t}\n\n\tif ok {\n\t\treturn d.Decode(value)\n\t}\n\n\tt, ok := field.Interface().(encoding.TextUnmarshaler)\n\tif !ok && field.CanAddr() {\n\t\tt, ok = field.Addr().Interface().(encoding.TextUnmarshaler)\n\t}\n\n\tif ok {\n\t\treturn t.UnmarshalText([]byte(value))\n\t}\n\n\treturn errors.New(\"failed to find a decoding type\")\n}", "func BytesString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func DecodeBytes(b []byte, val interface{}) error {\n\t// initialize byte reader\n\tr := bytes.NewReader(b)\n\tif err := NewStream(r, uint64(len(b))).Decode(val); err != nil {\n\t\treturn err\n\t}\n\tif r.Len() > 0 {\n\t\treturn ErrMoreThanOneValue\n\t}\n\treturn nil\n}", "func BytetoStr(str []byte) string {\n\treturn string(str)\n}", "func (b *Bytes) String() string {\n\treturn fmt.Sprint(*b)\n}", "func Decode(stringToDecode string, shiftFactor int, injectionFactor int) string {\n\tstrx := string_to_rune_slice.StringToRuneSlice(stringToDecode)\n\tsrx := unshift_rune_slice.UnshiftRuneSlice(strx, shiftFactor)\n\trrr := remove_random_runes.RemoveRandomRunes(srx, injectionFactor)\n\trxts := rune_slice_to_string.RuneSliceToString(rrr)\n\treturn rxts\n}", "func decode(id *ID, src []byte) {\n\tencoder.Decode(id[:], src)\n}", "func Base64Decode(encoded string) ([]byte, error) {\n\treturn base64.URLEncoding.DecodeString(encoded)\n}", "func (s *String) DecodeFromBytes(b []byte) error {\n\tif len(b) < 4 {\n\t\treturn errors.NewErrTooShortToDecode(s, \"should be longer than 4 bytes\")\n\t}\n\n\ts.Length = int32(binary.LittleEndian.Uint32(b[:4]))\n\tif s.Length <= 0 {\n\t\treturn nil\n\t}\n\ts.Value = b[4 : 4+s.Length]\n\treturn nil\n}", "func B64DecodeStrToByte(inputString string) ([]byte, error) {\r\n\tdecoded, err := base64.StdEncoding.DecodeString(inputString)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn decoded, nil\r\n}", "func byteString(b []byte) string {\n\tif len(b) < 1 {\n\t\treturn \"\"\n\t}\n\n\ts := make([]byte, len(b)*3-1)\n\ti, j := 0, 0\n\tfor n := len(b) - 1; i < n; i, j = i+1, j+3 {\n\t\ts[j+0] = hex[(b[i] >> 4)]\n\t\ts[j+1] = hex[(b[i] & 0x0f)]\n\t\ts[j+2] = ' '\n\t}\n\ts[j+0] = hex[(b[i] >> 4)]\n\ts[j+1] = hex[(b[i] & 0x0f)]\n\treturn string(s)\n}", "func BytesToStr(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func BASE64DecodeString(str string) string {\n\tresult, _ := base64.StdEncoding.DecodeString(str)\n\treturn string(result)\n}", "func cleanBytesToString(s []byte) string {\n\treturn strings.SplitN(string(s), \"\\000\", 2)[0]\n}", "func Decode(src []byte) (dst []byte, err error) {\n\tsize := coder.DecodedLen(len(src))\n\tbuf := make([]byte, size)\n\t_, err = coder.Decode(buf, src)\n\tdst = buf[:size-1]\n\treturn\n}", "func (b Bytes) ToString() string {\n\treturn string(b)\n}", "func Decode(data []byte) ([]byte, error) {\n\tvar (\n\t\tsrc = make([]byte, base64.StdEncoding.DecodedLen(len(data)))\n\t\tn, err = base64.StdEncoding.Decode(src, data)\n\t)\n\tif err != nil {\n\t\terr = gerror.Wrap(err, `base64.StdEncoding.Decode failed`)\n\t}\n\treturn src[:n], err\n}", "func BytesDecode(ctx context.Context, b []byte, obj interface{}) error {\n\tv := obj.(*[]byte)\n\t*v = b[:]\n\treturn nil\n}", "func (store *SessionCookieStore) decode(src string) ([]byte, error) {\n\tsize := len(src)\n\trem := (4 - size%4) % 4\n\tbuf := make([]byte, size+rem)\n\tcopy(buf, src)\n\tfor i := 0; i < rem; i++ {\n\t\tbuf[size+i] = '='\n\t}\n\tn, err := base64.URLEncoding.Decode(buf, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf[:n], nil\n}", "func DecodeString(data string) ([]byte, error) {\n\treturn Decode([]byte(data))\n}", "func BytesToString(data []byte) string {\n\treturn string(data[:])\n}", "func Decode(code string) string {\n\t// Don't decode empty strings\n\tif code == \"\" {\n\t\treturn \"\"\n\t}\n\tunhexedBytes, err := hex.DecodeString(code)\n\t//unhexedBytes, err := base32.StdEncoding.DecodeString(code)\n\tif err != nil {\n\t\tpanic(\"Could not hexdecode \" + code + \": \" + err.Error())\n\t}\n\tbuf := bytes.NewBuffer(unhexedBytes)\n\tdecompressorReader := flate.NewReader(buf)\n\tdecompressedBytes, err := ioutil.ReadAll(decompressorReader)\n\tdecompressorReader.Close()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvalue := string(decompressedBytes)\n\treturn value\n}" ]
[ "0.679415", "0.6686412", "0.6151728", "0.60770327", "0.59824395", "0.5945909", "0.59298795", "0.5899968", "0.58952236", "0.58858275", "0.587236", "0.5862185", "0.5832764", "0.5819838", "0.5808772", "0.5801181", "0.5795612", "0.57819957", "0.5781549", "0.57575077", "0.57296044", "0.57064664", "0.56832284", "0.5645887", "0.5644221", "0.56429464", "0.56304747", "0.562468", "0.55971414", "0.55926996", "0.5584455", "0.5578931", "0.55787396", "0.5541099", "0.5524597", "0.55241156", "0.5514", "0.5507188", "0.548919", "0.5483934", "0.5482698", "0.5474056", "0.54704595", "0.5461948", "0.5428806", "0.5419586", "0.54151374", "0.5397582", "0.5397527", "0.5381747", "0.53777844", "0.535027", "0.5346722", "0.53464127", "0.53274286", "0.53215766", "0.5320905", "0.530586", "0.52887803", "0.52705944", "0.52643836", "0.5244243", "0.5244243", "0.5244243", "0.5244243", "0.5244243", "0.5244243", "0.5244243", "0.5244243", "0.52379173", "0.52361906", "0.5234326", "0.5234326", "0.5234326", "0.52113205", "0.5208025", "0.52069044", "0.52056694", "0.5205378", "0.52042276", "0.51995724", "0.51947564", "0.5194027", "0.51812035", "0.51807135", "0.51803863", "0.5172952", "0.51716745", "0.5164749", "0.5164472", "0.5164167", "0.5159372", "0.515754", "0.514211", "0.5133941", "0.5130545", "0.5120787", "0.51102906", "0.51056623", "0.5100793" ]
0.68240315
0
overrideFile is for when the srv is udpatning lang files
func overrideFile(filename, newcontent string) { file, fileErr := os.Create(filename) //open given file if fileErr != nil { fmt.Println(fileErr) } file.WriteString(newcontent) //write the new content to the file file.Close() return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func updateFile(connection net.Conn) {\n\tfmt.Println(\"Updating file...\")\n\tlang := make([]byte, 10)\n\tvar content string //content for the new file\n\t\n\tconnection.Read(lang) //read what lang file to change\n\n\t\n\t\n\ttmp := make([]byte, 255) //tmp for holdning the content from the srv\n\tfor {\n\t\tread,_ := connection.Read(tmp) //reads what the srv wants to update the file with\n\t\tif tmp[read-1] == 4 { //the update from the srv will end will 4 ascii = end of transmission\n\t\t\tbreak\n\t\t}\n\t\tcontent += string(tmp) //store the content of the file\n\t}\n\t\n\n\t//search for the input lang and if we can change it.\n\texist := false\n\tfor _,currentlang := range languages {\n\t\tif currentlang == strings.TrimSpace(string(lang)) {\n\t\t\texist = true\n\t\t}\n\t}\n\n\t//the lang did exists! so we append the lang to the global languages list.\n\tif exist == false {\n\t\tlanguages = append(languages, strings.TrimSpace(string(lang)))\n\t}\n\n\t//We will override already existing languages and create a new file if its a totally new language\n\tfilename := strings.TrimSpace(string(lang)) + \".txt\"\n\n\tnewcontent := string(content) //the content from the srv\n\t\n\toverrideFile(filename, newcontent) //overridefile will take all the content and replace all content with the new content\n\n\n\t// check if the clients current lang is the new lang\n\tif custlang == strings.TrimSpace(string(lang)) {\n\t\ttmplines := make([]string,0) //we must replace all old lines from the lang file\n\t\tfile, err := os.Open(filename) //open the file\n\t\tcheck(err)\n\t\t\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\ttmplines = append(tmplines, scanner.Text())\n\t\t}\n\t\tfile.Close()\n\t\t*(&lines) = tmplines //replace all old lines with the new content \n\t\tcheck(scanner.Err())\n\t}\n\t\n}", "func getOverride(log *base.LogObject, filename string) string {\n\tif _, err := os.Stat(filename); err != nil {\n\t\treturn \"\"\n\t}\n\tcontents, err := os.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Errorf(\"getOverride(%s) failed: %s\\n\", filename, err)\n\t\treturn \"\"\n\t}\n\treturn strings.TrimSpace(string(contents))\n}", "func (p *Parser) LoadConfigFileOverride(path string) (*File, hcl.Diagnostics) {\n\treturn p.loadConfigFile(path, true)\n}", "func (c *Lang) applyFile(code string) (error, string) {\n\n\t_, header, err := c.GetFile(\"file\")\n\tif err != nil {\n\t\treturn err, T(\"lang_nofile\")\n\t}\n\n\ta := strings.Split(header.Filename, \".\")\n\tif l := len(a); l < 2 || strings.ToLower(a[l-1]) != \"json\" {\n\t\treturn errors.New(\"client validation by file type hacked\"), T(\"lang_badfile\")\n\t}\n\n\ts := c.langFileName(\"tmp_dir\", code)\n\n\terr = c.SaveToFile(\"file\", s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\terr = i18n.LoadTranslationFile(s)\n\tdefer os.Remove(s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\ts2 := c.langFileName(\"lang::folder\", code)\n\terr = c.SaveToFile(\"file\", s2)\n\tif err == nil {\n\t\terr = i18n.LoadTranslationFile(s2)\n\t}\n\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\treturn nil, \"\"\n}", "func (conf blah) SetOverride(key string, def string) {\n\tviper.Set(key, def)\n}", "func (c *configuration) cmdlineOverride(opts *cliOptions) {\n\t// Populate options that can be provided on both the commandline and config.\n\tif opts.Port > 0 {\n\t\tc.Port = int(opts.Port)\n\t}\n\tif opts.Rank != nil {\n\t\t// global rank parameter should only apply to first I/O service\n\t\tc.Servers[0].Rank = opts.Rank\n\t}\n\tif opts.Insecure {\n\t\tc.TransportConfig.AllowInsecure = true\n\t}\n\t// override each per-server config\n\tfor i := range c.Servers {\n\t\tsrv := &c.Servers[i]\n\n\t\tif opts.MountPath != \"\" {\n\t\t\t// override each per-server config in addition to global value\n\t\t\tc.ScmMountPath = opts.MountPath\n\t\t\tsrv.ScmMount = opts.MountPath\n\t\t} else if srv.ScmMount == \"\" {\n\t\t\t// if scm not specified for server, apply global\n\t\t\tsrv.ScmMount = c.ScmMountPath\n\t\t}\n\t\tif opts.Cores > 0 {\n\t\t\tlog.Debugf(\"-c option deprecated, please use -t instead\")\n\t\t\tsrv.Targets = int(opts.Cores)\n\t\t}\n\t\t// Targets should override Cores if specified in cmdline or\n\t\t// config file.\n\t\tif opts.Targets > 0 {\n\t\t\tsrv.Targets = int(opts.Targets)\n\t\t}\n\t\tif opts.NrXsHelpers != nil {\n\t\t\tsrv.NrXsHelpers = int(*opts.NrXsHelpers)\n\t\t}\n\t\tif opts.FirstCore > 0 {\n\t\t\tsrv.FirstCore = int(opts.FirstCore)\n\t\t}\n\t}\n\n\tif opts.Group != \"\" {\n\t\tc.SystemName = opts.Group\n\t}\n\tif opts.SocketDir != \"\" {\n\t\tc.SocketDir = opts.SocketDir\n\t}\n\tif opts.Modules != nil {\n\t\tc.Modules = *opts.Modules\n\t}\n\tif opts.Attach != nil {\n\t\tc.Attach = *opts.Attach\n\t}\n\tif opts.Map != nil {\n\t\tc.SystemMap = *opts.Map\n\t}\n}", "func overrideFile(fileName string, err error, contents []byte, perm os.FileMode, vfn verify.VerifyFn) error {\n\ttimeNano := time.Now().UnixNano()\n\t// write the new contents to a temporary file\n\tnewFileName := fmt.Sprintf(\"%s.tmp%d\", fileName, timeNano)\n\tlog.Printf(\"Writing contents to temporary file %s...\\n\", newFileName)\n\terr = ioutil.WriteFile(newFileName, contents, perm)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to write new file %s, err: %v\\n\", newFileName, err)\n\t\treturn err\n\t}\n\n\t// Sanity check the new file against the existing one\n\tif vfn != nil {\n\t\terr = vfn(fileName, newFileName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"invalid content: %q, error: %v\", newFileName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// move the contents of the old file to a backup file\n\tbakFileName := fmt.Sprintf(\"%s.bak%d\", fileName, timeNano)\n\tlog.Printf(\"Renaming original file %s to backup file %s...\\n\", fileName, bakFileName)\n\terr = os.Rename(fileName, bakFileName)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to rename file %s to %s, err: %v\\n\", fileName, bakFileName, err)\n\t\treturn err\n\t}\n\t// move the new contents to the original location\n\tlog.Printf(\"Renaming temporary file %s to requested file %s...\\n\", newFileName, fileName)\n\terr = os.Rename(newFileName, fileName)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to rename file %s to %s, err: %v\\n\", newFileName, fileName, err)\n\t\t// before returning try to restore the original file\n\t\tos.Rename(bakFileName, fileName)\n\t\treturn err\n\t}\n\t// remove the temporary backup file\n\tlog.Printf(\"Removing backup file %s...\\n\", bakFileName)\n\tos.Remove(bakFileName)\n\treturn nil\n}", "func OverrideLocale(loc *Locale) error {\n\tif err := loc.Check(); err != nil {\n\t\treturn err\n\t}\n\tif _, exists := locales[loc.ISOCode]; !exists {\n\t\treturn fmt.Errorf(\"locale with ISO code %s does not exist\", loc.ISOCode)\n\t}\n\tlocales[loc.ISOCode] = loc\n\tupdateAllLanguageList()\n\treturn nil\n}", "func FromFileWithOverride(path string) config.Provider {\n\tf1 := config.FromFile(path)\n\tf2 := config.FromFile(path + \".override\")\n\n\treturn func() ([]string, error) {\n\t\td, err := f1()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\td2, err := f2()\n\n\t\t// don't care about .override not existing\n\t\tif err == nil {\n\t\t\td = append(d, d2...)\n\t\t}\n\n\t\treturn d, nil\n\t}\n}", "func (g *altsTC) OverrideServerName(serverNameOverride string) error {\n\tg.info.ServerName = serverNameOverride\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 pythonConfigOverrideAction(app *DdevApp) error {\n\tif app.WebserverType == nodeps.WebserverDefault {\n\t\tapp.WebserverType = nodeps.WebserverNginxGunicorn\n\t}\n\tif app.Database == DatabaseDefault {\n\t\tapp.Database.Type = nodeps.Postgres\n\t\tapp.Database.Version = nodeps.Postgres14\n\t}\n\treturn nil\n}", "func updateUserdataFile(driverOpts *rpcdriver.RPCFlags, machineName, hostname, userdataFlag, osFlag, customInstallScript string) error {\n\tvar userdataContent []byte\n\tvar err error\n\tuserdataFile := driverOpts.String(userdataFlag)\n\tmachineOS := driverOpts.String(osFlag)\n\n\tif userdataFile == \"\" {\n\t\t// Always convert to cloud config if user data is not provided\n\t\tuserdataContent = []byte(\"#cloud-config\")\n\t} else {\n\t\tuserdataContent, err = os.ReadFile(userdataFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcustomScriptContent, err := os.ReadFile(customInstallScript)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Remove the shebang\n\tcustomScriptContent = regexp.MustCompile(`^#!.*\\n`).ReplaceAll(customScriptContent, nil)\n\n\tmodifiedUserdataFile, err := ioutil.TempFile(\"\", \"modified-user-data\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[updateUserdataFile] unable to create tempfile [%v]\\nError returned\\n[%v]\", modifiedUserdataFile, err)\n\t}\n\tdefer modifiedUserdataFile.Close()\n\n\tif err := replaceUserdataFile(machineName, machineOS, hostname, userdataContent, customScriptContent, modifiedUserdataFile); err != nil {\n\t\treturn err\n\t}\n\n\tdriverOpts.Values[userdataFlag] = modifiedUserdataFile.Name()\n\n\treturn nil\n}", "func (e Environment) Override(name string, a ...interface{}) {\n\te[fmt.Sprintf(\"%s.override\", name)] = fmt.Sprint(a...)\n}", "func (e *Engine) handleOverride(o seesaw.Override) {\n\te.overrides[o.Target()] = o\n\te.distributeOverride(o)\n\tif o.State() == seesaw.OverrideDefault {\n\t\tdelete(e.overrides, o.Target())\n\t}\n}", "func SetLanguageFilePath(path string) string {\n\tlastPath := langFilePath\n\tlangFilePath = path\n\treturn lastPath\n}", "func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilder {\n\tiob.document = append(iob.document, bson.E{\"language_override\", languageOverride})\n\treturn iob\n}", "func loadMessageFile(path string) (err error) {\n\t// open the static i18n file\n\tf, err := pkger.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tb := bytes.NewBufferString(\"\")\n\t// copy to contents of the file to a buffer string\n\tif _, err = io.Copy(b, f); err != nil {\n\t\tpanic(err)\n\t}\n\t// read the contents of the file to a byte array\n\tout, _ := ioutil.ReadAll(b)\n\t// load the contents into context\n\tbundle.RegisterUnmarshalFunc(\"toml\", toml.Unmarshal)\n\t_, err = bundle.ParseMessageFileBytes(out, \"en.toml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *BundleDefinitionOptions) defaultBundleFiles(cxt *portercontext.Context) error {\n\tif o.File != \"\" { // --file\n\t\to.defaultCNABFile()\n\t} else if o.CNABFile != \"\" { // --cnab-file\n\t\t// Nothing to default\n\t} else {\n\t\tdefaultPath := filepath.Join(o.Dir, config.Name)\n\t\tmanifestExists, err := cxt.FileSystem.Exists(defaultPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not find a porter manifest at %s: %w\", defaultPath, err)\n\t\t} else if !manifestExists {\n\t\t\treturn nil\n\t\t}\n\n\t\to.File = defaultPath\n\t\to.defaultCNABFile()\n\t}\n\n\treturn nil\n}", "func (s *BaseSyslParserListener) EnterSysl_file(ctx *Sysl_fileContext) {}", "func addRonYamlFile(oYamlPath string, configs *[]*RawConfig) (string, error) {\n\tvar err error\n\tfoundConfigDir := \"\"\n\tif oYamlPath == \"\" {\n\t\toYamlPath, err = findConfigFile()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfoundConfigDir = filepath.Dir(oYamlPath)\n\t}\n\n\tif oYamlPath != \"\" {\n\t\toConfig, err := LoadConfigFile(oYamlPath)\n\t\tif err != nil {\n\t\t\tfmt.Println(color.Red(err.Error()))\n\t\t\treturn \"\", err\n\t\t}\n\t\toConfig.Filepath = oYamlPath\n\t\toConfig.Envs = strings.TrimSpace(oConfig.Envs)\n\t\toConfig.Remotes = strings.TrimSpace(oConfig.Remotes)\n\t\toConfig.Targets = strings.TrimSpace(oConfig.Targets)\n\t\t// prepend the override config\n\t\t*configs = append([]*RawConfig{oConfig}, *configs...)\n\t}\n\n\treturn foundConfigDir, err\n}", "func (e Environment) ProcessOverride(processType string, name string, a ...interface{}) {\n\te.Override(filepath.Join(processType, name), a...)\n}", "func (ts *TranslationService) loadFiles() {\n\tfor _, fileName := range ts.translationFiles {\n\t\terr := ts.i18bundle.LoadTranslationFile(fileName)\n\t\tif err != nil {\n\t\t\tts.logger.Warn(fmt.Sprintf(\"loading of translationfile %s failed: %s\", fileName, err))\n\t\t}\n\t}\n\n\tts.lastReload = time.Now()\n}", "func (r *Reply) File(file string) *Reply {\n\tif !filepath.IsAbs(file) {\n\t\tfile = filepath.Join(r.ctx.a.BaseDir(), file)\n\t}\n\tr.gzip = util.IsGzipWorthForFile(file)\n\tr.Render(&binaryRender{Path: file})\n\treturn r\n}", "func intercept(p *supervisor.Process, args Args) error {\n\tif os.Geteuid() != 0 {\n\t\treturn errors.New(\"ERROR: teleproxy must be run as root or suid root\")\n\t}\n\n\tsup := p.Supervisor()\n\n\tif args.dnsIP == \"\" {\n\t\tdat, err := ioutil.ReadFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\t\tif strings.Contains(line, \"nameserver\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\targs.dnsIP = fields[1]\n\t\t\t\tlog.Printf(\"TPY: Automatically set -dns=%v\", args.dnsIP)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif args.dnsIP == \"\" {\n\t\treturn errors.New(\"couldn't determine dns ip from /etc/resolv.conf\")\n\t}\n\n\tif args.fallbackIP == \"\" {\n\t\tif args.dnsIP == \"8.8.8.8\" {\n\t\t\targs.fallbackIP = \"8.8.4.4\"\n\t\t} else {\n\t\t\targs.fallbackIP = \"8.8.8.8\"\n\t\t}\n\t\tlog.Printf(\"TPY: Automatically set -fallback=%v\", args.fallbackIP)\n\t}\n\tif args.fallbackIP == args.dnsIP {\n\t\treturn errors.New(\"if your fallbackIP and your dnsIP are the same, you will have a dns loop\")\n\t}\n\n\ticeptor := interceptor.NewInterceptor(\"teleproxy\")\n\tapis, err := api.NewAPIServer(iceptor)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"API Server\")\n\t}\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: TRANSLATOR,\n\t\tRequires: []string{}, // XXX: this will need to include the api server once it is changed to not bind early\n\t\tWork: iceptor.Work,\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: API,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tapis.Start()\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\tapis.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNS_SERVER,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tsrv := dns.Server{\n\t\t\t\tListeners: dnsListeners(p, DNS_REDIR_PORT),\n\t\t\t\tFallback: args.fallbackIP + \":53\",\n\t\t\t\tResolve: func(domain string) string {\n\t\t\t\t\troute := iceptor.Resolve(domain)\n\t\t\t\t\tif route != nil {\n\t\t\t\t\t\treturn route.Ip\n\t\t\t\t\t} else {\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\terr := srv.Start(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no srv.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: PROXY,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\t// hmm, we may not actually need to get the original\n\t\t\t// destination, we could just forward each ip to a unique port\n\t\t\t// and either listen on that port or run port-forward\n\t\t\tproxy, err := proxy.NewProxy(fmt.Sprintf(\":%s\", PROXY_REDIR_PORT), iceptor.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Proxy\")\n\t\t\t}\n\n\t\t\tproxy.Start(10000)\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no proxy.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNS_CONFIG,\n\t\tRequires: []string{TRANSLATOR},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tbootstrap := route.Table{Name: \"bootstrap\"}\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tIp: args.dnsIP,\n\t\t\t\tTarget: DNS_REDIR_PORT,\n\t\t\t\tProto: \"udp\",\n\t\t\t})\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tName: \"teleproxy\",\n\t\t\t\tIp: MAGIC_IP,\n\t\t\t\tTarget: apis.Port(),\n\t\t\t\tProto: \"tcp\",\n\t\t\t})\n\t\t\ticeptor.Update(bootstrap)\n\n\t\t\tvar restore func()\n\t\t\tif !args.nosearch {\n\t\t\t\trestore = dns.OverrideSearchDomains(p, \".\")\n\t\t\t}\n\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\n\t\t\tif !args.nosearch {\n\t\t\t\trestore()\n\t\t\t}\n\n\t\t\tdns.Flush()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn nil\n}", "func defaultLoader(serverType string) (caddy.Input, error) {\n\tcontents, err := os.ReadFile(caddy.DefaultConfigFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents: contents,\n\t\tFilepath: caddy.DefaultConfigFile,\n\t\tServerTypeName: serverType,\n\t}, nil\n}", "func (this *GenericController) setLangVer() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\n\t// 1. Check URL arguments.\n\tpreferredLang := this.GetString(\"preferredLang\", \"\")\n\n\t// 2. Get language information from cookies.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = this.Ctx.GetCookie(\"preferredLang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(preferredLang) {\n\t\tpreferredLang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(preferredLang) == 0 {\n\t\tal := this.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tpreferredLang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = \"ta-LK\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := lang.LangType{\n\t\tLang: preferredLang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.Ctx.SetCookie(\"preferredLang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\trestLangs := make([]*lang.LangType, 0, len(lang.LangTypes)-1)\n\tfor _, v := range lang.LangTypes {\n\t\tif preferredLang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\t// Set language properties.\n\tthis.Lang = preferredLang\n\tthis.Data[\"Lang\"] = curLang.Lang\n\tthis.Data[\"CurLang\"] = curLang.Name\n\tthis.Data[\"RestLangs\"] = restLangs\n\treturn isNeedRedir\n}", "func (m *Mosn) inheritHandler() error {\n\tvar err error\n\tm.Upgrade.InheritListeners, m.Upgrade.InheritPacketConn, m.Upgrade.ListenSockConn, err = server.GetInheritListeners()\n\tif err != nil {\n\t\tlog.StartLogger.Errorf(\"[mosn] [NewMosn] getInheritListeners failed, exit\")\n\t\treturn err\n\t}\n\tlog.StartLogger.Infof(\"[mosn] [NewMosn] active reconfiguring\")\n\t// parse MOSNConfig again\n\tc := configmanager.Load(configmanager.GetConfigPath())\n\tif c.InheritOldMosnconfig {\n\t\t// inherit old mosn config\n\t\toldMosnConfig, err := server.GetInheritConfig()\n\t\tif err != nil {\n\t\t\tm.Upgrade.ListenSockConn.Close()\n\t\t\tlog.StartLogger.Errorf(\"[mosn] [NewMosn] GetInheritConfig failed, exit\")\n\t\t\treturn err\n\t\t}\n\t\tlog.StartLogger.Debugf(\"[mosn] [NewMosn] old mosn config: %v\", oldMosnConfig)\n\t\tc.Servers = oldMosnConfig.Servers\n\t\tc.ClusterManager = oldMosnConfig.ClusterManager\n\t\tc.Extends = oldMosnConfig.Extends\n\t}\n\tif c.CloseGraceful {\n\t\tc.DisableUpgrade = true\n\t}\n\tm.Config = c\n\treturn nil\n}", "func defaultFile() string {\n if os.Getenv(\"DEFAULT_FILE\") != \"\" {\n return os.Getenv(\"DEFAULT_FILE\")\n }\n return \"testfile.txt\"\n}", "func defaultLoader(serverType string) (caddy.Input, error) {\n\tcontents, err := ioutil.ReadFile(caddy.DefaultConfigFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents: contents,\n\t\tFilepath: caddy.DefaultConfigFile,\n\t\tServerTypeName: serverType,\n\t}, nil\n}", "func envOverride(config *DefaultConfig) (*DefaultConfig, error) {\n\t// override UpdateTime\n\tupdateTime := os.Getenv(\"XIGNITE_FEEDER_UPDATE_TIME\")\n\tif updateTime != \"\" {\n\t\tt, err := time.Parse(ctLayout, updateTime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.UpdateTime = t\n\t}\n\n\t// override APIToken\n\tapiToken := os.Getenv(\"XIGNITE_FEEDER_API_TOKEN\")\n\tif apiToken != \"\" {\n\t\tconfig.APIToken = apiToken\n\t}\n\n\t// override NotQuoteSymbolList\n\tnotQuoteStockList := os.Getenv(\"XIGNITE_FEEDER_NOT_QUOTE_STOCK_LIST\")\n\tif notQuoteStockList != \"\" {\n\t\tconfig.NotQuoteStockList = strings.Split(notQuoteStockList, \",\")\n\t}\n\n\treturn config, nil\n}", "func intercept(p *supervisor.Process, tele *Teleproxy) error {\n\tif os.Geteuid() != 0 {\n\t\treturn errors.New(\"ERROR: teleproxy must be run as root or suid root\")\n\t}\n\n\tsup := p.Supervisor()\n\n\tif tele.DNSIP == \"\" {\n\t\tdat, err := ioutil.ReadFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"nameserver\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\ttele.DNSIP = fields[1]\n\t\t\t\tlog.Printf(\"TPY: Automatically set -dns=%v\", tele.DNSIP)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif tele.DNSIP == \"\" {\n\t\treturn errors.New(\"couldn't determine dns ip from /etc/resolv.conf\")\n\t}\n\n\tif tele.FallbackIP == \"\" {\n\t\tif tele.DNSIP == \"8.8.8.8\" {\n\t\t\ttele.FallbackIP = \"8.8.4.4\"\n\t\t} else {\n\t\t\ttele.FallbackIP = \"8.8.8.8\"\n\t\t}\n\t\tlog.Printf(\"TPY: Automatically set -fallback=%v\", tele.FallbackIP)\n\t}\n\tif tele.FallbackIP == tele.DNSIP {\n\t\treturn errors.New(\"if your fallbackIP and your dnsIP are the same, you will have a dns loop\")\n\t}\n\n\ticeptor := interceptor.NewInterceptor(\"teleproxy\")\n\tapis, err := api.NewAPIServer(iceptor)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"API Server\")\n\t}\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: TranslatorWorker,\n\t\t// XXX: Requires will need to include the api server once it is changed to not bind early\n\t\tRequires: []string{ProxyWorker, DNSServerWorker},\n\t\tWork: iceptor.Work,\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: APIWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tapis.Start()\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\tapis.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSServerWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tsrv := dns.Server{\n\t\t\t\tListeners: dnsListeners(p, DNSRedirPort),\n\t\t\t\tFallback: tele.FallbackIP + \":53\",\n\t\t\t\tResolve: func(domain string) string {\n\t\t\t\t\troute := iceptor.Resolve(domain)\n\t\t\t\t\tif route != nil {\n\t\t\t\t\t\treturn route.Ip\n\t\t\t\t\t}\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t}\n\t\t\terr := srv.Start(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no srv.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: ProxyWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\t// hmm, we may not actually need to get the original\n\t\t\t// destination, we could just forward each ip to a unique port\n\t\t\t// and either listen on that port or run port-forward\n\t\t\tproxy, err := proxy.NewProxy(fmt.Sprintf(\":%s\", ProxyRedirPort), iceptor.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Proxy\")\n\t\t\t}\n\n\t\t\tproxy.Start(10000)\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no proxy.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSConfigWorker,\n\t\tRequires: []string{TranslatorWorker},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tbootstrap := route.Table{Name: \"bootstrap\"}\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tIp: tele.DNSIP,\n\t\t\t\tTarget: DNSRedirPort,\n\t\t\t\tProto: \"udp\",\n\t\t\t})\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tName: \"teleproxy\",\n\t\t\t\tIp: MagicIP,\n\t\t\t\tTarget: apis.Port(),\n\t\t\t\tProto: \"tcp\",\n\t\t\t})\n\t\t\ticeptor.Update(bootstrap)\n\n\t\t\tvar restore func()\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore = dns.OverrideSearchDomains(p, \".\")\n\t\t\t}\n\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore()\n\t\t\t}\n\n\t\t\tdns.Flush()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn nil\n}", "func overridenSysctl(data string) string {\n\t// Example log line to parse:\n\t// 2023-02-10 12:57:13,201 INFO tuned.plugins.plugin_sysctl: Overriding sysctl parameter 'fs.inotify.max_user_instances' from '4096' to '8192'\n\tvar (\n\t\toverridenSysctl = \"\"\n\t)\n\tconst (\n\t\tkey = \"tuned.plugins.plugin_sysctl: Overriding sysctl parameter '\"\n\t)\n\ti := strings.Index(data, key)\n\tif i == -1 {\n\t\treturn \"\"\n\t}\n\ti += len(key)\n\tslice := strings.Split(data[i:], \"'\")\n\tif slice[2] != slice[4] {\n\t\toverridenSysctl = slice[0]\n\t}\n\n\treturn overridenSysctl\n}", "func (pp *protocPlugin) GenerateFile(gen *protogen.Plugin, file *protogen.File) {\n\tif pp.err != nil {\n\t\treturn\n\t}\n\tgopkg := file.Proto.GetOptions().GetGoPackage()\n\tif pp.completeImportPath {\n\t\tif parts := strings.SplitN(gopkg, generator.KitexGenPath, 2); len(parts) == 2 {\n\t\t\tpp.Namespace = parts[1]\n\t\t}\n\t} else {\n\t\tpp.Namespace = strings.TrimPrefix(gopkg, pp.PackagePrefix)\n\t}\n\n\tss := pp.convertTypes(file)\n\tpp.Services = append(pp.Services, ss...)\n\n\tif pp.Config.Use != \"\" {\n\t\treturn\n\t}\n\n\thasStreaming := false\n\t// generate service package\n\tfor _, si := range ss {\n\t\tpp.ServiceInfo = si\n\t\tfs, err := pp.kg.GenerateService(&pp.PackageInfo)\n\t\tif err != nil {\n\t\t\tpp.err = err\n\t\t\treturn\n\t\t}\n\t\tif !hasStreaming && si.HasStreaming {\n\t\t\thasStreaming = true\n\t\t}\n\t\tfor _, f := range fs {\n\t\t\tgen.NewGeneratedFile(pp.adjustPath(f.Name), \"\").P(f.Content)\n\t\t}\n\t}\n\t// generate service interface\n\tif pp.err == nil {\n\t\tfixed := *file\n\t\tfixed.GeneratedFilenamePrefix = strings.TrimPrefix(fixed.GeneratedFilenamePrefix, pp.PackagePrefix)\n\t\tf := gengo.GenerateFile(gen, &fixed)\n\t\tf.QualifiedGoIdent(protogen.GoIdent{GoImportPath: \"context\"})\n\t\tif hasStreaming {\n\t\t\tf.QualifiedGoIdent(protogen.GoIdent{GoImportPath: \"github.com/cloudwego/kitex/pkg/streaming\"})\n\t\t}\n\t\tf.P(\"var _ context.Context\")\n\n\t\ttpl := template.New(\"interface\")\n\t\ttpl = template.Must(tpl.Parse(interfaceTemplate))\n\t\tvar buf bytes.Buffer\n\t\tpp.err = tpl.ExecuteTemplate(&buf, tpl.Name(), pp.makeInterfaces(f, file))\n\n\t\tf.P(buf.String())\n\t}\n}", "func handleFile(config *Config, fileName string) {\n\tlog.Println(\"Edit\", fileName)\n\tnew_content, err_sed := execCmdWithOutput(config.SedCMD, \"-e\", \"s/\"+config.ReplaceFrom+\"/\"+config.ReplaceTo+\"/g\", fileName)\n\tif err_sed != nil {\n\t\tlog.Panic(err_sed)\n\t\treturn\n\t}\n\n\tfile, err := os.OpenFile(fileName, os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tlog.Fatal(\"File cannot opened\", fileName)\n\t}\n\n\tfile.Truncate(0)\n\tfile.WriteString(new_content)\n\tfile.Close()\n}", "func LocalUpdateFile(ctx context.Context, filePath string, contents string) error {\n\treturn platform.WriteFile(ctx, filePath, []byte(contents))\n}", "func initLocales(opt Options) {\n\tfor i, lang := range opt.Langs {\n\t\tfname := fmt.Sprintf(opt.Format, lang)\n\t\t// Append custom locale file.\n\t\tcustom := []interface{}{}\n\t\tcustomPath := path.Join(opt.CustomDirectory, fname)\n\t\tif com.IsFile(customPath) {\n\t\t\tcustom = append(custom, customPath)\n\t\t}\n\n\t\tvar locale interface{}\n\t\tif data, ok := opt.Files[fname]; ok {\n\t\t\tlocale = data\n\t\t} else {\n\t\t\tlocale = path.Join(opt.Directory, fname)\n\t\t}\n\n\t\terr := i18n.SetMessageWithDesc(lang, opt.Names[i], locale, custom...)\n\t\tif err != nil && err != i18n.ErrLangAlreadyExist {\n\t\t\tpanic(fmt.Errorf(\"fail to set message file(%s): %v\", lang, err))\n\t\t}\n\t}\n}", "func (c *Config) File() string { return c.viper.GetString(configFile) }", "func init(){\n\ttemp, _ := ioutil.ReadFile(\"templates/file2.htemplate\")\n\tfile1 = string(temp)\n}", "func generateResponseFile(templFP string, data *gengokit.Data, prevFile io.Reader) (io.Reader, error) {\n\tvar genCode io.Reader\n\tvar err error\n\n\t// Get the actual path to the file rather than the template file path\n\tactualFP := templatePathToActual(templFP, data.Service.Name)\n\n\tswitch templFP {\n\tcase service.ServicePath:\n\t\th, err := service.NewService(data.Service, prevFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot parse previous handler: %q\", actualFP)\n\t\t}\n\n\t\tif genCode, err = h.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render service template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(h, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServiceWrapperPath:\n\t\tw := service.NewServiceWrapper(prevFile)\n\t\tif genCode, err = w.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render middleware template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(w, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdServerPath:\n\t\tr := service.NewCmdServer(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdClientPath:\n\t\tif data.Config.GenClient {\n\t\t\tr := service.NewCmdClient(prevFile)\n\t\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd client template: %s\", templFP)\n\t\t\t}\n\t\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\t\t} else {\n\t\t\treturn nil, ErrGenIgnored\n\t\t}\n\tcase service.ServerPath:\n\t\tr := service.NewServer(nil) // override server.go\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(nil, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerEndpointsPath:\n\t\tedp := service.NewServerEndpoints(prevFile)\n\t\tif genCode, err = edp.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render endpoints template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(edp, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerInterruptPath:\n\t\tintrpt := service.NewServerInterrupt(prevFile)\n\t\tif genCode, err = intrpt.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render interrupt template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(intrpt, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerWrapperPath:\n\t\tr := service.NewServerWrapper(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.BaronPath:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render baron template: %s\", templFP)\n\t\t}\n\t\tactualFP = strings.TrimPrefix(actualFP, \"baron\")\n\t\tactualFP = filepath.Join(data.Config.PBPath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\tdefault:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render template: %s\", templFP)\n\t\t}\n\t\tactualFP = filepath.Join(data.Config.ServicePath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\t}\n\n\tcodeBytes, err := ioutil.ReadAll(genCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ignore error as we want to write the code either way to inspect after\n\t// writing to disk\n\tformattedCode := formatCode(codeBytes)\n\n\treturn bytes.NewReader(formattedCode), nil\n}", "func loadOverrides(filepath string) ([][]string, error) {\n\tf, err := os.Open(filepath)\n\tif os.IsNotExist(err) {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\toverrides := make([][]string, 0)\n\toverrides = append(overrides, make([]string, 0))\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif line == \"---\" {\n\t\t\toverrides = append(overrides, make([]string, 0))\n\t\t\tcontinue\n\t\t}\n\t\toverrides[len(overrides)-1] = append(overrides[len(overrides)-1], line)\n\t}\n\treturn overrides, nil\n}", "func (s *server) File(_ context.Context, request *pb.FileRequest) (*pb.FileResponse, error) {\n\tfmt.Printf(\"Patching file %s\\n\", path.Join(s.localReplicaPath, request.FullPath))\n\terr := ioutil.WriteFile(path.Join(s.localReplicaPath, request.FullPath), []byte(request.FullContents), defaultRights)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to file %s: %w\", request.FullPath, err)\n\t}\n\treturn &pb.FileResponse{}, nil\n}", "func (c *OrganizationsEnvironmentsApisRevisionsDeployCall) Override(override bool) *OrganizationsEnvironmentsApisRevisionsDeployCall {\n\tc.urlParams_.Set(\"override\", fmt.Sprint(override))\n\treturn c\n}", "func (c *OrganizationsEnvironmentsApisRevisionsDeploymentsGenerateDeployChangeReportCall) Override(override bool) *OrganizationsEnvironmentsApisRevisionsDeploymentsGenerateDeployChangeReportCall {\n\tc.urlParams_.Set(\"override\", fmt.Sprint(override))\n\treturn c\n}", "func overwriteHosts() {\n\tnewHostsPath, err := os.Getwd() // fetch working directory path to find new hosts file\n\n\t// return if Getwd returns an error\n\tif err != nil {\n\t\tprint(\"error returned in Getwd\")\n\t\treturn\n\t}\n\n\tnewHostsPath += \"\\\\hosts\"\n\n\toverwriteFileWith(OLDHOSTSPATH, newHostsPath)\n}", "func (conf blah) File() string {\n\treturn filepath.Join(configPath, defConfigFile)\n}", "func replaceUserdataFile(machineName, machineOS, hostname string, userdataContent, customScriptContent []byte, newUserDataFile *os.File) error {\n\tvar err error\n\tvar encodedData string\n\tcf := make(map[interface{}]interface{})\n\n\tswitch {\n\tcase bytes.HasPrefix(userdataContent, []byte(\"#!\")):\n\t\t// The user provided a script file, so the customInstallScript contents is appended to user script\n\t\t// and added to the \"runcmd\" section so modified user data is always in cloud config format.\n\n\t\t// Remove the shebang\n\t\tuserdataContent = regexp.MustCompile(`^#!.*\\n`).ReplaceAll(userdataContent, nil)\n\n\t\tencodedData, err = gzipEncode(bytes.Join([][]byte{userdataContent, customScriptContent}, []byte(\"\\n\\n\")))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase bytes.HasPrefix(userdataContent, []byte(\"#cloud-config\")):\n\t\t// The user provided a cloud-config file, so the customInstallScript context is added to the\n\t\t// \"runcmd\" section of the YAML.\n\t\tif err := yaml.Unmarshal(userdataContent, &cf); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tencodedData, err = gzipEncode(customScriptContent)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\tdefault:\n\t\treturn fmt.Errorf(\"existing userdata file does not begin with '#!' or '#cloud-config'\")\n\t}\n\n\treturn writeCloudConfig(machineName, encodedData, machineOS, hostname, cf, newUserDataFile)\n}", "func defaultEndpointFile() string {\n\tconst f = \"opencensus.endpoint\"\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(os.Getenv(\"APPDATA\"), \"opencensus\", f)\n\t}\n\treturn filepath.Join(guessUnixHomeDir(), \".config\", f)\n}", "func logEnvironmentOverride(lc logger.LoggingClient, name string, key string, value string) {\n\tlc.Info(fmt.Sprintf(\"Variables override of '%s' by environment variable: %s=%s\", name, key, value))\n}", "func (h *HAProxyManager) filename() string {\n\treturn filepath.Join(h.configDir, h.listenAddr+\".conf\")\n}", "func (this *BaseRouter) setLang() bool {\n\tfmt.Println(\"setLang() function\")\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tlangs := conf.Langs\n\n\t// 1. Check URL arguments.\n\tlang := this.GetString(\"lang\")\n\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = this.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\tif len(lang) == 0 && this.IsLogin {\n\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t}\n\n\t// 4. Get language information from 'Accept-Language'.\n\tif len(lang) == 0 {\n\t\tal := this.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. DefaucurLang language is English.\n\tif len(lang) == 0 {\n\t\tlang = \"en-US\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tthis.Data[\"Lang\"] = lang\n\tthis.Data[\"Langs\"] = langs\n\n\tthis.Lang = lang\n\n\treturn isNeedRedir\n}", "func overrideOyaCmd(projectDir string) {\n\texecutablePath := filepath.Join(projectDir, \"_bin/oya\")\n\toyaCmdOverride := fmt.Sprintf(\n\t\t\"(cd %v && go build -o %v oya.go); %v\",\n\t\tsourceFileDirectory(), executablePath, executablePath)\n\toyafile.OyaCmdOverride = &oyaCmdOverride\n}", "func (*bzlLibraryLang) Fix(c *config.Config, f *rule.File) {}", "func (h *Handler) UpdateFromFile(filename string) (*corev1.Service, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn h.UpdateFromBytes(data)\n}", "func (c *jsiiProxy_CfnFileSystem) OverrideLogicalId(newLogicalId *string) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"overrideLogicalId\",\n\t\t[]interface{}{newLogicalId},\n\t)\n}", "func handleTLFSpecialFile(name string, folder *Folder) dokan.File {\n\t// Common files (the equivalent of handleCommonSpecialFile\n\t// from libfuse) are handled in fs.go.\n\tswitch name {\n\tcase libfs.EditHistoryName:\n\t\treturn NewTlfEditHistoryFile(folder)\n\n\tcase libfs.UnstageFileName:\n\t\treturn &UnstageFile{\n\t\t\tfolder: folder,\n\t\t}\n\n\tcase libfs.DisableUpdatesFileName:\n\t\treturn &UpdatesFile{\n\t\t\tfolder: folder,\n\t\t}\n\n\tcase libfs.EnableUpdatesFileName:\n\t\treturn &UpdatesFile{\n\t\t\tfolder: folder,\n\t\t\tenable: true,\n\t\t}\n\n\tcase libfs.RekeyFileName:\n\t\treturn &RekeyFile{\n\t\t\tfolder: folder,\n\t\t}\n\n\tcase libfs.ReclaimQuotaFileName:\n\t\treturn &ReclaimQuotaFile{\n\t\t\tfolder: folder,\n\t\t}\n\n\tcase libfs.SyncFromServerFileName:\n\t\treturn &SyncFromServerFile{\n\t\t\tfolder: folder,\n\t\t}\n\n\tcase libfs.EnableJournalFileName:\n\t\treturn &JournalControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.JournalEnable,\n\t\t}\n\n\tcase libfs.FlushJournalFileName:\n\t\treturn &JournalControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.JournalFlush,\n\t\t}\n\n\tcase libfs.PauseJournalBackgroundWorkFileName:\n\t\treturn &JournalControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.JournalPauseBackgroundWork,\n\t\t}\n\n\tcase libfs.ResumeJournalBackgroundWorkFileName:\n\t\treturn &JournalControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.JournalResumeBackgroundWork,\n\t\t}\n\n\tcase libfs.DisableJournalFileName:\n\t\treturn &JournalControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.JournalDisable,\n\t\t}\n\n\tcase libfs.EnableSyncFileName:\n\t\treturn &SyncControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.SyncEnable,\n\t\t}\n\n\tcase libfs.DisableSyncFileName:\n\t\treturn &SyncControlFile{\n\t\t\tfolder: folder,\n\t\t\taction: libfs.SyncDisable,\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetConfigFilePath(override string) string {\n\tif len(override) > 0 {\n\t\treturn override\n\t}\n\tglobalPath := \"/etc/fusion/fusion.yml\"\n\tif _, err := os.Open(globalPath); err == nil {\n\t\treturn globalPath\n\t}\n\n\treturn \"\"\n}", "func replaceFile(filePath, lines string) {\n\tbytesToWrite := []byte(lines) //data written\n\terr := ioutil.WriteFile(filePath, bytesToWrite, 0644) //filename, byte array (binary representation), and 0644 which represents permission number. (0-777) //will create a new text file if that text file does not exist yet\n\tif isError(err) {\n\t\tfmt.Println(\"Error Writing to file:\", filePath, \"=\", err)\n\t\treturn\n\t}\n}", "func updateFromFile(cLink, fileName, user, passw string, params url.Values, headers map[string]string, client *http.Client) (solrResp *glsolr.Response, err error) {\r\n\tfile, err := os.Open(fileName)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tdefer file.Close()\r\n\r\n\tsolrResp, err = glsolr.Update(cLink, user, passw, file, params, headers, client)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn solrResp, nil\r\n}", "func UpFile(m *tb.Message) (string, error) {\n\tfilePath, e := makeTelegramFilePath(m.Document.FileID)\n\tif e != nil {\n\t\tlog.Fatalf(\"Error happened\")\n\t}\n\tfmt.Println(\"Url:\", filePath.GetFileURL())\n\tpathName := filepath.Join(\"src\", \"statics\", filepath.Base(m.Document.FileName))\n\tif e := DownloadFile(filePath.GetFileURL(), pathName); e != nil {\n\t\tfmt.Println(\"Error reading file:\", e)\n\t\tos.Exit(1)\n\t}\n\n\treturn pathName, e\n}", "func (a *Api) refreshLocal(res http.ResponseWriter, req *http.Request, vars map[string]string) {\n\tlog.Println(\"refresh locales files from remote system!\")\n\tsuccess := a.localeManager.DownloadLocales(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif !success {\n\t\tlog.Printf(\"error while retriving locales from localizer service!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlocalizer, err := localize.NewI18nLocalizer(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading locales files!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\temailTemplates, err := templates.New(a.Config.I18nTemplatesPath, localizer)\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading templates!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\ta.templates = emailTemplates\n}", "func generateServiceImplFile(pdArr []ProtoData, option string) error {\n\tdirPath := filepath.Join(appPath)\n\t_, fileErr := os.Stat(dirPath)\n\tif fileErr != nil {\n\t\tos.MkdirAll(dirPath, os.ModePerm)\n\t}\n\tfor _, pd := range pdArr {\n\t\tconnectorFile := filepath.Join(appPath, strings.Split(protoFileName, \".\")[0]+\".\"+pd.RegServiceName+\".\"+option+\".grpcservice.go\")\n\t\tf, err := os.Create(connectorFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error: \", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tpd.Option = option\n\t\tif strings.Compare(option, \"server\") == 0 {\n\t\t\terr = registryServerTemplate.Execute(f, pd)\n\t\t} else {\n\t\t\terr = registryClientTemplate.Execute(f, pd)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func setLang(lang string) {\n\tif lang == \"pl\" {\n\t\tl = langTexts[\"pl\"]\n\t} else if lang == \"en\" {\n\t\tl = langTexts[\"en\"]\n\t}\n}", "func (_m *FakeScheduleService) overrideCfg(cfg SchedulerCfg) {\n\t_m.Called(cfg)\n}", "func (v *Venom) SetOverride(key string, value interface{}) {\n\tv.Store.SetLevel(OverrideLevel, key, value)\n}", "func detectLanguage(f *os.File) (string, error) {\n\tswitch filepath.Ext(f.Name()) {\n\tcase \".go\":\n\t\treturn golang, nil\n\tcase \".py\":\n\t\treturn python, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unknown language for file %v\", f.Name())\n\t}\n}", "func Load(isServer bool) error {\n\tdirPath, err := getFullConfPath()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to determine full config dir path: %v\", err)\n\t}\n\tconfPath, err := getFullConfPath(configFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to determine full config file path: %v\", err)\n\t}\n\n\t// Create the config dir if it doesn't exist. Make with user-only\n\t// permissions, cuz fifo exists there, which can be used to control\n\t// server. Also saved service details could be sensitive.\n\tif os.Mkdir(dirPath, 0700); err != nil {\n\t\treturn fmt.Errorf(\"Failed to create config dir (%s): %v\", dirPath, err)\n\t}\n\n\t// Try opening the conf file, on most runs it'll already exist\n\tvar confData []byte\n\tif f, err := os.Open(confPath); err != nil && os.IsNotExist(err) {\n\t\t// Make a default one\n\t\tif err := ioutil.WriteFile(confPath, []byte(defaultConfig), 0660); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create a default config file (%s): %v\", confPath, err)\n\t\t}\n\t\tconfData = []byte(defaultConfig)\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"Failed to open config file (%s): %v\", confPath, err)\n\t} else {\n\t\tdefer f.Close()\n\n\t\tconfData, err = ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to read conf file (%s): %v\", confPath, err)\n\t\t}\n\t}\n\n\tconf := ConfFormat{}\n\tif err := yaml.Unmarshal(confData, &conf); err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse conf file (%s): %v\", confPath, err)\n\t}\n\n\tif *verbosity > 0 {\n\t\tLogLevel = log.LvlWarn + log.Lvl(*verbosity)\n\t} else if level, err := log.LvlFromString(conf.LogLevel); err == nil && isServer {\n\t\tLogLevel = level\n\t} else if isServer {\n\t\tLogLevel = log.LvlInfo\n\t} else {\n\t\tLogLevel = log.LvlWarn\n\t}\n\n\tif *logPath != \"\" {\n\t\tLogPath = *logPath\n\t} else if conf.LogPath != \"\" {\n\t\tLogPath = conf.LogPath\n\t} else {\n\t\tif LogPath, err = getFullConfPath(\"log\"); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to build log file path: %v\", err)\n\t\t}\n\t}\n\n\tif *fifoPath != \"\" {\n\t\tFifoPath = *fifoPath\n\t} else if conf.FifoPath != \"\" {\n\t\tFifoPath = conf.FifoPath\n\t} else {\n\t\tif FifoPath, err = getFullConfPath(FifoPath); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to build fifo file path: %v\", err)\n\t\t}\n\t}\n\n\tif conf.CleanTempServicesAfter != \"\" {\n\t\tdur, err := time.ParseDuration(conf.CleanTempServicesAfter)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid duration for cleaning temp services\")\n\t\t}\n\t\tCleanTempServicesAfter = dur\n\t}\n\n\t// After conf file stuff is all handled, do config related to other stuff\n\n\t// Set the path to services conf file only if it exists\n\tpath, err := getFullConfPath(serviceConfigFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get path to services config file: %v\", err)\n\t}\n\t_, err = os.Stat(path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Failed to open services config file: %v\", err)\n\t} else if err == nil {\n\t\tServiceConfigFile = path\n\t}\n\n\tlog.Debug(\n\t\t\"Config file loaded\",\n\t\t\"LogPath\", LogPath,\n\t\t\"FifoPath\", FifoPath,\n\t\t\"CleanTempServicesAfter\", CleanTempServicesAfter)\n\treturn nil\n}", "func (c *OrganizationsEnvironmentsSharedflowsRevisionsDeployCall) Override(override bool) *OrganizationsEnvironmentsSharedflowsRevisionsDeployCall {\n\tc.urlParams_.Set(\"override\", fmt.Sprint(override))\n\treturn c\n}", "func parseFile(c *Configuration) {\n\tc.viperEnvAndFile.SetConfigType(fileType)\n\tconfigFromEnv := c.viperEnvAndFile.GetString(configurationMap[configFile].Env)\n\tif configFromEnv != \"\" {\n\t\tc.viperEnvAndFile.SetConfigFile(configFromEnv)\n\t\terr := c.viperEnvAndFile.ReadInConfig()\n\t\tif err == nil {\n\t\t\tlogger.L.Debug(\"config file loaded from from env\")\n\t\t\treturn\n\t\t}\n\t}\n\tconfigFromFlag := c.viperFlag.GetString(configurationMap[configFile].Flag)\n\tif configFromFlag != \"\" {\n\t\tc.viperEnvAndFile.SetConfigFile(configFromFlag)\n\t\terr := c.viperEnvAndFile.ReadInConfig()\n\t\tif err == nil {\n\t\t\tlogger.L.Debug(\"config file loaded from from flag\")\n\t\t\treturn\n\t\t}\n\t}\n\tc.viperEnvAndFile.SetConfigFile(configurationMap[configFile].Default)\n\terr := c.viperEnvAndFile.ReadInConfig()\n\tif err == nil {\n\t\tlogger.L.Debug(\"config file loaded from defaults\")\n\t\treturn\n\t}\n\tc.viperEnvAndFile.SetConfigFile(\"./\" + fileName + \".\" + fileExtension)\n\terr = c.viperEnvAndFile.ReadInConfig()\n\tif err != nil {\n\t\tlogger.L.Info(\"config file was not found in pwd\")\n\t\treturn\n\t}\n}", "func (e *engine) setDefaults(ctx *Context) {\n\tif ctx.Req.Locale == nil {\n\t\tctx.Req.Locale = ahttp.NewLocale(AppConfig().StringDefault(\"i18n.default\", \"en\"))\n\t}\n}", "func (s *Server) setView(v string) *Server {\n\tif v == \"\" {\n\t\tpanic(`server: view file must provided`)\n\t}\n\n\tb, err := ioutil.ReadFile(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tm := minify.New()\n\tm.AddFunc(\"text/css\", css.Minify)\n\tm.AddFunc(\"text/html\", html.Minify)\n\tm.AddFunc(\"text/javascript\", js.Minify)\n\n\tn, err := m.Bytes(\"text/html\", b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = s.tmp.Parse(string(n))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn s\n}", "func (lc *LanguageConfig) UseDefaultIfNotProvided() {\n\tif \"\" == lc.SrcDir {\n\t\tlc.SrcDir = fmt.Sprintf(defaultSrcDir, lc.Language)\n\t}\n\tif \"\" == lc.WorkDir {\n\t\tlc.WorkDir = fmt.Sprintf(defaultWorkDir, lc.Language)\n\t}\n\tif \"\" == lc.AppName {\n\t\tlc.AppName = fmt.Sprintf(defaultAppName, lc.Language)\n\t}\n\tif \"\" == lc.YamlImagePlaceholder {\n\t\tlc.YamlImagePlaceholder = fmt.Sprintf(defaultYamlImagePlaceHolder, lc.Language)\n\t}\n}", "func (s *BaseSyslParserListener) ExitSysl_file(ctx *Sysl_fileContext) {}", "func fallbackService(lang string) string {\n\tif lang == \"\" {\n\t\treturn DefaultServiceName\n\t}\n\tif v, ok := fallbackServiceNames.Load(lang); ok {\n\t\treturn v.(string)\n\t}\n\tvar str strings.Builder\n\tstr.WriteString(\"unnamed-\")\n\tstr.WriteString(lang)\n\tstr.WriteString(\"-service\")\n\tfallbackServiceNames.Store(lang, str.String())\n\treturn str.String()\n}", "func GetLevel1File(c *gin.Context) {\n p, _ := c.Get(\"serviceProvider\")\n var serviceProvider *services.ServiceProvider\n serviceProvider = p.(*services.ServiceProvider)\n\tfileName := c.Param(\"level1\")\n\thtmlFolder := serviceProvider.GetConfig().StaticFolder\n\tpath := fmt.Sprintf(\"%s/%s\", htmlFolder, fileName)\n\tc.File(path)\n}", "func (m *Mosn) inheritConfig(c *v2.MOSNConfig) (err error) {\n\tm.Config = c\n\tserver.EnableInheritOldMosnconfig(c.InheritOldMosnconfig)\n\n\t// default is graceful mode, turn graceful off by set it to false\n\tif !c.DisableUpgrade && server.IsReconfigure() {\n\t\tm.isFromUpgrade = true\n\t\tif err = m.inheritHandler(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tlog.StartLogger.Infof(\"[mosn] [NewMosn] new mosn created\")\n\t// start init services\n\tif err = store.StartService(m.Upgrade.InheritListeners); err != nil {\n\t\tlog.StartLogger.Errorf(\"[mosn] [NewMosn] start service failed: %v, exit\", err)\n\t}\n\treturn\n}", "func (d DependencyCacheLayer) OverrideEnv(name string, format string, args ...interface{}) error {\n\td.Logger.SubsequentLine(\"Writing %s\", name)\n\treturn d.CacheLayer.OverrideEnv(name, format, args...)\n}", "func overrideEnvWithStaticProxy(conf ProxyConf, setenv envSetter) {\n\tif conf.Static.Active {\n\t\tfor _, scheme := range []string{\"http\", \"https\"} {\n\t\t\turl := mapFallback(scheme, \"\", conf.Static.Protocols)\n\t\t\tsetenv(scheme+\"_proxy\", url)\n\t\t}\n\t\tif conf.Static.NoProxy != \"\" {\n\t\t\tsetenv(\"no_proxy\", conf.Static.NoProxy)\n\t\t}\n\t}\n}", "func (h *MemHome) Lang(path string) Lang { return h.langs.lang(path) }", "func updateLocalizableStrings(project Project, str string) Project {\n\tfor _, lang := range project.Languages { //do it to all project's Localizable.strings file\n\t\tvar path = lang.Path + \"/Localizable.strings\"\n\t\tvar fileContents = readFile(path)\n\t\tif !strings.Contains(fileContents, str) { //if str does not exist in Localizable.strings...\n\t\t\tvar stringToWrite = str + \" = \\\"\\\";\" //equivalent to: \"word\" = \"\";\n\t\t\twriteToFile(path, \"\\n\"+stringToWrite) //write at the end\n\t\t}\n\t}\n\treturn project\n}", "func (config *Config) OverrideByCLIConfig(cliConfig *CLIConfig) {\n\tif cliConfig.LoggerColor != nil {\n\t\tconfig.Logger.Color = *cliConfig.LoggerColor\n\t}\n\tif cliConfig.DatabaseSSL != nil {\n\t\tconfig.Database.SSL = *cliConfig.DatabaseSSL\n\t}\n\tif cliConfig.DatabaseHost != \"\" {\n\t\tconfig.Database.Host = cliConfig.DatabaseHost\n\t}\n\tif cliConfig.DatabasePort != nil {\n\t\tconfig.Database.Port = *cliConfig.DatabasePort\n\t}\n\tif cliConfig.DatabaseUsername != \"\" {\n\t\tconfig.Database.Username = cliConfig.DatabaseUsername\n\t}\n\tif cliConfig.DatabaseName != \"\" {\n\t\tconfig.Database.Name = cliConfig.DatabaseName\n\t}\n\tif cliConfig.DatabaseSchema != \"\" {\n\t\tconfig.Database.Schema = cliConfig.DatabaseSchema\n\t}\n\tconfig.Database.Password = os.Getenv(\"DB_PASSWORD\")\n\n\tif cliConfig.TendermintHTTPRPCURL != \"\" {\n\t\tconfig.Tendermint.URL = cliConfig.TendermintHTTPRPCURL\n\t}\n}", "func (a *Adapter) toFile(message string) {\n\n\tif !a.cfg.File {\n\t\treturn\n\t}\n\n\t_, err := a.lf.WriteString(message + \"\\n\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (a *App) updateViews() {\n\t// if a.state.Settings[\"TLDSubstitutions\"] {\n\t// \ta.writeView(viewSettings, \"[X] TLD substitutions\")\n\t// } else {\n\t// \ta.writeView(viewSettings, \"[ ] TLD substitutions\")\n\t// }\n}", "func (md *MassDns) SetResolversFile(rpath string) error {\n\t// check is file exist\n\tif _, err := os.Stat(rpath); os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// set resolvers filepath\n\t// file won't be deleted after work\n\tmd.userResolversPath = rpath\n\treturn nil\n}", "func (c *IndexController) setLang() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tbeego.Debug(len(Langs))\n\tif len(Langs) == 0 {\n\t\tsettingLocales()\n\t}\n\n\t///*\n\tbeego.Debug(hasCookie)\n\tbeego.Debug(isNeedRedir)\n\t//*/ // 1. Check URL arguments.\n\tlang := c.GetString(\"lang\")\n\t//beego.Debug(lang)\n\t//*\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = c.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\t/*\n\t\tif len(lang) == 0 && this.IsLogin {\n\t\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t\t}\n\t\t//*/\n\t// 4. Get language information from 'Accept-Language'.\n\t//beego.Debug(\"浏览器是什么语言\", c.Ctx.Input.Header(\"Accept-Language\"))\n\t//*\n\tif len(lang) == 0 {\n\t\tal := c.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\t//*/\n\t// 4. DefaucurLang language is English.\n\t//*\n\tif len(lang) == 0 {\n\t\tlang = \"zh-TW\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\t//*\n\tif !hasCookie {\n\t\tc.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tc.Data[\"Lang\"] = lang\n\tc.Data[\"Langs\"] = Langs\n\n\tc.Lang = lang\n\t//\tbeego.Debug(\"坑货的值 :\", isNeedRedir)\n\treturn isNeedRedir\n\t//*/\n}", "func DoFile(L *lua.LState) int {\n\tfilename := L.CheckString(1)\n\tp := NewLuaPlugin(L, 2)\n\tp.filename = &filename\n\tud := L.NewUserData()\n\tud.Value = p\n\tL.SetMetatable(ud, L.GetTypeMetatable(`plugin_ud`))\n\tL.Push(ud)\n\treturn 1\n}", "func (fc *FilterConfig) reloadFile() {\n\tnewDb, err := ip2location.OpenDB(fc.DBPath)\n\tif err != nil {\n\t\tgoglog.Logger.Errorf(\"ip2location failed to update %s: %s\", fc.DBPath, err.Error())\n\t\treturn\n\t}\n\toldDb := fc.db\n\tfc.dbMtx.Lock()\n\tfc.db = newDb\n\tfc.dbMtx.Unlock()\n\toldDb.Close()\n\tfc.cache.Purge()\n\tgoglog.Logger.Infof(\"ip2location reloaded file %s\", fc.DBPath)\n}", "func addDefaultYamlFile(dYamlPath string, configs *[]*RawConfig) {\n\tenvs, targets, err := BuiltinDefault()\n\tdConfig := &RawConfig{\n\t\tFilepath: \"builtin:target/default.yaml\",\n\t\tEnvs: envs,\n\t\tTargets: targets,\n\t}\n\tif dYamlPath != \"\" {\n\t\tdConfig, err = LoadConfigFile(dYamlPath)\n\t\tif err != nil {\n\t\t\tfmt.Println(color.Red(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tdConfig.Filepath = dYamlPath\n\t}\n\tdConfig.Envs = strings.TrimSpace(dConfig.Envs)\n\tdConfig.Remotes = strings.TrimSpace(dConfig.Remotes)\n\tdConfig.Targets = strings.TrimSpace(dConfig.Targets)\n\t*configs = append(*configs, dConfig)\n}", "func (s *Syncthing) generateIgnoredFileConfig() (string, error) {\n\tvar ignoreFilePath = filepath.Join(s.LocalHome, IgnoredFIle)\n\tvar syncedPatternAdaption = make([]string, len(s.SyncedPattern))\n\tvar enableParseFromGitIgnore = DisableParseFromGitIgnore\n\n\tfor i, synced := range s.SyncedPattern {\n\t\tvar afterAdapt = synced\n\n\t\t// previews version support such this syntax\n\t\tif synced == \".\" {\n\t\t\tafterAdapt = \"**\"\n\t\t}\n\n\t\tif strings.Index(synced, \"./\") == 0 {\n\t\t\tafterAdapt = synced[1:]\n\t\t}\n\n\t\tsyncedPatternAdaption[i] = \"!\" + afterAdapt\n\t}\n\n\tvar ignoredPatternAdaption = make([]string, len(s.IgnoredPattern))\n\tfor i, ignored := range s.IgnoredPattern {\n\t\tvar afterAdapt = ignored\n\n\t\t// previews version support such this syntax\n\t\tif ignored == \".\" {\n\t\t\tafterAdapt = \"**\"\n\t\t}\n\n\t\tif strings.Index(ignored, \"./\") == 0 {\n\t\t\tafterAdapt = ignored[1:]\n\t\t}\n\n\t\tignoredPatternAdaption[i] = afterAdapt\n\t}\n\n\tif len(syncedPatternAdaption) == 0 {\n\t\tsyncedPatternAdaption = []string{\"!**\"}\n\t}\n\n\tignoredPattern := \"\"\n\tsyncedPattern := \"\"\n\n\tif s.EnableParseFromGitIgnore {\n\t\tlog.Infof(\"\\n Enable parsing file's ignore/sync from git ignore\\n\")\n\t\tenableParseFromGitIgnore = EnableParseFromGitIgnore\n\t} else {\n\t\tignoredPattern = strings.Join(ignoredPatternAdaption, \"\\n\")\n\t\tsyncedPattern = strings.Join(syncedPatternAdaption, \"\\n\")\n\n\t\tlog.Infof(\"IgnoredPattern: \\n\" + ignoredPattern)\n\t\tlog.Infof(\"SyncedPattern: \\n\" + syncedPattern)\n\t}\n\n\tvar values = map[string]string{\n\t\t\"enableParseFromGitIgnore\": enableParseFromGitIgnore,\n\t\t\"ignoredPattern\": ignoredPattern,\n\t\t\"syncedPattern\": syncedPattern,\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tif err := ignoredFileTemplate.Execute(buf, values); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to write .nhignore configuration template: %w\", err)\n\t}\n\n\tif err := ioutil.WriteFile(ignoreFilePath, buf.Bytes(), _const.DefaultNewFilePermission); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to generate .nhignore configuration: %w\", err)\n\t}\n\n\treturn ignoreFilePath, nil\n}", "func ReplaceLines(data map[string]string)(err error){\n sourceDownload := map[string]map[string]string{}\n sourceDownload[\"ruleset\"] = map[string]string{}\n sourceDownload[\"ruleset\"][\"sourceDownload\"] = \"\"\n sourceDownload,err = GetConf(sourceDownload)\n pathDownloaded := sourceDownload[\"ruleset\"][\"sourceDownload\"]\n if err != nil {\n logs.Error(\"ReplaceLines error loading data from main.conf: \"+ err.Error())\n return err\n }\n \n //split path \n splitPath := strings.Split(data[\"path\"], \"/\")\n pathSelected := splitPath[len(splitPath)-2]\n\n saved := false\n rulesFile, err := os.Create(\"_creating-new-file.txt\")\n defer rulesFile.Close()\n var validID = regexp.MustCompile(`sid:(\\d+);`)\n\n newFileDownloaded, err := os.Open(pathDownloaded + pathSelected + \"/rules/\" + \"drop.rules\")\n\n scanner := bufio.NewScanner(newFileDownloaded)\n for scanner.Scan() {\n for x := range data{\n sid := validID.FindStringSubmatch(scanner.Text())\n if (sid != nil) && (sid[1] == string(x)) {\n if data[x] == \"N/A\"{\n saved = true\n continue\n }else{\n _, err = rulesFile.WriteString(string(data[x])) \n _, err = rulesFile.WriteString(\"\\n\") \n saved = true\n continue\n }\n }\n }\n if !saved{\n _, err = rulesFile.WriteString(scanner.Text())\n _, err = rulesFile.WriteString(\"\\n\") \n }\n saved = false\n }\n\n input, err := ioutil.ReadFile(\"_creating-new-file.txt\")\n err = ioutil.WriteFile(\"rules/drop.rules\", input, 0644)\n\n _ = os.Remove(\"_creating-new-file.txt\")\n\n if err != nil {\n logs.Error(\"ReplaceLines error writting new lines: \"+ err.Error())\n return err\n }\n return nil\n}", "func (c *jsiiProxy_CfnModuleDefaultVersion) OverrideLogicalId(newLogicalId *string) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"overrideLogicalId\",\n\t\t[]interface{}{newLogicalId},\n\t)\n}", "func (h *HTTPTransport) replaceTLSServername(repl *caddy.Replacer) *HTTPTransport {\n\t// check whether we have TLS and need to replace the servername in the TLSClientConfig\n\tif h.TLSEnabled() && strings.Contains(h.TLS.ServerName, \"{\") {\n\t\t// make a new h, \"copy\" the parts we don't need to touch, add a new *tls.Config and replace servername\n\t\tnewtransport := &HTTPTransport{\n\t\t\tResolver: h.Resolver,\n\t\t\tTLS: h.TLS,\n\t\t\tKeepAlive: h.KeepAlive,\n\t\t\tCompression: h.Compression,\n\t\t\tMaxConnsPerHost: h.MaxConnsPerHost,\n\t\t\tDialTimeout: h.DialTimeout,\n\t\t\tFallbackDelay: h.FallbackDelay,\n\t\t\tResponseHeaderTimeout: h.ResponseHeaderTimeout,\n\t\t\tExpectContinueTimeout: h.ExpectContinueTimeout,\n\t\t\tMaxResponseHeaderSize: h.MaxResponseHeaderSize,\n\t\t\tWriteBufferSize: h.WriteBufferSize,\n\t\t\tReadBufferSize: h.ReadBufferSize,\n\t\t\tVersions: h.Versions,\n\t\t\tTransport: h.Transport.Clone(),\n\t\t\th2cTransport: h.h2cTransport,\n\t\t}\n\t\tnewtransport.Transport.TLSClientConfig.ServerName = repl.ReplaceAll(newtransport.Transport.TLSClientConfig.ServerName, \"\")\n\t\treturn newtransport\n\t}\n\n\treturn h\n}", "func (c *jsiiProxy_CfnFileSystem) AddPropertyOverride(propertyPath *string, value interface{}) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"addPropertyOverride\",\n\t\t[]interface{}{propertyPath, value},\n\t)\n}", "func (c *jsiiProxy_CfnDeploymentStrategy) OverrideLogicalId(newLogicalId *string) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"overrideLogicalId\",\n\t\t[]interface{}{newLogicalId},\n\t)\n}", "func NewCustomLoopbackFile(f *os.File) nodefs.File {\n\treturn &CustomLoopbackFile{File: f}\n}", "func envOverride(config *Config) error {\n\tconst defaultPort = \":3000\"\n\terr := envconfig.Process(\"athens\", config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tportEnv := os.Getenv(\"PORT\")\n\t// ATHENS_PORT takes precedence over PORT\n\tif portEnv != \"\" && os.Getenv(\"ATHENS_PORT\") == \"\" {\n\t\tconfig.Port = portEnv\n\t}\n\tif config.Port == \"\" {\n\t\tconfig.Port = defaultPort\n\t}\n\tconfig.Port = ensurePortFormat(config.Port)\n\treturn nil\n}", "func TestExcludeOverride(t *testing.T) {\n\tbaseTest(t, []string{\"LICENSE.*\\n\", \"!LICENSE.md\\n\", \"*.md\"}, []string{\"LICENSE.foo\", \"LICENSE.md\"}, []string{\"foo.bar\"})\n}", "func OverrideEnvWithStaticProxy() {\n\toverrideEnvWithStaticProxy(GetConf(), os.Setenv)\n}", "func (m *Windows10XVpnConfiguration) SetCustomXmlFileName(value *string)() {\n err := m.GetBackingStore().Set(\"customXmlFileName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *Server) Service() string { return \"file\" }" ]
[ "0.6689114", "0.5757277", "0.54427046", "0.54074204", "0.5232694", "0.5191908", "0.50697404", "0.50676125", "0.5054689", "0.49671054", "0.49453542", "0.4933882", "0.49225172", "0.49017486", "0.48665082", "0.4861324", "0.48573327", "0.48359537", "0.47937393", "0.47914287", "0.47601128", "0.47206944", "0.4718242", "0.4709651", "0.46874857", "0.4685768", "0.4681179", "0.46804163", "0.46538213", "0.46532676", "0.4629215", "0.46174324", "0.46144438", "0.46107808", "0.46059978", "0.46018872", "0.45883518", "0.45881078", "0.45807958", "0.45793223", "0.45729157", "0.45598453", "0.45583263", "0.45446834", "0.45435637", "0.4543472", "0.4534513", "0.45171836", "0.45100537", "0.45079714", "0.4504935", "0.4503264", "0.4500982", "0.44968966", "0.4493194", "0.447873", "0.44755107", "0.44706583", "0.44705704", "0.44701403", "0.4466616", "0.44623893", "0.4449469", "0.4446237", "0.44446835", "0.44431567", "0.44335982", "0.44326544", "0.4431666", "0.44297472", "0.44232398", "0.44191355", "0.44189695", "0.44171512", "0.44149145", "0.44092777", "0.44043234", "0.44034863", "0.44003886", "0.43980867", "0.4397433", "0.43968737", "0.43938524", "0.4393549", "0.43908697", "0.43881956", "0.43834835", "0.4372819", "0.4367763", "0.43608645", "0.43580177", "0.43542594", "0.43514645", "0.4341199", "0.43379655", "0.4337888", "0.43376723", "0.43370664", "0.43368575", "0.4326825" ]
0.609435
1
update the clients language file
func updateFile(connection net.Conn) { fmt.Println("Updating file...") lang := make([]byte, 10) var content string //content for the new file connection.Read(lang) //read what lang file to change tmp := make([]byte, 255) //tmp for holdning the content from the srv for { read,_ := connection.Read(tmp) //reads what the srv wants to update the file with if tmp[read-1] == 4 { //the update from the srv will end will 4 ascii = end of transmission break } content += string(tmp) //store the content of the file } //search for the input lang and if we can change it. exist := false for _,currentlang := range languages { if currentlang == strings.TrimSpace(string(lang)) { exist = true } } //the lang did exists! so we append the lang to the global languages list. if exist == false { languages = append(languages, strings.TrimSpace(string(lang))) } //We will override already existing languages and create a new file if its a totally new language filename := strings.TrimSpace(string(lang)) + ".txt" newcontent := string(content) //the content from the srv overrideFile(filename, newcontent) //overridefile will take all the content and replace all content with the new content // check if the clients current lang is the new lang if custlang == strings.TrimSpace(string(lang)) { tmplines := make([]string,0) //we must replace all old lines from the lang file file, err := os.Open(filename) //open the file check(err) scanner := bufio.NewScanner(file) for scanner.Scan() { tmplines = append(tmplines, scanner.Text()) } file.Close() *(&lines) = tmplines //replace all old lines with the new content check(scanner.Err()) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func updateLocalizableStrings(project Project, str string) Project {\n\tfor _, lang := range project.Languages { //do it to all project's Localizable.strings file\n\t\tvar path = lang.Path + \"/Localizable.strings\"\n\t\tvar fileContents = readFile(path)\n\t\tif !strings.Contains(fileContents, str) { //if str does not exist in Localizable.strings...\n\t\t\tvar stringToWrite = str + \" = \\\"\\\";\" //equivalent to: \"word\" = \"\";\n\t\t\twriteToFile(path, \"\\n\"+stringToWrite) //write at the end\n\t\t}\n\t}\n\treturn project\n}", "func openLangJSON(updated interface{}) CustError {\n\tfile, err := ioutil.ReadFile(\"languages.json\")\n\n\t// Failed reading the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to load local file: languages.json\"}\n\t}\n\n\terr = json.Unmarshal(file, &updated)\n\n\t// Failed unmarshaling the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to unmarshal local file: languages.json\"}\n\t}\n\n\t// Nothing bad happened\n\treturn CustError{0, errorStr[0]}\n}", "func validateLang() {\n\t\n\t//print all lang options\n\tfmt.Println(intro)\n\tfor _, lang := range languages {\n\t\tfmt.Println(lang)\n\t}\n\n\t//local lines that will hold all lines in the choosen lang file\n\tlines = make([]string,0)\n\t//l will be our predefined languages\n\tl := languages\n\n\t//infinit loop for reading user input language, loop ends if correct lang was choosen \n\tfor {\n\t\tpicked := strings.TrimSpace(userInput()) //read the input from Stdin, trim spaces \n\n\t\t//looping through our predefined languages\n\t\tfor _,lang := range(l) {\n\t\t\tfmt.Println(lang)\n\t\t\tif (picked == lang) {\n\t\t\t\t//fmt.Println(\"Found language!\", lang, picked)\n\t\t\t\tcustlang = lang //variable to hold current lang for client\n\t\t\t\tlang = lang + \".txt\" //append .txt because we are reading from files\n\t\t\t\n\t\t\t\tfile, err := os.Open(lang) //open the given languge file\n\t\t\t\tcheck(err) //check if correct\n\n\t\t\t\tscanner := bufio.NewScanner(file) //scanning through the file\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tlines = append(lines, scanner.Text()) //appending each line in the given langue file to lines\n\t\t\t\t }\n\t\t\t\tfile.Close() //close the file\n\t\t\t\tcheck(scanner.Err()) //check for errors so nothing is left in the file to read\n\t\t\t\tbreak\n\t\t\t} \n\t\t}\n\t\t//check so we actually got something in len, if we have, we have successfully changed language\n\t\tif (len(lines) != 0) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(end) //print error msg\n\t\t}\n\t}\n}", "func (c *IndexController) setLang() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tbeego.Debug(len(Langs))\n\tif len(Langs) == 0 {\n\t\tsettingLocales()\n\t}\n\n\t///*\n\tbeego.Debug(hasCookie)\n\tbeego.Debug(isNeedRedir)\n\t//*/ // 1. Check URL arguments.\n\tlang := c.GetString(\"lang\")\n\t//beego.Debug(lang)\n\t//*\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = c.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\t/*\n\t\tif len(lang) == 0 && this.IsLogin {\n\t\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t\t}\n\t\t//*/\n\t// 4. Get language information from 'Accept-Language'.\n\t//beego.Debug(\"浏览器是什么语言\", c.Ctx.Input.Header(\"Accept-Language\"))\n\t//*\n\tif len(lang) == 0 {\n\t\tal := c.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\t//*/\n\t// 4. DefaucurLang language is English.\n\t//*\n\tif len(lang) == 0 {\n\t\tlang = \"zh-TW\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\t//*\n\tif !hasCookie {\n\t\tc.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tc.Data[\"Lang\"] = lang\n\tc.Data[\"Langs\"] = Langs\n\n\tc.Lang = lang\n\t//\tbeego.Debug(\"坑货的值 :\", isNeedRedir)\n\treturn isNeedRedir\n\t//*/\n}", "func (this *GenericController) setLangVer() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\n\t// 1. Check URL arguments.\n\tpreferredLang := this.GetString(\"preferredLang\", \"\")\n\n\t// 2. Get language information from cookies.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = this.Ctx.GetCookie(\"preferredLang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(preferredLang) {\n\t\tpreferredLang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(preferredLang) == 0 {\n\t\tal := this.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tpreferredLang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = \"ta-LK\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := lang.LangType{\n\t\tLang: preferredLang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.Ctx.SetCookie(\"preferredLang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\trestLangs := make([]*lang.LangType, 0, len(lang.LangTypes)-1)\n\tfor _, v := range lang.LangTypes {\n\t\tif preferredLang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\t// Set language properties.\n\tthis.Lang = preferredLang\n\tthis.Data[\"Lang\"] = curLang.Lang\n\tthis.Data[\"CurLang\"] = curLang.Name\n\tthis.Data[\"RestLangs\"] = restLangs\n\treturn isNeedRedir\n}", "func setLang(lang string) {\n\tif lang == \"pl\" {\n\t\tl = langTexts[\"pl\"]\n\t} else if lang == \"en\" {\n\t\tl = langTexts[\"en\"]\n\t}\n}", "func (a *Api) refreshLocal(res http.ResponseWriter, req *http.Request, vars map[string]string) {\n\tlog.Println(\"refresh locales files from remote system!\")\n\tsuccess := a.localeManager.DownloadLocales(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif !success {\n\t\tlog.Printf(\"error while retriving locales from localizer service!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlocalizer, err := localize.NewI18nLocalizer(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading locales files!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\temailTemplates, err := templates.New(a.Config.I18nTemplatesPath, localizer)\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading templates!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\ta.templates = emailTemplates\n}", "func (h *MemHome) Lang(path string) Lang { return h.langs.lang(path) }", "func (u *GithubGistUpsertOne) UpdateLanguage() *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.UpdateLanguage()\n\t})\n}", "func (l *Language) Update(terms []TermTranslation) (CountResult, error) {\n\tvar res UploadResult\n\t// Typecheck translations\n\tfor _, t := range terms {\n\t\tc := t.Translation.Content\n\t\tif _, ok := c.(string); ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := c.(Plural); ok {\n\t\t\tcontinue\n\t\t}\n\t\treturn res.Translations, ErrTranslationInvalid\n\t}\n\t// Encode and send translations\n\tts, err := json.Marshal(terms)\n\tif err != nil {\n\t\treturn res.Translations, err\n\t}\n\terr = l.post(\"/languages/update\", map[string]string{\"data\": string(ts)}, nil, &res)\n\treturn res.Translations, err\n}", "func Load() {\n\tf, _ := os.Open(filepath.ToSlash(filepath.Join(model.Conf.StaticRoot, \"i18n\")))\n\tnames, _ := f.Readdirnames(-1)\n\tf.Close()\n\n\tfor _, name := range names {\n\t\tif !util.IsLetter(rune(name[0])) || !strings.HasSuffix(name, \".json\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tloc := name[:strings.LastIndex(name, \".\")]\n\t\tload(loc)\n\t}\n\n\tlogger.Tracef(\"loaded [%d] language configuration files\", len(locales))\n}", "func (u *GithubGistUpsert) UpdateLanguage() *GithubGistUpsert {\n\tu.SetExcluded(githubgist.FieldLanguage)\n\treturn u\n}", "func SetLanguageFilePath(path string) string {\n\tlastPath := langFilePath\n\tlangFilePath = path\n\treturn lastPath\n}", "func (c *ExtendedBeegoController) SetLanguange() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\tLoadLanguages()\n\n\t// 1. Check URL arguments.\n\tlang := c.Input().Get(\"lang\")\n\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = c.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(lang) == 0 {\n\t\tal := c.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(lang) == 0 {\n\t\tlang = \"en-US\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := langType{\n\t\tLang: lang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tc.Ctx.SetCookie(\"lang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\tvar langLength = len(i18n.ListLangs())\n\n\tfmt.Println(langLength - 1)\n\n\trestLangs := make([]*langType, 0, langLength-1)\n\tfor _, v := range langTypes {\n\t\tif lang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\n\t// Set language properties.\n\tc.Lang = lang\n\tc.Data[\"Lang\"] = curLang.Lang\n\tc.Data[\"CurLang\"] = curLang.Name\n\tc.Data[\"RestLangs\"] = restLangs\n\n\treturn isNeedRedir\n}", "func goLanguages(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar langs Languages = getLanguages();\n\tif err := json.NewEncoder(w).Encode(langs); err != nil {\n\t\tpanic(err)\n\t}\n}", "func goLanguages(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar langs Languages = getLanguages();\n\tif err := json.NewEncoder(w).Encode(langs); err != nil {\n\t\tpanic(err)\n\t}\n}", "func init() {\n\tlanguageFile, err := os.Open(\"settings/languages/\" + Config.General.Language + \".json\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbyteValue, _ := ioutil.ReadAll(languageFile)\n\n\terr = json.Unmarshal(byteValue, &Language)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer languageFile.Close()\n}", "func (m *MailboxSettings) SetLanguage(value LocaleInfoable)() {\n err := m.GetBackingStore().Set(\"language\", value)\n if err != nil {\n panic(err)\n }\n}", "func (e *HTMLApplet) Lang(v string) *HTMLApplet {\n\te.a[\"lang\"] = v\n\treturn e\n}", "func (a *App) updateViews() {\n\t// if a.state.Settings[\"TLDSubstitutions\"] {\n\t// \ta.writeView(viewSettings, \"[X] TLD substitutions\")\n\t// } else {\n\t// \ta.writeView(viewSettings, \"[ ] TLD substitutions\")\n\t// }\n}", "func loadMessageFile(path string) (err error) {\n\t// open the static i18n file\n\tf, err := pkger.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tb := bytes.NewBufferString(\"\")\n\t// copy to contents of the file to a buffer string\n\tif _, err = io.Copy(b, f); err != nil {\n\t\tpanic(err)\n\t}\n\t// read the contents of the file to a byte array\n\tout, _ := ioutil.ReadAll(b)\n\t// load the contents into context\n\tbundle.RegisterUnmarshalFunc(\"toml\", toml.Unmarshal)\n\t_, err = bundle.ParseMessageFileBytes(out, \"en.toml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Loadlangdata(id1 string, id2 int) {\n\n\t/*\n\t\t// arcanesData\n\n\t\turl := \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/arcanesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/arcanesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ := http.NewRequest(\"GET\", url, nil)\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\tarcanesData[id1] = string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// conclaveData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/conclaveData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/conclaveData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tconclaveData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// eventsData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/eventsData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/eventsData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\teventsData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// operationTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/operationTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/operationTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\toperationTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// persistentEnemyData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/persistentEnemyData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/persistentEnemyData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tpersistentEnemyData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\t// solNodes\n\turl := Dirpath + \"data/\" + id1 + \"/solNodes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"solNodes.json\"\n\t}\n\treq, err := os.Open(url)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tdefer req.Close()\n\tbody, _ := ioutil.ReadAll(req)\n\tfmt.Println(id1)\n\tvar result map[string]interface{}\n\tjson.Unmarshal([]byte(body), &result)\n\tSortieloc[id1] = result\n\n\t// sortieData\n\turl = Dirpath + \"data/\" + id1 + \"/sortieData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"sortieData.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\terr = json.Unmarshal(body, &Sortielang)\n\tSortiemodtypes[id1] = make(LangMap)\n\tSortiemodtypes[id1] = Sortielang[\"modifierTypes\"]\n\tSortiemoddesc[id1] = Sortielang[\"modifierDescriptions\"]\n\tSortiemodbosses[id1] = Sortielang[\"bosses\"]\n\n\t// FissureModifiers\n\turl = Dirpath + \"data/\" + id1 + \"/fissureModifiers.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"fissureModifiers.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFissureModifiers[id1] = result\n\n\t// MissionTypes\n\turl = Dirpath + \"data/\" + id1 + \"/missionTypes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"missionTypes.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tMissionTypes[id1] = result\n\n\t// languages\n\turl = Dirpath + \"data/\" + id1 + \"/languages.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"languages.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tLanguages[id1] = result\n\n\t// FactionsData\n\turl = Dirpath + \"data/\" + id1 + \"/factionsData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"factionsData.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFactionsData[id1] = result\n\n\t// sortieRewards\n\turl = Dirpath + \"data/\" + id1 + \"/sortieRewards.json\"\n\tif id1 != \"en\" {\n\t\t// url = \"https://drops.warframestat.us/data/sortieRewards.json\"\n\t\treturn\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tvar result2 string\n\n\tjson.Unmarshal([]byte(body), &result2)\n\tSortieRewards = body\n\n\t/*\n\t\t// syndicatesData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/syndicatesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/syndicatesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsyndicatesData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// synthTargets\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/synthTargets.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/synthTargets.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsynthTargets[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// upgradeTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/upgradeTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/upgradeTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tupgradeTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// warframes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/warframes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/warframes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\twarframes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// weapons\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/weapons.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/weapons.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tweapons[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\treturn\n}", "func (this *BaseRouter) setLang() bool {\n\tfmt.Println(\"setLang() function\")\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tlangs := conf.Langs\n\n\t// 1. Check URL arguments.\n\tlang := this.GetString(\"lang\")\n\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = this.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\tif len(lang) == 0 && this.IsLogin {\n\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t}\n\n\t// 4. Get language information from 'Accept-Language'.\n\tif len(lang) == 0 {\n\t\tal := this.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. DefaucurLang language is English.\n\tif len(lang) == 0 {\n\t\tlang = \"en-US\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tthis.Data[\"Lang\"] = lang\n\tthis.Data[\"Langs\"] = langs\n\n\tthis.Lang = lang\n\n\treturn isNeedRedir\n}", "func (u *GithubGistUpsertBulk) UpdateLanguage() *GithubGistUpsertBulk {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.UpdateLanguage()\n\t})\n}", "func initLocales(opt Options) {\n\tfor i, lang := range opt.Langs {\n\t\tfname := fmt.Sprintf(opt.Format, lang)\n\t\t// Append custom locale file.\n\t\tcustom := []interface{}{}\n\t\tcustomPath := path.Join(opt.CustomDirectory, fname)\n\t\tif com.IsFile(customPath) {\n\t\t\tcustom = append(custom, customPath)\n\t\t}\n\n\t\tvar locale interface{}\n\t\tif data, ok := opt.Files[fname]; ok {\n\t\t\tlocale = data\n\t\t} else {\n\t\t\tlocale = path.Join(opt.Directory, fname)\n\t\t}\n\n\t\terr := i18n.SetMessageWithDesc(lang, opt.Names[i], locale, custom...)\n\t\tif err != nil && err != i18n.ErrLangAlreadyExist {\n\t\t\tpanic(fmt.Errorf(\"fail to set message file(%s): %v\", lang, err))\n\t\t}\n\t}\n}", "func (cc *CommonController) SwitchLanguage() {\n\tlang := cc.GetString(\"lang\")\n\thash := cc.GetString(\"hash\")\n\tif _, exist := supportLanguages[lang]; !exist {\n\t\tlang = defaultLang\n\t}\n\tcc.SetSession(\"lang\", lang)\n\tcc.Data[\"Lang\"] = lang\n\tcc.Redirect(cc.Ctx.Request.Header.Get(\"Referer\")+hash, http.StatusFound)\n}", "func (m *InvitedUserMessageInfo) SetMessageLanguage(value *string)() {\n err := m.GetBackingStore().Set(\"messageLanguage\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Client) UpdateResLang(rl *ResLang) error {\n\treturn c.UpdateResLangs([]int64{rl.Id.Get()}, rl)\n}", "func initTranslationClients(b *backends) {\n\tlog.Println(\"cnweb.initTranslationClients enter\")\n\tdeepLKey, ok := os.LookupEnv(deepLKeyName)\n\tif !ok {\n\t\tlog.Printf(\"%s not set\\n\", deepLKeyName)\n\t} else {\n\t\tb.deepLApiClient = transtools.NewDeepLClient(deepLKey)\n\t}\n\tb.translateApiClient = transtools.NewGoogleClient()\n\tglossaryName, ok := os.LookupEnv(glossaryKeyName)\n\tif !ok {\n\t\tlog.Printf(\"%s not set\\n\", glossaryKeyName)\n\t} else {\n\t\tprojectID, ok := os.LookupEnv(projectIDKey)\n\t\tif !ok {\n\t\t\tlog.Printf(\"%s not set\\n\", projectIDKey)\n\t\t} else {\n\t\t\tb.glossaryApiClient = transtools.NewGlossaryClient(projectID, glossaryName)\n\t\t}\n\t}\n\tfExpected, err := os.Open(transtools.ExpectedDataFile)\n\tif err != nil {\n\t\tlog.Printf(\"initTranslationClients: Error opening expected file: %v\", err)\n\t\treturn\n\t}\n\tfReplace, err := os.Open(transtools.ReplaceDataFile)\n\tif err != nil {\n\t\tlog.Printf(\"initTranslationClients: Error opening replace file: %v\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err = fExpected.Close(); err != nil {\n\t\t\tlog.Printf(\"Error closing expected file: %v\", err)\n\t\t}\n\t\tif err = fReplace.Close(); err != nil {\n\t\t\tlog.Printf(\"Error closing replace file: %v\", err)\n\t\t}\n\t}()\n\tb.translationProcessor = transtools.NewProcessor(fExpected, fReplace)\n}", "func (c *Lang) applyFile(code string) (error, string) {\n\n\t_, header, err := c.GetFile(\"file\")\n\tif err != nil {\n\t\treturn err, T(\"lang_nofile\")\n\t}\n\n\ta := strings.Split(header.Filename, \".\")\n\tif l := len(a); l < 2 || strings.ToLower(a[l-1]) != \"json\" {\n\t\treturn errors.New(\"client validation by file type hacked\"), T(\"lang_badfile\")\n\t}\n\n\ts := c.langFileName(\"tmp_dir\", code)\n\n\terr = c.SaveToFile(\"file\", s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\terr = i18n.LoadTranslationFile(s)\n\tdefer os.Remove(s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\ts2 := c.langFileName(\"lang::folder\", code)\n\terr = c.SaveToFile(\"file\", s2)\n\tif err == nil {\n\t\terr = i18n.LoadTranslationFile(s2)\n\t}\n\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\treturn nil, \"\"\n}", "func ChangeLanguage(c buffalo.Context) error {\n\tf := struct {\n\t\tOldLanguage string `form:\"oldLanguage\"`\n\t\tLanguage string `form:\"language\"`\n\t\tURL string `form:\"url\"`\n\t}{}\n\tif err := c.Bind(&f); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Set new language prefix\n\tif f.URL == fmt.Sprintf(\"/%s\", f.OldLanguage) {\n\t\tf.URL = \"\"\n\t} else {\n\t\tp := fmt.Sprintf(\"/%s/\", f.OldLanguage)\n\t\tf.URL = strings.TrimPrefix(f.URL, p)\n\t}\n\n\treturn c.Redirect(302, fmt.Sprintf(\"/%s/%s\", f.Language, f.URL))\n}", "func NotifyUILanguageChange(dwFlags DWORD, pcwstrNewLanguage string, pcwstrPreviousLanguage string, dwReserved DWORD, pdwStatusRtrn *DWORD) bool {\n\tpcwstrNewLanguageStr := unicode16FromString(pcwstrNewLanguage)\n\tpcwstrPreviousLanguageStr := unicode16FromString(pcwstrPreviousLanguage)\n\tret1 := syscall6(notifyUILanguageChange, 5,\n\t\tuintptr(dwFlags),\n\t\tuintptr(unsafe.Pointer(&pcwstrNewLanguageStr[0])),\n\t\tuintptr(unsafe.Pointer(&pcwstrPreviousLanguageStr[0])),\n\t\tuintptr(dwReserved),\n\t\tuintptr(unsafe.Pointer(pdwStatusRtrn)),\n\t\t0)\n\treturn ret1 != 0\n}", "func SetLocale(o orm.Ormer, lang, code, message string) error {\n\tvar it Locale\n\terr := o.QueryTable(&it).\n\t\tFilter(\"lang\", lang).\n\t\tFilter(\"code\", code).\n\t\tOne(&it, \"id\")\n\n\tif err == nil {\n\t\t_, err = o.QueryTable(&it).Filter(\"id\", it.ID).Update(orm.Params{\n\t\t\t\"message\": message,\n\t\t\t\"updated_at\": time.Now(),\n\t\t})\n\t} else if err == orm.ErrNoRows {\n\t\tit.Lang = lang\n\t\tit.Code = code\n\t\tit.Message = message\n\t\t_, err = o.Insert(&it)\n\t}\n\treturn err\n}", "func (m *store) Update(w ukjent.Word) error {\n\tdefer m.withWrite()()\n\tm.data[w.Word] = entry{w.Translation, w.Note}\n\treturn nil\n}", "func ClientLocationUpdate(cll models.ClientListLocation, m *models.Message) {\n\tif cll.ID <= 0 {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"especifique localizacion\"\n\t\treturn\n\t}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\terr := updateClientLocation(&cll, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"descripcion de ubicacion no se actualizo\"\n\t\treturn\n\t}\n\tm.Code = http.StatusOK\n\tm.Message = \"se actualizo descripcion de ubicacion\"\n\tm.Data = cll\n}", "func (c *Conn) SetLanguage(code string) {\n\tc.headers.Set(\"Accept-Language\", code)\n}", "func (d Document) Language() string { return d.language }", "func I18n(options ...Options) macaron.Handler {\n\topt := prepareOptions(options)\n\tinitLocales(opt)\n\treturn func(ctx *macaron.Context) {\n\t\tisNeedRedir := false\n\t\thasCookie := false\n\n\t\t// 1. Check URL arguments.\n\t\tlang := ctx.Query(opt.Parameter)\n\n\t\t// 2. Get language information from cookies.\n\t\tif len(lang) == 0 {\n\t\t\tlang = ctx.GetCookie(\"lang\")\n\t\t\thasCookie = true\n\t\t} else {\n\t\t\tisNeedRedir = true\n\t\t}\n\n\t\t// Check again in case someone modify by purpose.\n\t\tif !i18n.IsExist(lang) {\n\t\t\tlang = \"\"\n\t\t\tisNeedRedir = false\n\t\t\thasCookie = false\n\t\t}\n\n\t\t// 3. Get language information from 'Accept-Language'.\n\t\tif len(lang) == 0 {\n\t\t\tal := ctx.Req.Header.Get(\"Accept-Language\")\n\t\t\tif len(al) > 4 {\n\t\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\t\tif i18n.IsExist(al) {\n\t\t\t\t\tlang = al\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 4. Default language is the first element in the list.\n\t\tif len(lang) == 0 {\n\t\t\tlang = i18n.GetLangByIndex(0)\n\t\t\tisNeedRedir = false\n\t\t}\n\n\t\tcurLang := LangType{\n\t\t\tLang: lang,\n\t\t}\n\n\t\t// Save language information in cookies.\n\t\tif !hasCookie {\n\t\t\tctx.SetCookie(\"lang\", curLang.Lang, 1<<31-1, \"/\"+strings.TrimPrefix(opt.SubURL, \"/\"))\n\t\t}\n\n\t\trestLangs := make([]LangType, 0, i18n.Count()-1)\n\t\tlangs := i18n.ListLangs()\n\t\tnames := i18n.ListLangDescs()\n\t\tfor i, v := range langs {\n\t\t\tif lang != v {\n\t\t\t\trestLangs = append(restLangs, LangType{v, names[i]})\n\t\t\t} else {\n\t\t\t\tcurLang.Name = names[i]\n\t\t\t}\n\t\t}\n\n\t\t// Set language properties.\n\t\tlocale := Locale{i18n.Locale{lang}}\n\t\tctx.Map(locale)\n\t\tctx.Locale = locale\n\t\tctx.Data[opt.TmplName] = locale\n\t\tctx.Data[\"Tr\"] = i18n.Tr\n\t\tctx.Data[\"Lang\"] = locale.Lang\n\t\tctx.Data[\"LangName\"] = curLang.Name\n\t\tctx.Data[\"AllLangs\"] = append([]LangType{curLang}, restLangs...)\n\t\tctx.Data[\"RestLangs\"] = restLangs\n\n\t\tif opt.Redirect && isNeedRedir {\n\t\t\tctx.Redirect(opt.SubURL + ctx.Req.RequestURI[:strings.Index(ctx.Req.RequestURI, \"?\")])\n\t\t}\n\t}\n}", "func (r *Repository) ChangeVOfficeLanguage(ctx context.Context, officeID string, langs []*qualifications.Language) error {\r\n\r\n\tobjID, err := primitive.ObjectIDFromHex(officeID)\r\n\tif err != nil {\r\n\t\treturn errors.New(\"wrong_ID\")\r\n\t}\r\n\tr.officeCollection.UpdateOne(\r\n\t\tctx,\r\n\t\tbson.M{\r\n\t\t\t\"_id\": objID,\r\n\t\t},\r\n\r\n\t\tbson.M{\r\n\t\t\t\"$set\": bson.M{\r\n\t\t\t\t\"languages\": langs,\r\n\t\t\t},\r\n\t\t},\r\n\t\toptions.Update().SetUpsert(true),\r\n\t)\r\n\tif err != nil {\r\n\t\tif err == mongo.ErrNoDocuments {\r\n\t\t\treturn errors.New(\"not_found\")\r\n\t\t}\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (c *sshConfig) update() error {\n\tif fileExists(c.path) {\n\t\terr := copyFile(c.path, c.path+\".linode-ssh-config.bak\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcontents, err := c.render()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(c.path, contents, 0644)\n}", "func updateFromFile(cLink, fileName, user, passw string, params url.Values, headers map[string]string, client *http.Client) (solrResp *glsolr.Response, err error) {\r\n\tfile, err := os.Open(fileName)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tdefer file.Close()\r\n\r\n\tsolrResp, err = glsolr.Update(cLink, user, passw, file, params, headers, client)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn solrResp, nil\r\n}", "func (i *I18n) Serve(ctx context.Context) {\n\twasByCookie := false\n\n\tlanguage := i.Default\n\n\tlangKey := ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()\n\tif ctx.Values().GetString(langKey) == \"\" {\n\t\t// try to get by url parameter\n\t\tlanguage = ctx.URLParam(i.URLParameter)\n\t\tif language == \"\" {\n\t\t\t// then try to take the lang field from the cookie\n\t\t\tlanguage = ctx.GetCookie(langKey)\n\n\t\t\tif len(language) > 0 {\n\t\t\t\twasByCookie = true\n\t\t\t} else {\n\t\t\t\t// try to get by the request headers.\n\t\t\t\tlangHeader := ctx.GetHeader(\"Accept-Language\")\n\t\t\t\tif len(langHeader) > 0 {\n\t\t\t\t\tfor _, langEntry := range strings.Split(langHeader, \",\") {\n\t\t\t\t\t\tlc := strings.Split(langEntry, \";\")[0]\n\t\t\t\t\t\tfor _, tag := range i.Bundle.LanguageTags() {\n\t\t\t\t\t\t\tcode := strings.Split(lc, \"-\")[0]\n\t\t\t\t\t\t\tif strings.Contains(tag.String(), code) {\n\t\t\t\t\t\t\t\tlanguage = lc\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}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// if it was not taken by the cookie, then set the cookie in order to have it\n\t\tif !wasByCookie {\n\t\t\tctx.SetCookieKV(langKey, language)\n\t\t}\n\t}\n\n\tlocalizer := i18n.NewLocalizer(i.Bundle, language)\n\n\tctx.Values().Set(langKey, language)\n\ttranslateFuncKey := ctx.Application().ConfigurationReadOnly().GetTranslateFunctionContextKey()\n\t//wrap tr to raw func for ctx.Translate usage\n\tctx.Values().Set(translateFuncKey, func(translationID string, args ...interface{}) string {\n\t\tdesc := \"\"\n\t\tif len(args) > 0 {\n\t\t\tif v, ok := args[0].(string); ok {\n\t\t\t\tdesc = v\n\t\t\t}\n\t\t}\n\n\t\ttranslated, err := localizer.LocalizeMessage(&i18n.Message{ID: translationID, Description: desc})\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\treturn translated\n\t})\n\n\tctx.Next()\n}", "func (lId *LangId) UpdateFromTxt(filename string, dispAvailableVarNames ...bool) error {\n\n\tvar tmpMap = lId.buildTmpMap()\n\n\tif err := lId.fmtTxtFile(filename); err != nil {\n\t\treturn err\n\t}\n\n\tif len(dispAvailableVarNames) > 0 && dispAvailableVarNames[0] {\n\t\tlId.getVarNames()\n\t\treturn nil\n\t}\n\n\tfor idx := 0; idx < len(lId.lines); idx++ {\n\n\t\tline := lId.lines[idx]\n\n\t\tswitch {\n\n\t\tcase len(line) == 0:\n\t\t\tcontinue\n\n\t\tcase line == \"%%\":\n\t\t\t// Reset tmp storage\n\t\t\tif len(tmpMap) > 0 {\n\t\t\t\tlId.LangId = append(lId.LangId, lId.storeEntry(tmpMap))\n\t\t\t}\n\t\t\ttmpMap = lId.buildTmpMap()\n\t\t\tcontinue\n\t\t}\n\n\t\tok, variable, value := lId.isRecognizedVar(line)\n\t\tif !ok {\n\t\t\tlog.Printf(\"Unrecognized variable: %s\\n\", line)\n\t\t\tcontinue\n\t\t}\n\t\t// 'Description' field may be repeated more than one time\n\t\tif variable == \"Description\" {\n\t\t\tif tmpMap[variable] != NA_STR && !strings.Contains(tmpMap[variable], value) {\n\t\t\t\ttmpMap[variable] = tmpMap[variable] + \", \" + value\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ttmpMap[variable] = value\n\t}\n\n\treturn nil\n}", "func (y *Handler) setLanguages(ctx context.Context, direction string) error {\n\tfromLanguage, toLanguage, err := y.detectLanguages(ctx, direction, y.text)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif knowLanguages(fromLanguage, toLanguage) {\n\t\ty.fromLanguage, y.toLanguage = fromLanguage, toLanguage\n\t\treturn nil\n\t}\n\n\tlanguages, err := y.loadLanguages(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not set languages: %w\", err)\n\t}\n\n\tif !languages.Contains(fromLanguage, toLanguage) {\n\t\treturn fmt.Errorf(\"unknown language direction: %s -> %s\\n%v\", fromLanguage, toLanguage, languages.String())\n\t}\n\n\ty.fromLanguage, y.toLanguage = fromLanguage, toLanguage\n\treturn nil\n}", "func (g *Goi18n) add(lc *locale) bool {\n\tif _, ok := g.localeMap[lc.lang]; ok {\n\t\treturn false\n\t}\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tif err := lc.Reload(g.option.Path); err != nil {\n\t\treturn false\n\t}\n\tlc.id = len(g.localeMap)\n\tg.localeMap[lc.lang] = lc\n\tg.langs = append(g.langs, lc.lang)\n\tg.langDescs[lc.lang] = lc.langDesc\n\treturn true\n}", "func ChangeLang(socketID uuid.UUID, lang int) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\tif _, ok := sessionCache[socketID]; ok && sessionCache[socketID].lang != lang {\n\t\tsessionVar := sessionCache[socketID]\n\t\tsessionVar.lang = lang\n\t\tsessionCache[socketID] = sessionVar\n\t}\n}", "func localizeConstantStrings(project Project) Project {\n\tvar fileContents = readFile(project.ConstantFile.Path)\n\tvar linesArray = contentToLinesArray(fileContents)\n\tfor _, line := range linesArray {\n\t\tif !strings.Contains(line, \"NSLocalizedString(\\\"\") { //if line does not contain NSLocalizedString\n\t\t\tif strArray := getStringsFromLine(line, false); len(strArray) > 0 { //ensures that the line has a string that is OK to be translated\n\t\t\t\tif len(strArray) > 1 { //little error handling that will more than likely not get executed\n\t\t\t\t\tunexpectedError(\"Line \" + line + \" unexpectedly have multiple strings.\")\n\t\t\t\t}\n\t\t\t\tvar str = strArray[0]\n\t\t\t\tvar localizedStr = \"NSLocalizedString(\" + str + \", comment: \\\"\\\")\"\n\t\t\t\tfileContents = strings.Replace(fileContents, str, localizedStr, 1) //from fileContents, replace the doubleQuotedWord with our variableName, -1 means globally, but changed it to one at a time\n\t\t\t\tupdateLocalizableStrings(project, str)\n\t\t\t}\n\t\t}\n\t}\n\treplaceFile(project.ConstantFile.Path, fileContents)\n\treturn project\n}", "func langFetch(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tprintln(\"📝 Currently on Language Control page.\")\n\n\tglobals.Tmpl.ExecuteTemplate(w, \"langs_fetch.gohtml\", langCtrl.FetchLangs())\n}", "func main() {\n\t//predef of 4 languages\n\tlanguages[0] = \"english\"\n\tlanguages[1] = \"日本語\"\n\tlanguages[2] = \"deutsch\"\n\tlanguages[3] = \"svenska\"\n\n\t//starting client\n\tclient()\n}", "func (g *Goi18n) SetLanguage(lang string, desc string) bool {\n\tif g.IsExist(lang) {\n\t\tg.langDescs[lang] = desc\n\t\tif err := g.Reload(lang); err != nil {\n\t\t\tfmt.Printf(\"Goi18n.SetLanguage: %v\\n\", err)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else {\n\t\treturn g.add(&locale{lang: lang, langDesc: desc})\n\t}\n}", "func (m *AgreementFile) SetLocalizations(value []AgreementFileLocalizationable)() {\n m.localizations = value\n}", "func (upr UpdatePathResponse) ContentLanguage() string {\n\treturn upr.rawResponse.Header.Get(\"Content-Language\")\n}", "func (y *Handler) loadLanguages(ctx context.Context) (result.Languages, error) {\n\tif y.isDictionary {\n\t\treturn dictionary.LoadLanguages(ctx, y.client, y.config)\n\t}\n\treturn translation.LoadLanguages(ctx, y.client, y.config)\n}", "func SetLanguage(language string) {\r\n\tcurrentLanguage = language\r\n}", "func (c *Client) Notify(text string, language ...string) error {\n\tlang := c.lang\n\tif len(language) != 0 {\n\t\tlang = language[0]\n\t}\n\tif c.accent != \"\" {\n\t\tlang = fmt.Sprintf(\"%s-%s\", lang, c.accent)\n\t}\n\n\turl, err := googletts.GetTTSURL(text, lang)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Play(url)\n}", "func (ts *TranslationService) loadFiles() {\n\tfor _, fileName := range ts.translationFiles {\n\t\terr := ts.i18bundle.LoadTranslationFile(fileName)\n\t\tif err != nil {\n\t\t\tts.logger.Warn(fmt.Sprintf(\"loading of translationfile %s failed: %s\", fileName, err))\n\t\t}\n\t}\n\n\tts.lastReload = time.Now()\n}", "func (suite *IndexerSuite) usfc(uid string, lang string) {\n\tr := require.New(suite.T())\n\terr := updateSourceFileContent(uid, lang)\n\tr.Nil(err)\n}", "func (client *Client) SetLanguage(langs ...string) error {\n\tif len(langs) == 0 {\n\t\treturn fmt.Errorf(\"languages cannot be empty\")\n\t}\n\n\tclient.Languages = langs\n\n\tclient.flagForInit()\n\n\treturn nil\n}", "func (leaf *Node) updateContent() (err error) {\n\tif leaf.Size > MaxFileSize {\n\t\treturn nil\n\t}\n\n\tleaf.V, err = ioutil.ReadFile(leaf.SysPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetLang(lang string) {\n\tAPI.Lang = lang\n}", "func (c *connAttrs) SetLocale(locale string) { c.mu.Lock(); defer c.mu.Unlock(); c._locale = locale }", "func UpsertUserLanguage(userID, voiceToken string) error {\n\treturn upsertImpl(userID, voiceToken, \"language\")\n}", "func (s *ClientState) UpdateMasterFile() {\n\tpath := s.GetConfig().RedisMasterFile\n\tsystems := make(map[string]string, 0)\n\tfor system, rs := range s.redisSystems {\n\t\tif rs.currentMaster == nil {\n\t\t\tsystems[system] = \"\"\n\t\t} else {\n\t\t\tsystems[system] = rs.currentMaster.server\n\t\t}\n\t}\n\tcontent := MarshalMasterFileContent(systems)\n\tWriteRedisMasterFile(path, content)\n}", "func (c *configData) update() error {\n\tif err := c.Global.WriteConfig(); err != nil {\n\t\treturn err\n\t}\n\t// return c.Local.WriteConfig() // TODO: Get local working.\n\treturn nil\n}", "func update(vs *ViewServer, primary string, backup string){\n\tvs.currentView.Viewnum += 1\n\tvs.currentView.Primary = primary\n\tvs.currentView.Backup = backup\n\tvs.idleServer = \"\"\n\tvs.primaryACK = false\n\tvs.backupACK = false\n}", "func writeUserLangOnCookie(c *fiber.Ctx, lang string) {\n\tlangCookie := &fiber.Cookie{\n\t\tHTTPOnly: false,\n\t\tName: \"social-lang\",\n\t\tValue: lang,\n\t\tPath: \"/\",\n\t\tDomain: authConfig.AuthConfig.CookieRootDomain,\n\t}\n\tc.Cookie(langCookie)\n}", "func SetLang(newLang string) error {\n\tfound := false\n\tfor _, l := range availLangs {\n\t\tif newLang == l {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn ErrNoLanguageFn(newLang)\n\t}\n\tlang = newLang\n\treturn nil\n}", "func (m *ChatMessage) SetLocale(value *string)() {\n m.locale = value\n}", "func LoadTranslations() error {\r\n\tbox := packr.NewBox(translationsPath)\r\n\tfor _, translationFilePath := range box.List() {\r\n\t\ttranslationFile, err := box.Open(translationFilePath)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tdefer translationFile.Close()\r\n\r\n\t\tbyteValue, _ := ioutil.ReadAll(translationFile)\r\n\r\n\t\tvar translation translationItem\r\n\t\terr = json.Unmarshal(byteValue, &translation)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\ttranslations = append(translations, translation)\r\n\t}\r\n\r\n\treturn nil\r\n}", "func SetClientLocale(locale string) {\n\tclientLocale = locale\n}", "func SetLanguage(language string) {\n\tif constants.GetAvailableSelectionID(language, constants.AvailableLangs, -1) < 0 {\n\t\tsetValue(\"common\", \"language\", getDefault(\"common\", \"language\"))\n\t} else {\n\t\tsetValue(\"common\", \"language\", language)\n\t}\n}", "func currentLang() string {\n\treturn fmt.Sprintf(\"go1.%d\", goversion.Version)\n}", "func SetHomeLocale(city string, state string, latitude string, longitude string) (string, error) {\n\tvar message string\n\tConfig.Home.City = city\n\tConfig.Home.State = state\n\tConfig.Home.Latitude = latitude\n\tConfig.Home.Longitude = longitude\n\n\tc, err := json.Marshal(Config)\n\tif err != nil {\n\t\tmessage = \"Failed to update home locale.\"\n\t}\n\n\terr = ioutil.WriteFile(\"./config.json\", c, 0644)\n\tif err != nil {\n\t\tmessage = \"Failed to update home locale.\"\n\t}\n\n\tif message == \"\" {\n\t\tmessage = \"Updated home locale successfully.\"\n\t}\n\tprintln(message)\n\treturn message, nil\n}", "func (r *Account) Language(lang int) (*Entities.Account, error) {\n\tresource := fmt.Sprintf(\"/account/language?idDisplayLanguage=%d\", lang)\n\tbody, err := r.cl.Request(mkm.Put, resource, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount := &Entities.Account{}\n\terr = json.Unmarshal(body, account)\n\treturn account, err\n}", "func (n *NupsCtr) UpdateKouji(c *gin.Context) {\n\treturn\n\n}", "func (c *Lang) cleanLang(code string) error {\n\ts := c.langFileName(\"tmp_dir\", code)\n\terr := ioutil.WriteFile(s, []byte(\"[]\"), 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(s)\n\treturn i18n.LoadTranslationFile(s)\n}", "func (s *InfoService) Languages(ctx context.Context) (languages *Languages, resp *http.Response, err error) {\n\tu := \"/api/v1/infos/languages\"\n\treq, err := s.client.NewRequest(\"GET\", u, \"\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err = s.client.Do(ctx, req, &languages)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn languages, resp, nil\n}", "func i18nLoad(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\ti18n.Load()\n\n\t\thandler(w, r)\n\t}\n}", "func Lang() build8.Lang { return lang{} }", "func ChangePreferedLanguage(r *http.Request) {\n\tvar matcher = language.NewMatcher([]language.Tag{\n\t\tlanguage.English, // The first language is used as fallback.\n\t\tlanguage.Chinese,\n\t})\n\n\taccept := r.Header.Get(\"Accept-Language\")\n\ttag, _ := language.MatchStrings(matcher, accept)\n\tif strings.HasPrefix(tag.String(), \"zh\") {\n\t\tchangeLocale(\"zh_CN\")\n\t} else {\n\t\tchangeLocale(\"en_US\")\n\t}\n}", "func (obj *script) LanguagePath() string {\n\treturn obj.lang\n}", "func (c *Client) UpdateResLangs(ids []int64, rl *ResLang) error {\n\treturn c.Update(ResLangModel, ids, rl)\n}", "func chineseTranslationSet() TranslationSet {\n\treturn TranslationSet{\n\t\tNotEnoughSpace: \"没有足够的空间来渲染面板\",\n\t\tDiffTitle: \"差异\",\n\t\tFilesTitle: \"文件\",\n\t\tBranchesTitle: \"分支\",\n\t\tCommitsTitle: \"提交\",\n\t\tStashTitle: \"贮藏\",\n\t\tUnstagedChanges: `未暂存更改`,\n\t\tStagedChanges: `已暂存更改`,\n\t\tMainTitle: \"主要\",\n\t\tStagingTitle: \"正在暂存\",\n\t\tMergingTitle: \"正在合并\",\n\t\tNormalTitle: \"正常\",\n\t\tCommitSummary: \"提交信息\",\n\t\tCredentialsUsername: \"用户名\",\n\t\tCredentialsPassword: \"密码\",\n\t\tCredentialsPassphrase: \"输入 SSH 密钥的密码\",\n\t\tPassUnameWrong: \"密码 和/或 用户名错误\",\n\t\tCommitChanges: \"提交更改\",\n\t\tAmendLastCommit: \"修补最后一次提交\",\n\t\tAmendLastCommitTitle: \"修补最后一次提交\",\n\t\tSureToAmend: \"您确定要修补上一次提交吗?之后您可以从提交面板更改提交消息。\",\n\t\tNoCommitToAmend: \"没有需要提交的修补。\",\n\t\tCommitChangesWithEditor: \"提交更改(使用编辑器编辑提交信息)\",\n\t\tStatusTitle: \"状态\",\n\t\tMenu: \"菜单\",\n\t\tExecute: \"执行\",\n\t\tToggleStaged: \"切换暂存状态\",\n\t\tToggleStagedAll: \"切换所有文件的暂存状态\",\n\t\tToggleTreeView: \"切换文件树视图\",\n\t\tOpenMergeTool: \"打开外部合并工具 (git mergetool)\",\n\t\tRefresh: \"刷新\",\n\t\tPush: \"推送\",\n\t\tPull: \"拉取\",\n\t\tScroll: \"滚动\",\n\t\tMergeConflictsTitle: \"合并冲突\",\n\t\tCheckout: \"检出\",\n\t\tNoChangedFiles: \"没有更改过文件\",\n\t\tPullWait: \"正在拉取…\",\n\t\tPushWait: \"正在推送…\",\n\t\tFetchWait: \"正在抓取…\",\n\t\tSoftReset: \"软重置\",\n\t\tAlreadyCheckedOutBranch: \"您已经检出至此分支\",\n\t\tSureForceCheckout: \"您确定要强制检出吗?您将丢失所有本地更改\",\n\t\tForceCheckoutBranch: \"强制检出分支\",\n\t\tBranchName: \"分支名称\",\n\t\tNewBranchNameBranchOff: \"新分支名称(基于 {{.branchName}})\",\n\t\tCantDeleteCheckOutBranch: \"您不能删除已检出的分支!\",\n\t\tForceDeleteBranchMessage: \"{{.selectedBranchName}} 还没有被完全合并。您确定要删除它吗?\",\n\t\tRebaseBranch: \"将已检出的分支变基到该分支\",\n\t\tCantRebaseOntoSelf: \"您不能将分支变基到其自身\",\n\t\tCantMergeBranchIntoItself: \"您不能将分支合并到其自身\",\n\t\tForceCheckout: \"强制检出\",\n\t\tCheckoutByName: \"按名称检出\",\n\t\tNewBranch: \"新分支\",\n\t\tNoBranchesThisRepo: \"此仓库中没有分支\",\n\t\tCommitWithoutMessageErr: \"您必须编写提交消息才能进行提交\",\n\t\tCloseCancel: \"关闭\",\n\t\tConfirm: \"确认\",\n\t\tClose: \"关闭\",\n\t\tQuit: \"退出\",\n\t\tSquashDown: \"向下压缩\",\n\t\tFixupCommit: \"修正提交(fixup)\",\n\t\tNoCommitsThisBranch: \"该分支没有提交\",\n\t\tCannotSquashOrFixupFirstCommit: \"There's no commit below to squash into\",\n\t\tFixup: \"修正(fixup)\",\n\t\tSureFixupThisCommit: \"您确定要“修正”此提交吗?它将合并到下面的提交中\",\n\t\tSureSquashThisCommit: \"您确定要将这个提交压缩到下面的提交中吗?\",\n\t\tSquash: \"压缩\",\n\t\tPickCommit: \"选择提交(变基过程中)\",\n\t\tRevertCommit: \"还原提交\",\n\t\tRewordCommit: \"改写提交\",\n\t\tDeleteCommit: \"删除提交\",\n\t\tMoveDownCommit: \"下移提交\",\n\t\tMoveUpCommit: \"上移提交\",\n\t\tEditCommit: \"编辑提交\",\n\t\tAmendToCommit: \"用已暂存的更改来修补提交\",\n\t\tRenameCommitEditor: \"使用编辑器重命名提交\",\n\t\tError: \"错误\",\n\t\tPickHunk: \"选中区块\",\n\t\tPickAllHunks: \"选中所有区块\",\n\t\tUndo: \"撤销\",\n\t\tUndoReflog: \"(通过 reflog)撤销「实验功能」\",\n\t\tRedoReflog: \"(通过 reflog)重做「实验功能」\",\n\t\tPop: \"应用并删除\",\n\t\tDrop: \"删除\",\n\t\tApply: \"应用\",\n\t\tNoStashEntries: \"没有贮藏条目\",\n\t\tStashDrop: \"删除贮藏\",\n\t\tSureDropStashEntry: \"您确定要删除此贮藏条目吗?\",\n\t\tStashPop: \"应用并删除贮藏\",\n\t\tSurePopStashEntry: \"您确定要应用并删除此贮藏条目吗?\",\n\t\tStashApply: \"应用贮藏\",\n\t\tSureApplyStashEntry: \"您确定要应用此贮藏条目?\",\n\t\tNoTrackedStagedFilesStash: \"没有可以贮藏的已跟踪/暂存文件\",\n\t\tStashChanges: \"贮藏更改\",\n\t\tRenameStash: \"Rename stash\",\n\t\tRenameStashPrompt: \"Rename stash: {{.stashName}}\",\n\t\tOpenConfig: \"打开配置文件\",\n\t\tEditConfig: \"编辑配置文件\",\n\t\tForcePush: \"强制推送\",\n\t\tForcePushPrompt: \"您的分支已与远程分支不同。按‘esc’取消,或‘enter’强制推送.\",\n\t\tForcePushDisabled: \"您的分支已与远程分支不同, 并且您已经禁用了强行推送\",\n\t\tUpdatesRejectedAndForcePushDisabled: \"更新被拒绝,您已禁用强制推送\",\n\t\tCheckForUpdate: \"检查更新\",\n\t\tCheckingForUpdates: \"正在检查更新…\",\n\t\tOnLatestVersionErr: \"已是最新版本\",\n\t\tMajorVersionErr: \"新版本 ({{.newVersion}}) 与当前版本 ({{.currentVersion}}) 相比,具有非向后兼容的更改\",\n\t\tCouldNotFindBinaryErr: \"在 {{.url}} 处找不到任何二进制文件\",\n\t\tMergeToolTitle: \"合并工具\",\n\t\tMergeToolPrompt: \"确定要打开 `git mergetool` 吗?\",\n\t\tIntroPopupMessage: chineseIntroPopupMessage,\n\t\tGitconfigParseErr: `由于存在未加引号的'\\'字符,因此 Gogit 无法解析您的 gitconfig 文件。删除它们应该可以解决问题。`,\n\t\tEditFile: `编辑文件`,\n\t\tOpenFile: `打开文件`,\n\t\tIgnoreFile: `添加到 .gitignore`,\n\t\tRefreshFiles: `刷新文件`,\n\t\tMergeIntoCurrentBranch: `合并到当前检出的分支`,\n\t\tConfirmQuit: `您确定要退出吗?`,\n\t\tSwitchRepo: `切换到最近的仓库`,\n\t\tAllBranchesLogGraph: `显示所有分支的日志`,\n\t\tUnsupportedGitService: `不支持的 git 服务`,\n\t\tCreatePullRequest: `创建抓取请求`,\n\t\tCopyPullRequestURL: `将抓取请求 URL 复制到剪贴板`,\n\t\tNoBranchOnRemote: `该分支在远程上不存在. 您需要先将其推送到远程.`,\n\t\tFetch: `抓取`,\n\t\tNoAutomaticGitFetchTitle: `无法自动进行 \"git fetch\"`,\n\t\tNoAutomaticGitFetchBody: `Lazygit 不能在私人仓库中使用 \"git fetch\"; 请在文件面板中使用 'f' 手动运行 \"git fetch\"`,\n\t\tFileEnter: `暂存单个 块/行 用于文件, 或 折叠/展开 目录`,\n\t\tFileStagingRequirements: `只能暂存跟踪文件的单独行`,\n\t\tStageSelection: `切换行暂存状态`,\n\t\tDiscardSelection: `取消变更 (git reset)`,\n\t\tToggleDragSelect: `切换拖动选择`,\n\t\tToggleSelectHunk: `切换选择区块`,\n\t\tToggleSelectionForPatch: `添加/移除 行到补丁`,\n\t\tToggleStagingPanel: `切换到其他面板`,\n\t\tReturnToFilesPanel: `返回文件面板`,\n\t\tFastForward: `从上游快进此分支`,\n\t\tFetching: \"抓取并快进 {{.from}} -> {{.to}} ...\",\n\t\tFoundConflictsTitle: \"自动合并失败\",\n\t\tViewMergeRebaseOptions: \"查看 合并/变基 选项\",\n\t\tNotMergingOrRebasing: \"您目前既不进行变基也不进行合并\",\n\t\tRecentRepos: \"最近的仓库\",\n\t\tMergeOptionsTitle: \"合并选项\",\n\t\tRebaseOptionsTitle: \"变基选项\",\n\t\tCommitSummaryTitle: \"提交讯息\",\n\t\tLocalBranchesTitle: \"分支页面\",\n\t\tSearchTitle: \"搜索\",\n\t\tTagsTitle: \"标签页面\",\n\t\tMenuTitle: \"菜单\",\n\t\tRemotesTitle: \"远程页面\",\n\t\tRemoteBranchesTitle: \"远程分支\",\n\t\tPatchBuildingTitle: \"构建补丁中\",\n\t\tInformationTitle: \"信息\",\n\t\tSecondaryTitle: \"次要\",\n\t\tReflogCommitsTitle: \"Reflog 页面\",\n\t\tGlobalTitle: \"全局键绑定\",\n\t\tConflictsResolved: \"已解决所有冲突。是否继续?\",\n\t\tConfirmMerge: \"您确定要将分支 {{.selectedBranch}} 合并到 {{.checkedOutBranch}} 吗?\",\n\t\tFwdNoUpstream: \"此分支没有上游,无法快进\",\n\t\tFwdNoLocalUpstream: \"此分支的远程未在本地注册,无法快进\",\n\t\tFwdCommitsToPush: \"此分支带有尚未推送的提交,无法快进\",\n\t\tErrorOccurred: \"发生错误!请在以下位置创建 issue\",\n\t\tNoRoom: \"空间不足\",\n\t\tYouAreHere: \"您在这里\",\n\t\tRewordNotSupported: \"当前不支持交互式重新基准化时的重新措词提交\",\n\t\tCherryPickCopy: \"复制提交(拣选)\",\n\t\tCherryPickCopyRange: \"复制提交范围(拣选)\",\n\t\tPasteCommits: \"粘贴提交(拣选)\",\n\t\tSureCherryPick: \"您确定要将选中的提交进行拣选到这个分支吗?\",\n\t\tCherryPick: \"拣选 (Cherry-Pick)\",\n\t\tDonate: \"捐助\",\n\t\tAskQuestion: \"提问咨询\",\n\t\tPrevLine: \"选择上一行\",\n\t\tNextLine: \"选择下一行\",\n\t\tPrevHunk: \"选择上一个区块\",\n\t\tNextHunk: \"选择下一个区块\",\n\t\tPrevConflict: \"选择上一个冲突\",\n\t\tNextConflict: \"选择下一个冲突\",\n\t\tSelectPrevHunk: \"选择顶部块\",\n\t\tSelectNextHunk: \"选择底部块\",\n\t\tScrollDown: \"向下滚动\",\n\t\tScrollUp: \"向上滚动\",\n\t\tScrollUpMainPanel: \"向上滚动主面板\",\n\t\tScrollDownMainPanel: \"向下滚动主面板\",\n\t\tAmendCommitTitle: \"修改提交\",\n\t\tAmendCommitPrompt: \"您确定要使用暂存文件来修改此提交吗?\",\n\t\tDeleteCommitTitle: \"删除提交\",\n\t\tDeleteCommitPrompt: \"您确定要删除此提交吗?\",\n\t\tSquashingStatus: \"正在压缩\",\n\t\tFixingStatus: \"正在修正\",\n\t\tDeletingStatus: \"正在删除\",\n\t\tMovingStatus: \"正在移动\",\n\t\tRebasingStatus: \"正在变基\",\n\t\tAmendingStatus: \"正在修改\",\n\t\tCherryPickingStatus: \"正在拣选\",\n\t\tUndoingStatus: \"正在撤销\",\n\t\tRedoingStatus: \"正在重做\",\n\t\tCheckingOutStatus: \"长子检出\",\n\t\tCommittingStatus: \"正在提交\",\n\t\tCommitFiles: \"提交文件\",\n\t\tViewItemFiles: \"查看提交的文件\",\n\t\tCommitFilesTitle: \"提交文件\",\n\t\tCheckoutCommitFile: \"检出文件\",\n\t\tDiscardOldFileChange: \"放弃对此文件的提交更改\",\n\t\tDiscardFileChangesTitle: \"放弃文件更改\",\n\t\tDiscardFileChangesPrompt: \"您确定要舍弃此提交对该文件的更改吗?如果此文件是在此提交中创建的,它将被删除\",\n\t\tDisabledForGPG: \"该功能不适用于使用 GPG 的用户\",\n\t\tCreateRepo: \"当前目录不在 git 仓库中。是否在此目录创建一个新的 git 仓库?(y/n): \",\n\t\tAutoStashTitle: \"自动存储?\",\n\t\tAutoStashPrompt: \"您必须隐藏并弹出更改以使更改生效。自动执行?(enter/esc)\",\n\t\tStashPrefix: \"自动隐藏更改 \",\n\t\tViewDiscardOptions: \"查看'放弃更改'选项\",\n\t\tCancel: \"取消\",\n\t\tDiscardAllChanges: \"放弃所有更改\",\n\t\tDiscardUnstagedChanges: \"放弃未暂存的变更\",\n\t\tDiscardAllChangesToAllFiles: \"清空工作区\",\n\t\tDiscardAnyUnstagedChanges: \"丢弃未暂存的变更\",\n\t\tDiscardUntrackedFiles: \"丢弃未跟踪的文件\",\n\t\tHardReset: \"硬重置\",\n\t\tViewResetOptions: `查看重置选项`,\n\t\tCreateFixupCommit: `为此提交创建修正`,\n\t\tSquashAboveCommits: `压缩在所选提交之上的所有“fixup!”提交(自动压缩)`,\n\t\tSureSquashAboveCommits: `您确定要压缩在 {{.commit}} 之上的所有“fixup!”提交吗?`,\n\t\tCreateFixupCommitDescription: `创建修正提交`,\n\t\tSureCreateFixupCommit: `您确定要对 {{.commit}} 创建修正提交吗?`,\n\t\tExecuteCustomCommand: \"执行自定义命令\",\n\t\tCustomCommand: \"自定义命令:\",\n\t\tCommitChangesWithoutHook: \"提交更改而无需预先提交钩子\",\n\t\tSkipHookPrefixNotConfigured: \"您尚未配置用于跳过钩子的提交消息前缀。请在您的配置中设置 `git.skipHookPrefix ='WIP'`\",\n\t\tResetTo: `重置为`,\n\t\tPressEnterToReturn: \"按下 Enter 键返回 lazygit\",\n\t\tViewStashOptions: \"查看贮藏选项\",\n\t\tStashAllChanges: \"将所有更改加入贮藏\",\n\t\tStashAllChangesKeepIndex: \"将已暂存的更改加入贮藏\",\n\t\tStashOptions: \"贮藏选项\",\n\t\tNotARepository: \"错误:必须在 git 仓库中运行\",\n\t\tJump: \"跳到面板\",\n\t\tScrollLeftRight: \"左右滚动\",\n\t\tScrollLeft: \"向左滚动\",\n\t\tScrollRight: \"向右滚动\",\n\t\tDiscardPatch: \"丢弃补丁\",\n\t\tDiscardPatchConfirm: \"您一次只能通过一个提交或贮藏条目构建补丁。需要放弃当前补丁吗?\",\n\t\tCantPatchWhileRebasingError: \"处于合并或变基状态时,您无法构建修补程序或运行修补程序命令\",\n\t\tToggleAddToPatch: \"补丁中包含的切换文件\",\n\t\tViewPatchOptions: \"查看自定义补丁选项\",\n\t\tPatchOptionsTitle: \"补丁选项\",\n\t\tNoPatchError: \"尚未创建补丁。你可以在提交中的文件上按下“空格”或使用“回车”添加其中的特定行以开始构建补丁\",\n\t\tEnterFile: \"输入文件以将所选行添加到补丁中(或切换目录折叠)\",\n\t\tExitCustomPatchBuilder: `退出逐行模式`,\n\t\tEnterUpstream: `以这种格式输入上游:'<远程仓库> <分支名称>'`,\n\t\tInvalidUpstream: \"上游格式无效,格式应当为:'<remote> <branchname>'\",\n\t\tReturnToRemotesList: `返回远程仓库列表`,\n\t\tAddNewRemote: `添加新的远程仓库`,\n\t\tNewRemoteName: `新远程仓库名称:`,\n\t\tNewRemoteUrl: `新远程仓库 URL:`,\n\t\tEditRemoteName: `输入远程仓库 {{.remoteName}} 的新名称:`,\n\t\tEditRemoteUrl: `输入远程仓库 {{.remoteName}} 的新 URL:`,\n\t\tRemoveRemote: `删除远程`,\n\t\tRemoveRemotePrompt: \"您确定要删除远程仓库吗?\",\n\t\tDeleteRemoteBranch: \"删除远程分支\",\n\t\tDeleteRemoteBranchMessage: \"您确定要删除远程分支吗?\",\n\t\tSetUpstream: \"设置为检出分支的上游\",\n\t\tSetAsUpstream: \"设置为检出分支的上游\",\n\t\tSetUpstreamTitle: \"设置上游分支\",\n\t\tSetUpstreamMessage: \"您确定要将 {{.checkedOut}} 的上游分支设置为 {{.selected}} 吗?\",\n\t\tEditRemote: \"编辑远程仓库\",\n\t\tTagCommit: \"标签提交\",\n\t\tTagMenuTitle: \"创建标签\",\n\t\tTagNameTitle: \"标签名称\",\n\t\tTagMessageTitle: \"标签消息\",\n\t\tAnnotatedTag: \"附注标签\",\n\t\tLightweightTag: \"轻量标签\",\n\t\tPushTagTitle: \"将 {{.tagName}} 推送到远程仓库:\",\n\t\tPushTag: \"推送标签\",\n\t\tCreateTag: \"创建标签\",\n\t\tFetchRemote: \"抓取远程仓库\",\n\t\tFetchingRemoteStatus: \"抓取远程仓库中\",\n\t\tCheckoutCommit: \"检出提交\",\n\t\tSureCheckoutThisCommit: \"您确定要检出此提交吗?\",\n\t\tGitFlowOptions: \"显示 git-flow 选项\",\n\t\tNotAGitFlowBranch: \"这似乎不是 git flow 分支\",\n\t\tNewGitFlowBranchPrompt: \"新的 {{.branchType}} 名称:\",\n\t\tIgnoreTracked: \"忽略跟踪文件\",\n\t\tIgnoreTrackedPrompt: \"您确定要忽略已跟踪的文件吗?\",\n\t\tViewResetToUpstreamOptions: \"查看上游重置选项\",\n\t\tNextScreenMode: \"下一屏模式(正常/半屏/全屏)\",\n\t\tPrevScreenMode: \"上一屏模式\",\n\t\tStartSearch: \"开始搜索\",\n\t\tPanel: \"面板\",\n\t\tKeybindings: \"按键绑定\",\n\t\tRenameBranch: \"重命名分支\",\n\t\tNewBranchNamePrompt: \"输入分支的新名称\",\n\t\tRenameBranchWarning: \"该分支正在跟踪远程仓库。此操作将仅会重命名本地分支名称,而不会重命名远程分支的名称。确定继续?\",\n\t\tOpenMenu: \"打开菜单\",\n\t\tResetCherryPick: \"重置已拣选(复制)的提交\",\n\t\tNextTab: \"下一个标签\",\n\t\tPrevTab: \"上一个标签\",\n\t\tCantUndoWhileRebasing: \"进行基础调整时无法撤消\",\n\t\tCantRedoWhileRebasing: \"变基时无法重做\",\n\t\tMustStashWarning: \"将补丁拉出到索引中需要存储和取消存储所做的更改。如果出现问题,您将可以从存储中访问文件。继续?\",\n\t\tMustStashTitle: \"必须保存进度\",\n\t\tConfirmationTitle: \"确认面板\",\n\t\tPrevPage: \"上一页\",\n\t\tNextPage: \"下一页\",\n\t\tGotoTop: \"滚动到顶部\",\n\t\tGotoBottom: \"滚动到底部\",\n\t\tFilteringBy: \"过滤依据\",\n\t\tResetInParentheses: \"(重置)\",\n\t\tOpenFilteringMenu: \"查看按路径过滤选项\",\n\t\tFilterBy: \"过滤\",\n\t\tExitFilterMode: \"停止按路径过滤\",\n\t\tFilterPathOption: \"输入要过滤的路径\",\n\t\tEnterFileName: \"输入路径:\",\n\t\tFilteringMenuTitle: \"正在过滤\",\n\t\tMustExitFilterModeTitle: \"命令不可用\",\n\t\tMustExitFilterModePrompt: \"命令在过滤模式下不可用。退出过滤模式?\",\n\t\tDiff: \"差异\",\n\t\tEnterRefToDiff: \"输入 ref 以 diff\",\n\t\tEnterRefName: \"输入 ref:\",\n\t\tExitDiffMode: \"退出差异模式\",\n\t\tDiffingMenuTitle: \"正在 diff\",\n\t\tSwapDiff: \"反向 diff\",\n\t\tOpenDiffingMenu: \"打开 diff 菜单\",\n\t\t// 实际视图 (actual view) 是附加视图 (extras view),未来,我打算为附加视图提供更多选项卡,但现在,上面的文本只需要提及“命令日志”这个部分\n\t\tOpenExtrasMenu: \"打开命令日志菜单\",\n\t\tShowingGitDiff: \"显示输出:\",\n\t\tCopyCommitShaToClipboard: \"将提交的 SHA 复制到剪贴板\",\n\t\tCopyCommitMessageToClipboard: \"将提交消息复制到剪贴板\",\n\t\tCopyBranchNameToClipboard: \"将分支名称复制到剪贴板\",\n\t\tCopyFileNameToClipboard: \"将文件名复制到剪贴板\",\n\t\tCopyCommitFileNameToClipboard: \"将提交的文件名复制到剪贴板\",\n\t\tCopySelectedTexToClipboard: \"将选中文本复制到剪贴板\",\n\t\tCommitPrefixPatternError: \"提交前缀模式错误\",\n\t\tNoFilesStagedTitle: \"没有暂存文件\",\n\t\tNoFilesStagedPrompt: \"您尚未暂存任何文件。提交所有文件?\",\n\t\tBranchNotFoundTitle: \"找不到分支\",\n\t\tBranchNotFoundPrompt: \"找不到分支。创建一个新分支命名为:\",\n\t\tDiscardChangeTitle: \"取消暂存选中的行\",\n\t\tDiscardChangePrompt: \"您确定要删除所选的行(git reset)吗?这是不可逆的。\\n要禁用此对话框,请将 'gui.skipDiscardChangeWarning' 的配置键设置为 true\",\n\t\tCreateNewBranchFromCommit: \"从提交创建新分支\",\n\t\tBuildingPatch: \"正在构建补丁\",\n\t\tViewCommits: \"查看提交\",\n\t\tMinGitVersionError: \"Git 版本必须至少为 2.20(即从 2018 年开始的版本)。请更新 git。或者在 https://github.com/jesseduffield/lazygit/issues 上提出一个问题,以使 lazygit 更加向后兼容。\",\n\t\tRunningCustomCommandStatus: \"正在运行自定义命令\",\n\t\tSubmoduleStashAndReset: \"存放未提交的子模块更改和更新\",\n\t\tAndResetSubmodules: \"和重置子模块\",\n\t\tEnterSubmodule: \"输入子模块\",\n\t\tCopySubmoduleNameToClipboard: \"将子模块名称复制到剪贴板\",\n\t\tRemoveSubmodule: \"删除子模块\",\n\t\tRemoveSubmodulePrompt: \"您确定要删除子模块 '%s' 及其对应的目录吗?这是不可逆的。\",\n\t\tResettingSubmoduleStatus: \"正在重置子模块\",\n\t\tNewSubmoduleName: \"新的子模块名称:\",\n\t\tNewSubmoduleUrl: \"新的子模块 URL:\",\n\t\tNewSubmodulePath: \"新的子模块路径:\",\n\t\tAddSubmodule: \"添加新的子模块\",\n\t\tAddingSubmoduleStatus: \"添加子模块\",\n\t\tUpdateSubmoduleUrl: \"更新子模块 '%s' 的 URL\",\n\t\tUpdatingSubmoduleUrlStatus: \"更新 URL 中\",\n\t\tEditSubmoduleUrl: \"更新子模块 URL\",\n\t\tInitializingSubmoduleStatus: \"正在初始化子模块\",\n\t\tInitSubmodule: \"初始化子模块\",\n\t\tSubmoduleUpdate: \"更新子模块\",\n\t\tUpdatingSubmoduleStatus: \"正在更新子模块\",\n\t\tBulkInitSubmodules: \"批量初始化子模块\",\n\t\tBulkUpdateSubmodules: \"批量更新子模块\",\n\t\tBulkDeinitSubmodules: \"批量反初始化子模块\",\n\t\tViewBulkSubmoduleOptions: \"查看批量子模块选项\",\n\t\tBulkSubmoduleOptions: \"批量子模块选项\",\n\t\tRunningCommand: \"运行命令\",\n\t\tSubCommitsTitle: \"子提交\",\n\t\tSubmodulesTitle: \"子模块\",\n\t\tNavigationTitle: \"列表面板导航\",\n\t\tSuggestionsCheatsheetTitle: \"意见建议\",\n\t\tSuggestionsTitle: \"意见建议 (点击 %s 以聚焦)\",\n\t\tExtrasTitle: \"附加\",\n\t\tPushingTagStatus: \"推送标签\",\n\t\tPullRequestURLCopiedToClipboard: \"抓取请求网址已复制到剪贴板\",\n\t\tCommitMessageCopiedToClipboard: \"提交消息复制到剪贴板\",\n\t\tCopiedToClipboard: \"复制到剪贴板\",\n\t\tErrCannotEditDirectory: \"无法编辑目录:您只能编辑单个文件\",\n\t\tErrStageDirWithInlineMergeConflicts: \"无法 暂存/取消暂存 包含具有内联合并冲突的文件的目录。请先解决合并冲突\",\n\t\tErrRepositoryMovedOrDeleted: \"找不到仓库。它可能已被移动或删除 ¯\\\\_(ツ)_/¯\",\n\t\tCommandLog: \"命令日志\",\n\t\tToggleShowCommandLog: \"切换 显示/隐藏 命令日志\",\n\t\tFocusCommandLog: \"焦点命令日志\",\n\t\tCommandLogHeader: \"您可以通过按 '%s' 隐藏或集中显示该面板,或使用 `gui.showCommandLog: false`\\n将其永久隐藏在您的配置中\",\n\t\tRandomTip: \"随机小提示\",\n\t\tSelectParentCommitForMerge: \"选择父提交进行合并\",\n\t\tToggleWhitespaceInDiffView: \"切换是否在差异视图中显示空白字符差异\",\n\t\tIncreaseContextInDiffView: \"扩大差异视图中显示的上下文范围\",\n\t\tDecreaseContextInDiffView: \"缩小差异视图中显示的上下文范围\",\n\t\tCreatePullRequestOptions: \"创建抓取请求选项\",\n\t\tDefaultBranch: \"默认分支\",\n\t\tSelectBranch: \"选择分支\",\n\t\tSelectConfigFile: \"选择配置文件\",\n\t\tNoConfigFileFoundErr: \"找不到配置文件\",\n\t\tLoadingFileSuggestions: \"正在加载文件建议\",\n\t\tLoadingCommits: \"正在加载提交\",\n\t\tMustSpecifyOriginError: \"指定分支时,必须同时指定远程\",\n\t\tGitOutput: \"Git 输出:\",\n\t\tGitCommandFailed: \"Git 命令执行失败。查看命令日志了解详情 (使用 %s 打开)\",\n\t\tAbortTitle: \"放弃 %s\",\n\t\tAbortPrompt: \"您确定要放弃当前 %s 吗?\",\n\t\tOpenLogMenu: \"打开日志菜单\",\n\t\tLogMenuTitle: \"提交日志选项\",\n\t\tToggleShowGitGraphAll: \"切换显示完整 git 分支图 (向 `git log` 命令传入 `--all` 选项)\",\n\t\tShowGitGraph: \"显示 git 分支图\",\n\t\tSortCommits: \"提交排序\",\n\t\tCantChangeContextSizeError: \"无法在补丁构建模式下更改上下文,因为我们在发布该功能时懒得支持它。 如果你真的想要这么做,请告诉我们!\",\n\t\tOpenCommitInBrowser: \"在浏览器中打开提交\",\n\t\tViewBisectOptions: \"查看二分查找选项\",\n\t\tActions: Actions{\n\t\t\t// TODO: combine this with the original keybinding descriptions (those are all in lowercase atm)\n\t\t\tCheckoutCommit: \"检出提交\",\n\t\t\tCheckoutTag: \"检出标签\",\n\t\t\tCheckoutBranch: \"检出分支\",\n\t\t\tForceCheckoutBranch: \"强制检出分支\",\n\t\t\tMerge: \"合并\",\n\t\t\tRebaseBranch: \"变基分支\",\n\t\t\tRenameBranch: \"重命名分支\",\n\t\t\tCreateBranch: \"建立分支\",\n\t\t\tCherryPick: \"(拣选) 粘贴提交\",\n\t\t\tCheckoutFile: \"检出文件\",\n\t\t\tDiscardOldFileChange: \"放弃旧文件更改\",\n\t\t\tSquashCommitDown: \"向下压缩提交\",\n\t\t\tFixupCommit: \"修正提交\",\n\t\t\tRewordCommit: \"改写提交\",\n\t\t\tDropCommit: \"删除提交\",\n\t\t\tEditCommit: \"编辑提交\",\n\t\t\tAmendCommit: \"修改提交\",\n\t\t\tRevertCommit: \"还原提交\",\n\t\t\tCreateFixupCommit: \"创建修正提交\",\n\t\t\tSquashAllAboveFixupCommits: \"压缩以上所有的修正提交\",\n\t\t\tCreateLightweightTag: \"创建轻量标签\",\n\t\t\tCreateAnnotatedTag: \"创建附注标签\",\n\t\t\tCopyCommitMessageToClipboard: \"将提交消息复制到剪贴板\",\n\t\t\tMoveCommitUp: \"上移提交\",\n\t\t\tMoveCommitDown: \"下移提交\",\n\t\t\tCustomCommand: \"自定义命令\",\n\t\t\tDiscardAllChangesInDirectory: \"丢弃目录中的所有更改\",\n\t\t\tDiscardUnstagedChangesInDirectory: \"丢弃目录中未暂存的更改\",\n\t\t\tDiscardAllChangesInFile: \"丢弃文件中的所有更改\",\n\t\t\tDiscardAllUnstagedChangesInFile: \"丢弃文件中所有未暂存的更改\",\n\t\t\tStageFile: \"暂存文件\",\n\t\t\tUnstageFile: \"取消暂存文件\",\n\t\t\tUnstageAllFiles: \"取消暂存所有文件\",\n\t\t\tStageAllFiles: \"暂存所有文件\",\n\t\t\tIgnoreExcludeFile: \"忽略文件\",\n\t\t\tCommit: \"提交 (Commit)\",\n\t\t\tEditFile: \"编辑文件\",\n\t\t\tPush: \"推送 (Push)\",\n\t\t\tPull: \"拉取 (Pull)\",\n\t\t\tOpenFile: \"打开文件\",\n\t\t\tStashAllChanges: \"贮藏所有更改\",\n\t\t\tStashStagedChanges: \"贮藏暂存的更改\",\n\t\t\tGitFlowFinish: \"git flow 结果\",\n\t\t\tGitFlowStart: \"git flow 开始\",\n\t\t\tCopyToClipboard: \"复制到剪贴板\",\n\t\t\tCopySelectedTextToClipboard: \"将选中文本复制到剪贴板\",\n\t\t\tRemovePatchFromCommit: \"从提交中删除补丁\",\n\t\t\tMovePatchToSelectedCommit: \"将补丁移动到选定的提交\",\n\t\t\tMovePatchIntoIndex: \"将补丁移到索引\",\n\t\t\tMovePatchIntoNewCommit: \"将补丁移到新提交中\",\n\t\t\tDeleteRemoteBranch: \"删除远程分支\",\n\t\t\tSetBranchUpstream: \"设置分支上游\",\n\t\t\tAddRemote: \"添加远程\",\n\t\t\tRemoveRemote: \"移除远程\",\n\t\t\tUpdateRemote: \"更新远程\",\n\t\t\tApplyPatch: \"应用补丁\",\n\t\t\tStash: \"贮藏 (Stash)\",\n\t\t\tRenameStash: \"Rename stash\",\n\t\t\tRemoveSubmodule: \"删除子模块\",\n\t\t\tResetSubmodule: \"重置子模块\",\n\t\t\tAddSubmodule: \"添加子模块\",\n\t\t\tUpdateSubmoduleUrl: \"更新子模块 URL\",\n\t\t\tInitialiseSubmodule: \"初始化子模块\",\n\t\t\tBulkInitialiseSubmodules: \"批量初始化子模块\",\n\t\t\tBulkUpdateSubmodules: \"批量更新子模块\",\n\t\t\tBulkDeinitialiseSubmodules: \"批量取消初始化子模块\",\n\t\t\tUpdateSubmodule: \"更新子模块\",\n\t\t\tPushTag: \"推送标签\",\n\t\t\tNukeWorkingTree: \"Nuke 工作树\",\n\t\t\tDiscardUnstagedFileChanges: \"放弃未暂存的文件更改\",\n\t\t\tRemoveUntrackedFiles: \"删除未跟踪的文件\",\n\t\t\tSoftReset: \"软重置\",\n\t\t\tMixedReset: \"混合重置\",\n\t\t\tHardReset: \"硬重置\",\n\t\t\tFastForwardBranch: \"快进分支\",\n\t\t\tUndo: \"撤销\",\n\t\t\tRedo: \"重做\",\n\t\t\tCopyPullRequestURL: \"复制拉取请求 URL\",\n\t\t\tOpenMergeTool: \"打开合并工具\",\n\t\t\tOpenCommitInBrowser: \"在浏览器中打开提交\",\n\t\t\tOpenPullRequest: \"在浏览器中打开拉取请求\",\n\t\t\tStartBisect: \"开始二分查找 (Bisect)\",\n\t\t\tResetBisect: \"重置二分查找\",\n\t\t\tBisectSkip: \"二分查找跳过\",\n\t\t\tBisectMark: \"二分查找标记\",\n\t\t},\n\t\tBisect: Bisect{\n\t\t\tMark: \"将 %s 标记为 %s\",\n\t\t\tMarkStart: \"将 %s 标记为 %s (start bisect)\",\n\t\t\tSkipCurrent: \"跳过 %s\",\n\t\t\tResetTitle: \"重置 'git bisect'\",\n\t\t\tResetPrompt: \"您确定要重置 'git bisect' 吗?\",\n\t\t\tResetOption: \"重置二分查找\",\n\t\t\tBisectMenuTitle: \"二分查找\",\n\t\t\tCompleteTitle: \"二分查找完成\",\n\t\t\tCompletePrompt: \"二分查找完成!以下提交引入了此变更:\\n\\n%s\\n\\n您现在要重置 'git bisect' 吗?\",\n\t\t\tCompletePromptIndeterminate: \"二分查找完成!一些提交被跳过了,所以下列提交中的任何一个都可能引入了此变更:\\n\\n%s\\n\\n您现在要重置 'git bisect' 吗?\",\n\t\t},\n\t}\n}", "func ClientUpdate(c models.Client, m *models.Message) {\n\tif c.ID <= 0 {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"especifique cliente\"\n\t\treturn\n\t}\n\tdb := configuration.GetConnection()\n\tdefer db.Close()\n\ttx := db.Begin()\n\terr := updateClient(&c, tx)\n\tm.Code = http.StatusBadRequest\n\tm.Message = \"no se puedo actualizar\"\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tfor _, tel := range c.ClientTelDelete {\n\t\terr = deleteClientTel(&tel, tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, tel := range c.ClientTelNew {\n\t\terr = createClientTel(&tel, tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, tel := range c.ClientTel {\n\t\terr = updateClientTel(&tel, tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn\n\t\t}\n\t}\n\ttx.Commit()\n\tm.Code = http.StatusOK\n\tm.Message = \"se actualizo cliente\"\n\tm.Data = c\n}", "func loadTranslations(trPath string) error {\n\tfiles, _ := filepath.Glob(trPath + \"/*.json\")\n\n\tif len(files) == 0 {\n\t\treturn errors.New(\"no translations found\")\n\t}\n\n\tfor _, file := range files {\n\t\terr := loadFileToMap(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func updateClientLocation(cll *models.ClientListLocation, db *gorm.DB) error {\n\tomitList := []string{\"id\", \"cod_collection\", \"deleted_at\"}\n\terr := db.Model(cll).Omit(omitList...).Save(cll).Error\n\treturn err\n}", "func (this *Tidy) Language(val string) (bool, error) {\n\tv := (*C.tmbchar)(C.CString(val))\n\tdefer C.free(unsafe.Pointer(v))\n\treturn this.optSetString(C.TidyLanguage, v)\n}", "func UpdateVault(s SiteFile) (err error) {\n\tsi, err := GetSitesFile()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get pass dir: %s\", err.Error())\n\t}\n\tsiteFileContents, err := json.MarshalIndent(s, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not marshal site info: %s\", err.Error())\n\t}\n\n\t// Write the site with the newly appended site to the file.\n\terr = ioutil.WriteFile(si, siteFileContents, 0666)\n\treturn\n}", "func (_obj *Apilangpack) Langpack_getLanguage(params *TLlangpack_getLanguage, _opt ...map[string]string) (ret LangPackLanguage, 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, \"langpack_getLanguage\", _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 (m *User) SetPreferredLanguage(value *string)() {\n m.preferredLanguage = value\n}", "func (l *Library) update(r *Root, c *web.Client) error {\n\twfs, err := l.Library.Folders(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.updateObjects(l, &l.folders.objects, wfs, nil)\n}", "func SetLanguage(language string) {\n\tif _, ok := supportedTranslations[language]; ok {\n\t\tgotext.SetLanguage(language)\n\t\treturn\n\t}\n\tgotext.SetLanguage(defaultLanguage)\n}", "func ISO() {\n\tin, err := os.Open(*input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer in.Close()\n\tout, err := os.Create(\"iso639-3.go\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer out.Close()\n\tisoTemplate, err := template.New(\"iso\").\n\t\tParse(isoTemplate)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlanguages := make(chan []string, 8)\n\tgo func() {\n\t\treader := bufio.NewReader(in)\n\t\t_, err = reader.ReadString('\\n')\n\t\tfor err == nil {\n\t\t\tvar line string\n\t\t\tline, err = reader.ReadString('\\n')\n\t\t\tparts := strings.Split(line, \"\\t\")\n\t\t\tfor i, part := range parts {\n\t\t\t\tparts[i] = strings.TrimSpace(part)\n\t\t\t}\n\t\t\tswitch parts[4] {\n\t\t\tcase \"I\":\n\t\t\t\tparts[4] = \"LanguageScopeIndividual\"\n\t\t\tcase \"M\":\n\t\t\t\tparts[4] = \"LanguageScopeMacrolanguage\"\n\t\t\tcase \"S\":\n\t\t\t\tparts[4] = \"LanguageScopeSpecial\"\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"invalid scope %v\", parts))\n\t\t\t}\n\t\t\tswitch parts[5] {\n\t\t\tcase \"A\":\n\t\t\t\tparts[5] = \"LanguageTypeAncient\"\n\t\t\tcase \"C\":\n\t\t\t\tparts[5] = \"LanguageTypeConstructed\"\n\t\t\tcase \"E\":\n\t\t\t\tparts[5] = \"LanguageTypeExtinct\"\n\t\t\tcase \"H\":\n\t\t\t\tparts[5] = \"LanguageTypeHistorical\"\n\t\t\tcase \"L\":\n\t\t\t\tparts[5] = \"LanguageTypeLiving\"\n\t\t\tcase \"S\":\n\t\t\t\tparts[5] = \"LanguageTypeSpecial\"\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"invalid type %v\", parts))\n\t\t\t}\n\t\t\tlanguages <- parts\n\t\t}\n\t\tclose(languages)\n\t}()\n\terr = isoTemplate.Execute(out, languages)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t/*fmt.Fprintf(out, \"// Copyright 2018 The dbnary Authors. All rights reserved.\\n\")\n\tfmt.Fprintf(out, \"// Use of this source code is governed by a BSD-style\\n\")\n\tfmt.Fprintf(out, \"// license that can be found in the LICENSE file.\\n\\n\")\n\tfmt.Fprintf(out, \"// http://www.iso639-3.sil.org/\\n\\n\")\n\tfmt.Fprintf(out, \"package utils\\n\\n\")\n\tfmt.Fprintf(out, \"// Language is a language\\n\")\n\tfmt.Fprintf(out, \"type Language struct {\\n\")\n\tfmt.Fprintf(out, \"\\tID string\\n\")\n\tfmt.Fprintf(out, \"\\tPart2B string\\n\")\n\tfmt.Fprintf(out, \"\\tPart2T string\\n\")\n\tfmt.Fprintf(out, \"\\tPart1 string\\n\")\n\tfmt.Fprintf(out, \"\\tScope string\\n\")\n\tfmt.Fprintf(out, \"\\tType string\\n\")\n\tfmt.Fprintf(out, \"\\tName string\\n\")\n\tfmt.Fprintf(out, \"\\tComment string\\n\")\n\tfmt.Fprintf(out, \"}\\n\\n\")\n\tfmt.Fprintf(out, \"var Languages = map[string]Language{\\n\")\n\treader, seen := bufio.NewReader(in), make(map[string]bool)\n\t_, err = reader.ReadString('\\n')\n\tfor err == nil {\n\t\tvar line string\n\t\tline, err = reader.ReadString('\\n')\n\t\tparts := strings.Split(line, \"\\t\")\n\t\tif seen[parts[0]] {\n\t\t\tfmt.Printf(line)\n\t\t\tcontinue\n\t\t}\n\t\tfor i, part := range parts {\n\t\t\tparts[i] = strings.TrimSpace(part)\n\t\t}\n\t\tfmt.Fprintf(out, \"\\t\\\"%s\\\": {\\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\", \\\"%s\\\"},\\n\",\n\t\t\tparts[0], parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7])\n\t\tseen[parts[0]] = true\n\t}\n\tfmt.Fprintf(out, \"}\\n\")*/\n}", "func LocalUpdateFile(ctx context.Context, filePath string, contents string) error {\n\treturn platform.WriteFile(ctx, filePath, []byte(contents))\n}", "func InitLangDir() {\n\t_, err := os.Stat(\"./langsource/\")\n\n\tif os.IsNotExist(err) {\n\t\tfmt.Println(err) //Shows error if file not exists\n\t\t_, _ = git.PlainClone(\"./langsource/\", false, &git.CloneOptions{\n\t\t\tURL: \"https://github.com/WFCD/warframe-worldstate-data\",\n\t\t\tProgress: os.Stdout,\n\t\t})\n\t}\n\tif !os.IsNotExist(err) {\n\t\tfmt.Println(\"path exist\") // Shows success message like file is there\n\t\tr, _ := git.PlainOpen(\"./langsource\")\n\t\tw, _ := r.Worktree()\n\t\terr3 := w.Pull(&git.PullOptions{\n\t\t\tProgress: os.Stdout,\n\t\t\tForce: true,\n\t\t})\n\t\tfmt.Println(err3)\n\n\t}\n}", "func SetLanguage(chatId string, lang string) error {\n\tchat, err := GetChatWithId(chatId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttag, _ := language.MatchStrings(i18n.Matcher, lang)\n\tif tag.String() == lang { // if the language is supported, update the chat\n\t\tchat.Language = tag.String()\n\t\treturn updateChat(chat)\n\t}\n\n\treturn fmt.Errorf(\"unsupported language\")\n}", "func ClientSync(client RPCClient) {\n\tfiles, err := ioutil.ReadDir(client.BaseDir)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\tif _,err := os.Stat(client.BaseDir + \"/index.txt\"); os.IsNotExist(err) {\n\t\tf,_ := os.Create(client.BaseDir + \"/index.txt\")\n\t\tf.Close()\n\t}\n\n\t//Getting Local Index\n\tindex_file, err := os.Open(client.BaseDir + \"/index.txt\")\n\treader := bufio.NewReader(index_file)\n\ttemp_FileMetaMap := make(map[string]FileMetaData)\n\n\tfor{\n\t\tvar isPrefix bool\n\t\tvar line string\n\t\tvar l []byte\n\t\tfor {\n\t\t\tl,isPrefix,err = reader.ReadLine()\n\t\t//\tlog.Printf(string(l))\n\t\t\tline = line + string(l)\n\t\t\tif !isPrefix {\n\t\t\t\tbreak\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\tif line != \"\" {\n\t//\t\tlog.Print(line)\n\t\t\tvar new_File_Meta_Data FileMetaData\n\t\t\tnew_File_Meta_Data = handleIndex(string(line))\n\t\t\ttemp_FileMetaMap[new_File_Meta_Data.Filename] = new_File_Meta_Data\n\t\t}\n\t\tif err == io.EOF{\n\t\t\tbreak\n\t\t}\n\t}\n\tindex_file.Close()\n\t//Getting Remote Index\n\tremote_FileMetaMap := make(map[string]FileMetaData)\n\tvar success bool\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\tPrintMetaMap(remote_FileMetaMap)\n\t//Sorting Local Index\n\t//Client, files, \n\t//Handle Deleted Files\n\tHandle_Deleted_File(client, temp_FileMetaMap, files)\n\n\tLocal_Mod_FileMetaMap,Local_new_FileMetaMap,Local_No_Mod_FileMetaMap := CheckForNewChangedFile(client,files, temp_FileMetaMap)\n\tfor index,element := range Local_new_FileMetaMap {\n\t\t//Case 1 : new file was created locally that WAS NOT on the server\n\t//\tlog.Print(\"New File\")\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: new file was created locally but it WAS on the server\n\t\t\tif Local_new_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_new_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Update Remote File\n\t\t\t\tUpdateRemote(client, Local_new_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_No_Mod_FileMetaMap {\n\t//\tlog.Print(\"No Mod\")\n\t\t//Case 1 : if local no modification file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modification file WAS on the server\n\t//\t\tlog.Print(\"CLIENT - REMOTE VERSION : \", remote_FileMetaMap[index].Version)\n\t\t\tif Local_No_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_Mod_FileMetaMap {\n\t//\tlog.Print(\"Mod\")\n\t\t//Case 1 : if local modified file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t//\t\tlog.Print(\"NOT IN SERVER\")\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modified file WAS on the server\n\t//\t\tlog.Print(\"IN SERVER\")\n\t\t\tif Local_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t//\t\t\tlog.Print(\"SERVER VERSION IS HIGHER\")\n\t\t\t\t//Lost the race\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_Mod_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Check if file is the same.\n\t\t\t\t//Don't touch if it is\n\t\t\t\t//Update Remote File, version += 1\n\t//\t\t\tlog.Print(\"VERSION ARE EQUAL\")\n\t\t\t\tUpdateRemote(client, Local_Mod_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\t// Need to handle file that's in remote, but not in local.\n\t// Above accounts for all the updates, no changes and new file\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\n\tfor _,element := range remote_FileMetaMap {\n\t\tUpdateLocal(client, element)\n\t}\n\tPrintMetaMap(remote_FileMetaMap)\n\tUpdateIndex(client,remote_FileMetaMap)\n\t//Check for deleted files\n\treturn\n}", "func (m *Group) SetPreferredLanguage(value *string)() {\n m.preferredLanguage = value\n}", "func (dn *Daemon) updateFiles(oldIgnConfig, newIgnConfig ign3types.Config, skipCertificateWrite bool) error {\n\tklog.Info(\"Updating files\")\n\tif err := dn.writeFiles(newIgnConfig.Storage.Files, skipCertificateWrite); err != nil {\n\t\treturn err\n\t}\n\tif err := dn.writeUnits(newIgnConfig.Systemd.Units); err != nil {\n\t\treturn err\n\t}\n\treturn dn.deleteStaleData(oldIgnConfig, newIgnConfig)\n}", "func (d *Document) update(r *Root, c *web.Client) error {\n\treturn nil\n}" ]
[ "0.60816187", "0.58577764", "0.5845021", "0.5756729", "0.56602055", "0.56186885", "0.5585146", "0.54932135", "0.5451898", "0.54252183", "0.5391257", "0.5374925", "0.5353714", "0.52746046", "0.5268636", "0.5268636", "0.52674454", "0.5230201", "0.5176819", "0.5175852", "0.51708317", "0.51638675", "0.51620346", "0.5154838", "0.5150839", "0.5140208", "0.5124141", "0.51085407", "0.5097121", "0.5092712", "0.5088361", "0.5075227", "0.50666094", "0.50662357", "0.50637764", "0.505736", "0.5039215", "0.5020198", "0.5015209", "0.5003432", "0.50019145", "0.49963334", "0.49941266", "0.4992628", "0.49865913", "0.49864808", "0.49849835", "0.497156", "0.49578157", "0.493712", "0.49174684", "0.4910993", "0.4893134", "0.488073", "0.48753858", "0.4849038", "0.48427963", "0.4830471", "0.47861525", "0.47838753", "0.4777703", "0.47693992", "0.4752222", "0.47425076", "0.47408843", "0.47403336", "0.47339788", "0.47330365", "0.47230554", "0.4703226", "0.46928453", "0.46882346", "0.46874976", "0.46775162", "0.46753266", "0.46676642", "0.46560898", "0.46528515", "0.46504134", "0.46482596", "0.4634752", "0.46270037", "0.4625386", "0.46121585", "0.46035117", "0.4597549", "0.45941767", "0.45926774", "0.45895037", "0.45867145", "0.4586438", "0.45817947", "0.45763898", "0.45748222", "0.45550948", "0.45536694", "0.454021", "0.45343024", "0.45159417", "0.4509009" ]
0.7256982
0
two different Dials, updateListener dial is constantly listing from srv updates
func client(){ // Connect to the server through tcp/IP. connection, err := net.Dial("tcp", ("127.0.0.1" + ":" + "9090")) updateListener , listErr := net.Dial("tcp", ("127.0.0.1" + ":" + "9091")) // If connection failed crash. check(err) check(listErr) //Create separate thread for updating client. go update(updateListener) //Configure the language. validateLang() //Time to log in to the account. loginSetUp(connection) //handling requests from usr handlingRequests(connection) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Watcher) dial() (watcher *mpd.Watcher, err error) {\n for {\n if watcher, err = mpd.NewWatcher(\"tcp\", w.addr, w.passwd); err == nil {\n return\n }\n\n select {\n case <-w.done:\n return\n case <-time.After(time.Second):\n // retry\n }\n }\n}", "func startListenerAdvertisements(i *app.Indicator) {\n\ti.Listen(client.ChanAdvNew, i.AgentCtrl().AdvCache().NotifyChannels[client.ChanAdvNew], func(objName string, args ...interface{}) {\n\t\tctrl := i.AgentCtrl()\n\t\tif !ctrl.Mocked() {\n\t\t\tadvStore := ctrl.AdvCache().Store\n\t\t\t_, exist, err := advStore.GetByKey(objName)\n\t\t\tif err != nil {\n\t\t\t\ti.NotifyNoConnection()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !exist {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ti.NotifyNewAdv(objName)\n\t})\n\ti.Listen(client.ChanAdvAccepted, i.AgentCtrl().AdvCache().NotifyChannels[client.ChanAdvAccepted], func(objName string, args ...interface{}) {\n\t\tctrl := i.AgentCtrl()\n\t\tif !ctrl.Mocked() {\n\t\t\tadvStore := ctrl.AdvCache().Store\n\t\t\t_, exist, err := advStore.GetByKey(objName)\n\t\t\tif err != nil {\n\t\t\t\ti.NotifyNoConnection()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !exist {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ti.NotifyAcceptedAdv(objName)\n\t\ti.Status().IncConsumePeerings()\n\t})\n\ti.Listen(client.ChanAdvRevoked, i.AgentCtrl().AdvCache().NotifyChannels[client.ChanAdvRevoked], func(objName string, args ...interface{}) {\n\t\tctrl := i.AgentCtrl()\n\t\tif !ctrl.Mocked() {\n\t\t\tadvStore := ctrl.AdvCache().Store\n\t\t\t_, exist, err := advStore.GetByKey(objName)\n\t\t\tif err != nil {\n\t\t\t\ti.NotifyNoConnection()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !exist {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ti.NotifyRevokedAdv(objName)\n\t\ti.Status().DecConsumePeerings()\n\t})\n\ti.Listen(client.ChanAdvDeleted, i.AgentCtrl().AdvCache().NotifyChannels[client.ChanAdvDeleted], func(objName string, args ...interface{}) {\n\t\ti.NotifyDeletedAdv(objName)\n\t\ti.Status().DecConsumePeerings()\n\t})\n}", "func (s *Server) updater(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\t// Same as handleConnections\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"Exit call updater...\")\n\n\t\t\treturn\n\t\tcase <-s.ticker.C:\n\t\t\tif err := s.updateClients(s.getTimer()); err == nil {\n\t\t\t\ts.notifyClients()\n\t\t\t} else {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (pl *Mpris2) Listen() {\n\tc := make(chan *dbus.Signal, 10)\n\tpl.conn.BusObject().Call(\"org.freedesktop.DBus.AddMatch\", 0, MATCH_NOC)\n\tpl.conn.BusObject().Call(\"org.freedesktop.DBus.AddMatch\", 0, MATCH_PC)\n\tpl.conn.Signal(c)\n\tfor v := range c {\n\t\tif strings.Contains(v.Name, \"NameOwnerChanged\") {\n\t\t\tswitch name := v.Body[0].(type) {\n\t\t\tcase string:\n\t\t\t\tvar pid uint32\n\t\t\t\tpl.conn.BusObject().Call(\"org.freedesktop.DBus.GetConnectionUnixProcessID\", 0, name).Store(&pid)\n\t\t\t\t// Ignore playerctld\n\t\t\t\tif strings.Contains(name, \"playerctld\") {\n\t\t\t\t\t// Store UID so we know to ignore it later\n\t\t\t\t\tpl.playerctldUID = v.Sender\n\t\t\t\t} else if strings.Contains(name, INTERFACE) {\n\t\t\t\t\tif pid == 0 {\n\t\t\t\t\t\tpl.Remove(name)\n\t\t\t\t\t\tpl.Messages <- Message{Name: \"remove\", Value: name}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpl.New(name)\n\t\t\t\t\t\tpl.Messages <- Message{Name: \"add\", Value: name}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if strings.Contains(v.Name, \"PropertiesChanged\") && strings.Contains(v.Body[0].(string), INTERFACE+\".Player\") && v.Sender != pl.playerctldUID {\n\t\t\tpl.Refresh()\n\t\t}\n\t}\n}", "func listen(ch chan client.Notify) {\n\tfor notify := range ch {\n\t\tif notify.PingRequest != nil {\n\t\t\tfmt.Printf(\"Ping Request %v\\n\", notify.PingRequest)\n\t\t}\n\t}\n}", "func Dial(ctx context.Context, addr string, opts ...Option) (*Client, error) {\n\tctx, task := trace.NewTask(ctx, \"Dial\")\n\tdefer task.End()\n\tvar o options\n\to.pingPeriod = 60 * time.Second\n\to.pongWait = 10 * o.pingPeriod / 9\n\tfor _, f := range opts {\n\t\tf(&o)\n\t}\n\tdialer := websocket.Dialer{\n\t\tNetDialContext: o.dial,\n\t\tTLSClientConfig: o.tls,\n\t\tEnableCompression: true,\n\t}\n\tws, _, err := dialer.DialContext(ctx, addr, o.header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\taddr: addr,\n\t\tws: ws,\n\t\tpongWait: o.pongWait,\n\t\tpingPeriod: o.pingPeriod,\n\t\tnotify: o.notify,\n\t\tcalls: make(map[uint32]*call),\n\t\tsend: make(chan *request),\n\t\terrc: make(chan struct{}),\n\t}\n\tvar pingTicker *time.Ticker\n\tif o.pingPeriod != 0 {\n\t\tws.SetPongHandler(func(string) error {\n\t\t\tdefer trace.StartRegion(ctx, \"PongHandler\").End()\n\t\t\ttrace.Logf(ctx, \"\", \"received pong\")\n\t\t\tif c.pongWait != 0 {\n\t\t\t\treadDeadline := time.Now().Add(c.pongWait)\n\t\t\t\ttrace.Logf(ctx, \"\", \"setting new read deadline %v\", readDeadline)\n\t\t\t\tws.SetReadDeadline(readDeadline)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\t// Initial read deadline must be set for the first ping message\n\t\t// sent pingPeriod from now.\n\t\tif c.pongWait != 0 {\n\t\t\treadDeadline := time.Now().Add(c.pingPeriod + c.pongWait)\n\t\t\ttrace.Logf(ctx, \"\", \"setting first read deadline %v\", readDeadline)\n\t\t\tws.SetReadDeadline(readDeadline)\n\t\t}\n\t\tpingTicker = time.NewTicker(c.pingPeriod)\n\t}\n\tgo c.in(ctx)\n\tgo c.out(ctx, pingTicker)\n\treturn c, nil\n}", "func (s *Server) LiveUpdates(stream pb.TRISADemo_LiveUpdatesServer) (err error) {\n\tvar (\n\t\tclient string\n\t\tmessages uint64\n\t)\n\n\tctx := stream.Context()\n\n\tfor {\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tvar req *pb.Command\n\t\tif req, err = stream.Recv(); err != nil {\n\t\t\t// The stream was closed on the client side\n\t\t\tif err == io.EOF {\n\t\t\t\tif client == \"\" {\n\t\t\t\t\tlog.Warn().Msg(\"live updates connection closed before first message\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Warn().Str(\"client\", client).Msg(\"live updates connection closed\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Some other error occurred\n\t\t\tlog.Error().Err(err).Str(\"client\", client).Msg(\"connection dropped\")\n\t\t\treturn nil\n\t\t}\n\n\t\t// If this is the first time we've seen the client, log it\n\t\tif client == \"\" {\n\t\t\tclient = req.Client\n\t\t\tif err = s.updates.Add(client, stream); err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"could not create client updater\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Info().Str(\"client\", client).Msg(\"connected to live updates\")\n\t\t\tdefer s.updates.Del(client)\n\n\t\t} else if client != req.Client {\n\t\t\tlog.Warn().Str(\"request from\", req.Client).Str(\"client stream\", client).Msg(\"unexpected client\")\n\t\t\ts.updates.Del(client)\n\t\t\treturn fmt.Errorf(\"unexpected client %q (connected as %q)\", req.Client, client)\n\t\t}\n\n\t\t// Handle the message\n\t\tmessages++\n\t\tlog.Info().\n\t\t\tUint64(\"message\", messages).\n\t\t\tStr(\"type\", req.Type.String()).\n\t\t\tMsg(\"received message\")\n\n\t\tswitch req.Type {\n\t\tcase pb.RPC_NORPC:\n\t\t\t// Send back an acknowledgement message\n\t\t\tack := &pb.Message{\n\t\t\t\tType: pb.RPC_NORPC,\n\t\t\t\tId: req.Id,\n\t\t\t\tUpdate: fmt.Sprintf(\"command %d acknowledged\", req.Id),\n\t\t\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\t\t}\n\t\t\tif err = s.updates.Send(client, ack); err != nil {\n\t\t\t\tlog.Error().Err(err).Str(\"client\", client).Msg(\"could not send message\")\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase pb.RPC_ACCOUNT:\n\t\t\tvar rep *pb.AccountReply\n\t\t\tif rep, err = s.AccountStatus(context.Background(), req.GetAccount()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tack := &pb.Message{\n\t\t\t\tType: pb.RPC_ACCOUNT,\n\t\t\t\tId: req.Id,\n\t\t\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\t\t\tReply: &pb.Message_Account{Account: rep},\n\t\t\t}\n\n\t\t\tif err = s.updates.Send(client, ack); err != nil {\n\t\t\t\tlog.Error().Err(err).Str(\"client\", client).Msg(\"could not send message\")\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase pb.RPC_TRANSFER:\n\t\t\tif err = s.handleTransaction(client, req); err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"could not handle transaction\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Conn) epUpdate(ctx context.Context) {\n\tvar lastEndpoints []string\n\tvar lastCancel func()\n\tvar lastDone chan struct{}\n\n\tvar regularUpdate <-chan time.Time\n\tif !version.IsMobile() {\n\t\t// We assume that LinkChange notifications are plumbed through well\n\t\t// on our mobile clients, so don't do the timer thing to save radio/battery/CPU/etc.\n\t\tticker := time.NewTicker(28 * time.Second) // just under 30s, a likely UDP NAT timeout\n\t\tdefer ticker.Stop()\n\t\tregularUpdate = ticker.C\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif lastCancel != nil {\n\t\t\t\tlastCancel()\n\t\t\t}\n\t\t\treturn\n\t\tcase <-c.startEpUpdate:\n\t\tcase <-regularUpdate:\n\t\t}\n\n\t\tif lastCancel != nil {\n\t\t\tlastCancel()\n\t\t\t<-lastDone\n\t\t}\n\t\tvar epCtx context.Context\n\t\tepCtx, lastCancel = context.WithCancel(ctx)\n\t\tlastDone = make(chan struct{})\n\n\t\tgo func() {\n\t\t\tdefer close(lastDone)\n\n\t\t\tc.updateNetInfo() // best effort\n\t\t\tc.cleanStaleDerp()\n\n\t\t\tendpoints, err := c.determineEndpoints(epCtx)\n\t\t\tif err != nil {\n\t\t\t\tc.logf(\"magicsock.Conn: endpoint update failed: %v\", err)\n\t\t\t\t// TODO(crawshaw): are there any conditions under which\n\t\t\t\t// we should trigger a retry based on the error here?\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif stringsEqual(endpoints, lastEndpoints) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlastEndpoints = endpoints\n\t\t\t// TODO(bradfiz): get nearestDerp back to ipn for a HostInfo update\n\t\t\tc.epFunc(endpoints)\n\t\t}()\n\t}\n}", "func (c *Reader) poll() {\n\tlog.Info(\"Polling\")\n\n\t// Lookup \"active\" clients\n\t// @NOTE(mannkind) Clients remain \"active\" long after they disconnect\n\tclients, err := c.service.lookup()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Fatal(\"Unable to find clients\")\n\t\treturn\n\t}\n\n\t// Set the Last Seen value for clients we care about\n\t// @NOTE(mannkind) It appears that we cannot trust client.LastSeen (anymore?)\n\tfor _, client := range *clients {\n\t\t// Skip clients that we don't care about\n\t\tslug, ok := c.opts.Devices[client.Mac]\n\t\tif !ok {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"mac\": client.Mac,\n\t\t\t}).Debug(\"The device is not known nor cared about\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Make up our own Last Seen value\n\t\tc.deviceAwayTime[slug] = time.Now()\n\t}\n\n\t// Determine the status of clients we care about\n\tfor _, slug := range c.opts.Devices {\n\t\tpayload := notHome\n\t\tlastSeen, _ := c.deviceAwayTime[slug]\n\t\tif time.Now().Sub(lastSeen) < c.opts.AwayTimeout {\n\t\t\tpayload = home\n\t\t}\n\n\t\tc.outgoing <- c.adapt(slug, payload)\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"sleep\": c.opts.LookupInterval,\n\t}).Info(\"Finished polling; sleeping\")\n}", "func DialS(iPort int,cbR cbRead,cbD cbDiscon)(bool,string){\n if iPort <= 0 {\n return false,\"server port is invalued!!\"\n }\n if nil == cbR || nil == cbD{\n return false ,\"server callback func is nil!!\"\n }\n l,err := net.Listen(\"tcp\",fmt.Sprintf(\"%s:%d\",\"127.0.0.1\",iPort))\n if nil != err{\n L.W(fmt.Sprintf(\"start listen:port[%d],err:%s\",iPort,err),L.Level_Error)\n return false,\"start listen err!!\"\n }\n go handleAccp(cbR,cbD,l,iPort)\n return true,\"\"\n}", "func (c *Client) update(rsp *Response) {\n\tif rsp.Label == \"CAPABILITY\" {\n\t\tc.setCaps(rsp.Fields[1:])\n\t\treturn\n\t}\n\tswitch rsp.Type {\n\tcase Data:\n\t\tif c.Mailbox == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch rsp.Label {\n\t\tcase \"FLAGS\":\n\t\t\tc.Mailbox.Flags.Replace(rsp.Fields[1])\n\t\tcase \"EXISTS\":\n\t\t\tc.Mailbox.Messages = rsp.Value()\n\t\tcase \"RECENT\":\n\t\t\tc.Mailbox.Recent = rsp.Value()\n\t\tcase \"EXPUNGE\":\n\t\t\tc.Mailbox.Messages--\n\t\t\tif c.Mailbox.Recent > c.Mailbox.Messages {\n\t\t\t\tc.Mailbox.Recent = c.Mailbox.Messages\n\t\t\t}\n\t\t\tif c.Mailbox.Unseen == rsp.Value() {\n\t\t\t\tc.Mailbox.Unseen = 0\n\t\t\t}\n\t\t}\n\tcase Status:\n\t\tswitch rsp.Status {\n\t\tcase BAD:\n\t\t\t// RFC 3501 is a bit vague on how the client is expected to react to\n\t\t\t// an untagged BAD response. It's probably best to close this\n\t\t\t// connection and open a new one; leave this up to the caller. For\n\t\t\t// now, abort all active commands to avoid waiting for completion\n\t\t\t// responses that may never come.\n\t\t\tc.Logln(LogCmd, \"ABORT!\", rsp.Info)\n\t\t\tc.deliver(abort)\n\t\tcase BYE:\n\t\t\tc.Logln(LogConn, \"Logout reason:\", rsp.Info)\n\t\t\tc.setState(Logout)\n\t\t}\n\t\tfallthrough\n\tcase Done:\n\t\tif rsp.Label == \"ALERT\" {\n\t\t\tc.Logln(LogConn, \"ALERT!\", rsp.Info)\n\t\t\treturn\n\t\t} else if c.Mailbox == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch selected := (c.state == Selected); rsp.Label {\n\t\tcase \"PERMANENTFLAGS\":\n\t\t\tc.Mailbox.PermFlags.Replace(rsp.Fields[1])\n\t\tcase \"READ-ONLY\":\n\t\t\tif selected && !c.Mailbox.ReadOnly {\n\t\t\t\tc.Logln(LogState, \"Mailbox access change: RW -> RO\")\n\t\t\t}\n\t\t\tc.Mailbox.ReadOnly = true\n\t\tcase \"READ-WRITE\":\n\t\t\tif selected && c.Mailbox.ReadOnly {\n\t\t\t\tc.Logln(LogState, \"Mailbox access change: RO -> RW\")\n\t\t\t}\n\t\t\tc.Mailbox.ReadOnly = false\n\t\tcase \"UIDNEXT\":\n\t\t\tc.Mailbox.UIDNext = rsp.Value()\n\t\tcase \"UIDVALIDITY\":\n\t\t\tv := rsp.Value()\n\t\t\tif u := c.Mailbox.UIDValidity; selected && u != v {\n\t\t\t\tc.Logf(LogState, \"Mailbox UIDVALIDITY change: %d -> %d\", u, v)\n\t\t\t}\n\t\t\tc.Mailbox.UIDValidity = v\n\t\tcase \"UNSEEN\":\n\t\t\tc.Mailbox.Unseen = rsp.Value()\n\t\tcase \"UIDNOTSTICKY\":\n\t\t\tc.Mailbox.UIDNotSticky = true\n\t\t}\n\t}\n}", "func (cust *custInfo) getBalance(ReqId string){\n cAddr, err3 := net.ResolveUDPAddr(\"udp\",\":0\")\n /* I have to update the server config and read the value by looping */\n\n fmt.Println(\"tail Address, myQuery\",tailAddress,myQueryAddress)\n sAddr, err4 := net.ResolveUDPAddr(\"udp\", tailAddress)\n if(err3!=nil || err4!=nil){\n log.Fatal(\"Connection error\",err4)\n }\n connToTail, err := net.DialUDP(\"udp\",cAddr,sAddr)\n logMessage(\"Status\",\"Connecting to the tail\")\n if(err!=nil){\n log.Fatal(\"Connection error\",err)\n }\n // notifyMe(connToTail)\n param := Params{ReqId,cust.accountNumber,\"query\"}\n fmt.Println(\"Params in client\",param)\n b,err1 := json.Marshal(param)\n if(err1 != nil){\n fmt.Println(\"Error\")\n }\n connToTail.Write(b)\n go receiveMsgFromTail(connToTail,\"Query\")\n // connToTail.Close()\n}", "func GetOffers(stopchan chan struct{}) bool {\n\tutil.Info.Println(\"GetOffers started\")\n\tl := len(linkBridges.unconnected)\n\tgetOffers := make(chan dynamic.DHTGetReturn, l)\n\tfor _, link := range linkBridges.unconnected {\n\t\tif link.State == StateNew || link.State == StateWaitForAnswer {\n\t\t\tvar linkBridge = NewLinkBridge(link.LinkAccount, link.MyAccount, accounts)\n\t\t\tdynamicd.GetLinkRecord(linkBridge.LinkAccount, linkBridge.MyAccount, getOffers)\n\t\t\tutil.Info.Println(\"GetOffer for\", link.LinkAccount)\n\t\t} else {\n\t\t\tutil.Info.Println(\"GetOffers skipped\", link.LinkAccount)\n\t\t\tl--\n\t\t}\n\t}\n\tfor i := 0; i < l; i++ {\n\t\tselect {\n\t\tdefault:\n\t\t\toffer := <-getOffers\n\t\t\tlinkBridge := NewLinkBridge(offer.Sender, offer.Receiver, accounts)\n\t\t\tlink := linkBridges.unconnected[linkBridge.LinkID()]\n\t\t\tif link.Get.GetValue != offer.GetValue {\n\t\t\t\tif offer.GetSeq > link.Get.GetSeq {\n\t\t\t\t\tlink.Get = offer.DHTGetJSON\n\t\t\t\t\tif link.Get.NullRecord == \"true\" {\n\t\t\t\t\t\tutil.Info.Println(\"GetOffers null\", offer.Sender, offer.Receiver)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif link.Get.Minutes() <= OfferExpireMinutes && link.Get.GetValueSize > MinimumOfferValueLength {\n\t\t\t\t\t\tpc, err := ConnectToIceServices(config)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\terr = util.DecodeObject(offer.GetValue, &link.Offer)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tutil.Info.Println(\"GetOffers error with DecodeObject\", link.LinkAccount, link.LinkID(), err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlink.PeerConnection = pc\n\t\t\t\t\t\t\tlink.State = StateSendAnswer\n\t\t\t\t\t\t\tutil.Info.Println(\"GetOffers: Offer found for\", link.LinkAccount, link.LinkID())\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if link.Get.Minutes() > OfferExpireMinutes && link.Get.GetValueSize > MinimumOfferValueLength {\n\t\t\t\t\t\tutil.Info.Println(\"GetOffers: Stale offer found for\", link.LinkAccount, link.LinkID(), \"minutes\", link.Get.Minutes())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-stopchan:\n\t\t\tutil.Info.Println(\"GetOffers stopped\")\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *collector) update(addr string, message proto.Message) {\n\tresp, ok := message.(*openconfig.SubscribeResponse)\n\tif !ok {\n\t\tglog.Errorf(\"Unexpected type of message: %T\", message)\n\t\treturn\n\t}\n\tnotif := resp.GetUpdate()\n\tif notif == nil {\n\t\treturn\n\t}\n\n\tdevice := strings.Split(addr, \":\")[0]\n\tprefix := \"/\" + strings.Join(notif.Prefix.Element, \"/\")\n\n\t// Process deletes first\n\tfor _, del := range notif.Delete {\n\t\tpath := prefix + \"/\" + strings.Join(del.Element, \"/\")\n\t\tkey := source{addr: device, path: path}\n\t\tc.m.Lock()\n\t\tdelete(c.metrics, key)\n\t\tc.m.Unlock()\n\t}\n\n\t// Process updates next\n\tfor _, update := range notif.Update {\n\t\t// We only use JSON encoded values\n\t\tif update.Value == nil || update.Value.Type != openconfig.Type_JSON {\n\t\t\tglog.V(9).Infof(\"Ignoring incompatible update value in %s\", update)\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := prefix + \"/\" + strings.Join(update.Path.Element, \"/\")\n\t\tvalue, suffix, ok := parseValue(update)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif suffix != \"\" {\n\t\t\tpath += \"/\" + suffix\n\t\t}\n\t\tsrc := source{addr: device, path: path}\n\t\tc.m.Lock()\n\t\t// Use the cached labels and descriptor if available\n\t\tif m, ok := c.metrics[src]; ok {\n\t\t\tm.metric = prometheus.MustNewConstMetric(m.metric.Desc(), prometheus.GaugeValue, value,\n\t\t\t\tm.labels...)\n\t\t\tc.m.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\tc.m.Unlock()\n\n\t\t// Get the descriptor and labels for this source\n\t\tdesc, labelValues := c.config.getDescAndLabels(src)\n\t\tif desc == nil {\n\t\t\tglog.V(8).Infof(\"Ignoring unmatched update at %s:%s: %+v\", device, path, update.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m.Lock()\n\t\t// Save the metric and labels in the cache\n\t\tmetric := prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, value, labelValues...)\n\t\tc.metrics[src] = &labelledMetric{\n\t\t\tmetric: metric,\n\t\t\tlabels: labelValues,\n\t\t}\n\t\tc.m.Unlock()\n\t}\n}", "func listen2dial(listen, dial string) {\n\tclient := make(chan net.Conn)\n\tgo ListenTCP(listen, client)\n\n\tfor {\n\t\tlistenConn := <-client\n\t\tdialConn, err := connect(dial)\n\t\tif err != nil {\n\t\t\tlistenConn.Close()\n\t\t\tFail2Connect(dial)\n\t\t}\n\t\tgo link(listenConn, dialConn)\n\t}\n}", "func dial2dial(dial1, dial2 string) {\n\tfor {\n\t\tdial1Conn, err := connect(dial1)\n\t\tif err != nil {\n\t\t\tFail2Connect(dial1)\n\t\t}\n\n\t\t// Read request from dst\n\t\tbuf := make([]byte, maxBytes)\n\t\tn, err := dial1Conn.Read(buf)\n\t\tif err != nil {\n\t\t\tFail2Read(dial1)\n\t\t}\n\n\t\tdial2Conn, err := connect(dial2)\n\t\tif err != nil {\n\t\t\tFail2Connect(dial2)\n\t\t}\n\n\t\t_, err = dial2Conn.Write(buf[:n])\n\t\tif err != nil {\n\t\t\tFail2Write(dial2)\n\t\t}\n\n\t\tgo link(dial1Conn, dial2Conn)\n\t}\n}", "func (s *StreamService) StreamCall(srv pb.Control_StreamCallServer) error {\n var driverId int32\n var seq int32\n if name, err := srv.Recv(); err != nil {\n fmt.Printf(\"Recv From Driver err: %v\", err)\n return err\n } else {\n fmt.Printf(\"Driver driverId[%v] login\", name.DriverId)\n driverId = name.DriverId\n seq = name.Seq\n }\n\n if fmtinStatus[driverId] == true {\n fmt.Printf(\"Driver driverId[%v] AlReady login\", driverId)\n return status.Errorf(codes.AlreadyExists, \"AlReady fmtin!\")\n }\n\n fmtinStatus[driverId] = true\n defer func(){fmtinStatus[driverId] = false}()\n\n for {\n var val string\n select {\n case val = <- chans[driverId].ch:\n fmt.Printf(\"Driver driverId[%v] Get Action [%s]!\", driverId, val)\n case <-time.After(3 * time.Second):\n fmt.Printf(\"Driver driverId[%v] Timeout And Continue!\", driverId)\n err := srv.Send(&pb.Response{\n DriverId: driverId,\n Seq: seq,\n Ping: \"PING\",\n })\n \n if err != nil {\n fmt.Printf(\"Clinet err: %v\", err)\n return err\n }\n\n continue\n }\n\n err := srv.Send(&pb.Response{\n DriverId: driverId,\n Seq: seq,\n Data: \"Driver Do Action: \" + val ,\n })\n\n if err != nil {\n fmt.Printf(\"Clinet err: %v\", err)\n return err\n }\n\n res, err := srv.Recv()\n if err != nil {\n fmt.Printf(\"Recv From Clinet err: %v\", err)\n return err\n }\n\n if seq != res.Seq {\n fmt.Printf(\"Seq %d != %d \", seq, res.Seq)\n }\n\n seq++\n fmt.Printf(\"Recv From Driver: %v\", res)\n }\n}", "func (lc *LuMiGatewayClient) gainAndParse(s *net.UDPConn) {\n\tfor {\n\t\td := make([]byte, 1024)\n\t\tread, _, err := s.ReadFromUDP(d)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"read from udp failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar resp lumiResponse\n\t\tif err := json.Unmarshal(d[:read], &resp); err != nil {\n\t\t\tfmt.Printf(\"unmarshal response failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch resp.Command {\n\t\tcase lumiCommandResponseGetIDListAck:\n\t\t\t{\n\t\t\t\tvar sids []string\n\t\t\t\tif err := json.Unmarshal([]byte(resp.Data), &sids); err != nil {\n\t\t\t\t\tfmt.Printf(\"unmarshal get id list faield: %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlc.token = resp.Token\n\t\t\t\tlc.idlist = sids\n\n\t\t\t\tlc.bgetidlist <- true\n\t\t\t}\n\t\tcase lumiCommandResponseHeartbeat:\n\t\t\t{\n\t\t\t\tlc.token = resp.Token\n\t\t\t}\n\t\tcase lumiCommandResponseReport:\n\t\t\t{\n\t\t\t\t// TODO push data to upper server\n\t\t\t\t// fmt.Printf(\"report: %s\\n\", d[:read])\n\t\t\t}\n\t\tcase lumiCommandResponseReadAck:\n\t\t\t{\n\t\t\t\tvar d lumiData\n\t\t\t\tif err := json.Unmarshal([]byte(resp.Data), &d); err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// cache sid\n\t\t\t\tids, ok := lc.devices[resp.Model]\n\t\t\t\tif !ok {\n\t\t\t\t\tlc.devices[resp.Model] = append(lc.devices[resp.Model], resp.SID)\n\t\t\t\t} else {\n\t\t\t\t\texist := false\n\t\t\t\t\tfor _, id := range ids {\n\t\t\t\t\t\tif id == resp.SID {\n\t\t\t\t\t\t\texist = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlc.devices[resp.Model] = append(lc.devices[resp.Model], resp.SID)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// cache data\n\t\t\t\td.ShortID = int(resp.ShortID.(float64))\n\t\t\t\tlc.data[resp.SID] = d\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Printf(\"response: %s\\n\", d[:read])\n\t\t}\n\n\t}\n}", "func Listener(s *Services) {\n\tvar message Message\n\tfor {\n\t\tmessage = <-s.MQ\n\t\tresp, err := client.Get(message.URL)\n\t\tif err != nil {\n\t\t\tresp = &http.Response{\n\t\t\t\tStatusCode: 503,\n\t\t\t}\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\ts.Stats[message.index].Lock.Lock()\n\t\ts.Stats[message.index].Status = resp.StatusCode\n\t\ts.Stats[message.index].StatusHistory = append(s.Stats[message.index].StatusHistory, ServiceStatus{Status: resp.StatusCode, Time: time.Now()})\n\t\tif len(s.Stats[message.index].StatusHistory) > 6 {\n\t\t\ts.Stats[message.index].StatusHistory = s.Stats[message.index].StatusHistory[1:]\n\t\t}\n\t\ts.Stats[message.index].Lock.Unlock()\n\t}\n}", "func (d *delegate) NotifyUpdate(n *memberlist.Node) {\n\tlevel.Debug(d.logger).Log(\"received\", \"NotifyUpdate\", \"node\", n.Name, \"addr\", fmt.Sprintf(\"%s:%d\", n.Addr, n.Port))\n}", "func DevsHandler(res chan<- RpcRequest, minerInfo *MinerInformation, c *Client, wg *sync.WaitGroup) {\n\t//Signal that the thread is started\n\twg.Done()\n\n\t//Now do this forever and ever!\n\tfor {\n\t\t//If it return false it has failed to connect\n\t\t//So wait abit more before next time\n\t\tif UpdateDevs(c.Name, true) == false {\n\t\t\tlog.Println(\"Failed to fetch new data from: \" + c.Name)\n\t\t\t//No response so wait somee extra before try again\n\t\t\ttime.Sleep(time.Duration(c.RefreshInterval*2) * time.Second)\n\t\t}\n\n\t\t//Now sleep\n\t\ttime.Sleep(time.Duration(c.RefreshInterval) * time.Second)\n\t}\n}", "func (s storeServer) Dial(upspin.Config, upspin.Endpoint) (upspin.Service, error) { return s, nil }", "func (s *StreamService) Call(srv pb.Control_CallServer) error {\n var driverId int32\n var cmd string\n if name, err := srv.Recv(); err != nil {\n fmt.Printf(\"Recv From Driver err: %v\", err)\n return err\n } else {\n fmt.Printf(\"Driver driverId[%v] Client login\", name.DriverId)\n driverId = name.DriverId\n cmd = name.Cmd\n }\n \n if fmtinStatus[driverId] == false {\n fmt.Printf(\"Driver[%d] Not Ready!\", driverId)\n //err := srv.Send(&pb.Result{\n // DriverId: driverId,\n // Data: \"driver not ready: \" + cmd,\n //})\n return status.Errorf(codes.AlreadyExists, \"Driver Not Ready!\")\n //return errors.New(\"Driver Not Ready!\")\n }\n \n select {\n case <-chans[driverId].mux:\n fmt.Println(\"Receive Get Lock\")\n default:\n err := srv.Send(&pb.Result{\n DriverId: driverId,\n Data: \"busy: \" + cmd,\n })\n return err\n }\n defer func(){ \n chans[driverId].mux <- struct{}{}\n fmt.Println(\"Receive Release Lock\") \n }()\n \n for {\n var driverId int32\n var cmd string\n if name, err := srv.Recv(); err != nil {\n fmt.Printf(\"Recv From Driver err: %v\", err)\n return err\n } else {\n fmt.Printf(\"Driver driverId[%v] cmd\", name.DriverId)\n driverId = name.DriverId\n cmd = name.Cmd\n }\n\n for _, v := range cmdlist[cmd] {\n select {\n case chans[driverId].ch <- v:\n // fmt.Printf(\"Send %s\", v)\n case <-time.After(5 * time.Second):\n fmt.Println(\"Send Timeout!\")\n err := srv.Send(&pb.Result{\n DriverId: driverId,\n Data: \"Call Driver Timeout: \" + cmd,\n })\n return err\n }\n }\n \n srv.Send(&pb.Result{\n DriverId: driverId,\n Data: \"finish: \" + cmd,\n })\n }\n}", "func (t *tui) listen() {\n\tfor {\n\t\tres := <-t.listener\n\t\tswitch res.Name {\n\t\tcase \"fg\", \">\", \"<\", \"[\", \"]\":\n\t\t\t// Switch to active view or error if not found.\n\t\t\tif err := t.switchConn(res.Payload[0], res.Payload[1]); err != nil {\n\t\t\t\tlog.Warningf(\"error switching connections: %v\", err)\n\t\t\t}\n\t\tcase \"connect\", \"c\":\n\t\t\t// Maybe create receivedView here á là TF's trying to connect\n\t\t\t// screen? Maybe not.\n\t\t\tcontinue\n\t\tcase \"disconnect\", \"dc\":\n\t\t\t// If it's a disconnect without a payload, redispatch with the\n\t\t\t// current connection's name.\n\t\t\tif (len(res.Payload) == 1 && res.Payload[0] != \"-r\") || len(res.Payload) != 0 || t.currView == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres.Payload = append(res.Payload, t.currView.connName)\n\t\t\tlog.Tracef(\"disconnecting current world %+v\", res)\n\t\t\tgo t.client.Env.DirectDispatch(res)\n\t\tcase \"help\":\n\t\t\t// get the command text and tell the system to display it in a modal\n\t\t\tvar cmd string\n\t\t\tif len(res.Payload) == 0 {\n\t\t\t\tcmd = \"help\"\n\t\t\t} else {\n\t\t\t\tcmd = res.Payload[0]\n\t\t\t}\n\t\t\th, ok := help.HelpMessages[cmd]\n\t\t\tif !ok {\n\t\t\t\tlog.Warningf(\"no help available for /%s\", cmd)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thelpText := help.RenderText(h)\n\t\t\tgo t.client.Env.Dispatch(\"_client:showModal\", fmt.Sprintf(\"Help: %s::\\n%s\", cmd, helpText))\n\t\tcase \"_client:connect\":\n\t\t\t// Attach receivedView to conn.\n\t\t\terr := t.connect(res.Payload[0], t.g)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error setting up connection in ui: %v\", err)\n\t\t\t}\n\t\tcase \"_client:disconnect\":\n\t\t\t// Grey out tab in send title, grey out text in receivedView.\n\t\t\tt.updateSendTitle()\n\t\tcase \"_client:disconnected\":\n\t\t\t// Grey out tab in send title, grey out text in receivedView.\n\t\t\tt.updateSendTitle()\n\t\tcase \"_client:allDisconnect\":\n\t\t\t// do we really need to do anything?\n\t\t\tt.updateSendTitle()\n\t\tcase \"_client:quitReady\":\n\t\t\tgo t.g.Update(func(g *gotui.Gui) error {\n\t\t\t\treturn gotui.ErrQuit\n\t\t\t})\n\t\tcase \"_client:showModal\":\n\t\t\tres.Name = \"_tui:showModal\"\n\t\t\tgo t.client.Env.DirectDispatch(res)\n\t\tcase \"_tui:showModal\":\n\t\t\tt.createModal(res.Payload[0], res.Payload[1])\n\t\tcase \"_client:removeWorld\", \"remove\", \"r\":\n\t\t\tif len(res.Payload) != 1 {\n\t\t\t\tlog.Warningf(\"tried to remove a world without an argument\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tworld := res.Payload[0]\n\t\t\tif err := t.removeWorld(world); err != nil {\n\t\t\t\tlog.Errorf(\"unable to remove world %s: %v\", res.Payload[0], err)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Tracef(\"got unknown signal result %v\", res)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (m *HTTPService) Dial() error {\n\tif m.cert != nil {\n\t\t// return http.ListenAndServe(m.GetPath(), http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\t// \tm.Route.IssueRequestPath(r.URL.Path, func(pack *grids.GridPacket) {\n\t\t// \t\tpack.Set(\"Req\", r)\n\t\t// \t\tpack.Set(\"Res\", rw)\n\t\t// \t\tCollectHTTPBody(r, pack)\n\t\t// \t})\n\t\t// }))\n\t\treturn http.ListenAndServe(m.GetPath(), http.HandlerFunc(m.ProcessPackets))\n\t}\n\treturn http.ListenAndServeTLS(m.GetPath(), m.cert.Cert, m.cert.Key, http.HandlerFunc(m.ProcessPackets))\n}", "func (u Updates) ListenAndServe() {\n\tu.bot.logger.Info(fmt.Sprintf(\"[Router] [ListenAndServe] Hi, I am %s\", u.bot.bot.Self.String()))\n\tfor update := range u.ch {\n\t\tupdate := update\n\t\tgo func() {\n\t\t\tif update.CallbackQuery != nil {\n\t\t\t\tcallback.Handler(u.bot.bot, update, u.bot.logger, u.bot.svc, u.bot.adminChatID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif update.Message == nil || update.Message.Text == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif cmd := update.Message.Command(); cmd != \"\" {\n\t\t\t\tswitch cmd {\n\t\t\t\tcase \"start\", \"hello\":\n\t\t\t\t\thello.Handler(u.bot.bot, update, u.bot.logger)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery.Handler(u.bot.bot, update, u.bot.logger, u.bot.svc, u.bot.adminChatID)\n\t\t}()\n\t}\n}", "func (w *deviceWrapper) pullUpdate() {\n\tw.Ctor.Logger.Debug(\"Fetching update for the device\", common.LogDeviceTypeToken,\n\t\tw.Ctor.DeviceType.String(), common.LogDeviceNameToken, w.ID)\n\tswitch w.Ctor.DeviceType {\n\tcase enums.DevHub:\n\t\tw.pullHubUpdate()\n\tdefault:\n\t\tw.pullDeviceUpdate()\n\t}\n}", "func main() {\n\tflag.Parse()\n\n\t/////\n\taliveTimer = time.Now()\n\n\tlginfo.Init()\n\n\t// parse server ip need valid\n\tserverIp := net.ParseIP(server);\n\tserverAdd := net.UDPAddr{\n\t\tIP: serverIp,\n\t\tPort: 38302,\n\t}\n\n\t// 本机地址\n\thostIp := net.ParseIP(host)\n\thostAdd := net.UDPAddr{\n\t\tIP: hostIp,\n\t\tPort: 38300,\n\t}\n\t// Can卡固定IP\n\tcanAddr := net.UDPAddr{\n\t\tIP: net.IPv4(192, 168, 1, 10),\n\t\tPort: 8002,\n\t}\n\tlg, err := net.DialUDP(\"udp\", nil, &serverAdd)\n\ttool.CheckError(err)\n\tcan, err := net.DialUDP(\"udp\", &hostAdd, &canAddr)\n\ttool.CheckError(err)\n\n\tdefer lg.Close()\n\tdefer can.Close()\n\n\t//\n\tgo rpc.KeepAlive(lg)\n\tgo timeOutHandler();\n\tgo writeToVehicle(can)\n\t//go read(can)\n\n\tbuf := make([]byte, 12)\n\tfor {\n\t\t_, err := lg.Read(buf)\n\t\tif err != nil {\n\t\t\tfmt.Print(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// 读取 状态\n\t\tlginfo.ReadDriver(buf)\n\t\taliveTimer = time.Now()\n\t\t// 反馈状态\n\t\tlg.Write(lginfo.Pong(1))\n\t}\n\n}", "func (cm *clientManager) requestListener() {\n\tfor {\n\t\tselect {\n\t\tcase clReq := <-cm.newClient:\n\t\t\tch, err := cm.handleClientRequest(clReq)\n\t\t\tgo clReq.sendResponse(ch, err)\n\t\tcase host := <-cm.closeHandle:\n\t\t\tcl := cm.clients[host]\n\t\t\tcl.numOpenHandles--\n\t\t\tif cl.numOpenHandles == 0 {\n\t\t\t\tclose(cl.queries)\n\t\t\t\tdelete(cm.clients, host)\n\t\t\t}\n\t\tcase <-cm.exit:\n\t\t\t// Shutdown the clntMngr, this is just for testing\n\t\t\t// purposes to avoid a data race\n\t\t\treturn\n\t\t}\n\t}\n}", "func requestListener() {\n\tfor {\n\t\tconnId, payLoad, err := lspServer.Read()\n\t\tif err != nil {\n\t\t\tlogger.Println(\"Failure handler with clientId\", connId)\n\t\t\tfailureHandler(connId)\n\t\t} else {\n\t\t\tincomingMsgHanler(connId, payLoad)\n\t\t}\n\t}\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 updateConInfo(iId int,iPort int,szHost string,conn net.Conn,cbD cbDiscon,bServer,bAdd bool) bool{\n if nil == conn || nil == cbD || iId < 0 || iPort < 0{\n return false\n }\n if bAdd{\n m.Lock()\n defer m.Unlock()\n _,ok := mConInfo[iId]\n if !ok{\n arg := stConnInfo{ szHost, iPort, bServer,conn,cbD}\n mConInfo[iId] = arg\n }else{\n return false\n }\n }else{\n closeCon(iId)\n }\n return true\n}", "func getUpdatesResponse(addr string, url string, padL string, padR string) (header string, result api.Response, err error) {\n\tvar client http.Client\n\tvar connType string\n\tlog.Debugf(\"[updates] request URL: %s\", url)\n\tif strings.HasPrefix(addr, \"/\") {\n\t\tconnType = \"unix\"\n\t\tlog.Debugf(\"[updates] unix connection to %s\", addr)\n\t} else {\n\t\tconnType = \"tcp\"\n\t\tlog.Debugf(\"[updates] tcp connection to %s\", addr)\n\t}\n\tclient = http.Client{\n\t\tTimeout: 1 * time.Second,\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(connType, addr)\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\terr = &ModuleNotAvailable{\"updates\", err}\n\t\theader = fmt.Sprintf(\"%s: %s\\n\", utils.Wrap(\"Updates\", padL, padR), utils.Warn(\"unavailable\"))\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\terr = &ModuleNotAvailable{\"updates\", err}\n\t\theader = fmt.Sprintf(\"%s: %s (%v)\\n\", utils.Wrap(\"Updates\", padL, padR), utils.Warn(\"Cannot decode response\"), err)\n\t\treturn\n\t}\n\tlog.Debugf(\"[updates] response:\\n%s\", utils.PrettyPrint(&result))\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\terr = &ModuleNotAvailable{\"updates\", fmt.Errorf(\"invalid response code %s\", resp.Status)}\n\t\theader = fmt.Sprintf(\"%s: %s (%s)\\n\", utils.Wrap(\"Updates\", padL, padR), utils.Warn(\"Invalid response\"), resp.Status)\n\t\treturn\n\t}\n\treturn\n}", "func (s *storeServer) Dial(upspin.Config, upspin.Endpoint) (upspin.Service, error) { return s, nil }", "func (c *client) clientInfoRequests() {\n\tfor {\n\t\tselect {\n\t\tcase <-c.getServerSN:\n\t\t\tc.serverSeqNumRes <- c.serverSN\n\t\t\tc.serverSN++\n\t\tcase <-c.getClientSN:\n\t\t\tc.clientSeqNumRes <- c.currSN\n\t\t\tc.currSN++\n\t\tcase <-c.dataStorage.closed:\n\t\t\treturn\n\t\tcase <-c.closeInfoReq:\n\t\t\t// return when finished closing\n\t\t\treturn\n\t\tcase <-c.ticker.C:\n\t\t\tif !c.wroteInEpoch {\n\t\t\t\t//send heartbeat\n\t\t\t\tackMsg := NewAck(c.clientID, 0)\n\t\t\t\tbyteMsg, _ := json.Marshal(&ackMsg)\n\t\t\t\tc.conn.Write(byteMsg)\n\t\t\t\tc.wroteInEpoch = false\n\t\t\t}\n\n\t\t\tif !c.readInEpoch {\n\t\t\t\t// increment the number of epochs in which we haven't heard anything\n\t\t\t\tc.unreadEpochs++\n\t\t\t\tif c.unreadEpochs == c.epochLimit {\n\t\t\t\t\t// if hit epoch limit, we have lost the client\n\t\t\t\t\tclose(c.lostCxn)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.readInEpoch = false\n\t\t\t\tc.unreadEpochs = 0\n\t\t\t}\n\n\t\tcase <-c.writtenChan:\n\t\t\tc.wroteInEpoch = true\n\t\tcase <-c.readChan:\n\t\t\tc.readInEpoch = true\n\t\t}\n\t}\n}", "func Notify(id int) {\n\tresp := \".\\n\"\n\tresp += \"**\" + Config.Feeds[id].Feed.Title + \": **\" + \"\\n\"\n\tresp += Config.Feeds[id].Feed.Items[0].Date.String() + \"\\n\\n\"\n\t// If a 9front feed, extract the user ☺\n\tif strings.Contains(Config.Feeds[id].Feed.Items[0].Link, \"http://code.9front.org/hg/\") {\n\t\tlines := strings.Split(Config.Feeds[id].Feed.Items[0].Summary, \"\\n\")\n\t\tfor i, v := range lines {\n\t\t\tif strings.Contains(v, \"<th style=\\\"text-align:left;vertical-align:top;\\\">user</th>\") {\n\t\t\t\tline := html.UnescapeString((lines[i+1])[6:len(lines[i+1])-5])\n\t\t\t\tresp += line + \"\\n\\n\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tresp += \"`\" + Config.Feeds[id].Feed.Items[0].Title + \"`\" + \"\\n\"\n\tresp += \"\\n\" + Config.Feeds[id].Feed.Items[0].Link + \"\\n\"\n\tConfig.Feeds[id].Feed.Items[0].Read = true\n\tresp += \"\\n\"\n\t\n\t// Loop through subbed chans and post notification message\n\tfmt.Println(\"Looping through subs to notify...\")\n\tfor _, v := range Config.Subs {\n\t\tif v.SubID == id {\n\t\t\tSession.ChannelMessageSend(v.ChanID, resp)\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfmt.Println(\"No new notifys for \", Config.Feeds[id].Feed.UpdateURL)\n\t\n\t/* Enable for logging if subs break\n\tfmt.Println(Config.Feeds[id].Feed.Items[0])\n\tfmt.Println(Config.Feeds[id].Feed.Items[len(Config.Feeds[id].Feed.Items)-1])\n\t*/\n}", "func handleHealthCheck(m *MicroService, d *net.Dialer) bool {\r\n\tchange := false\r\n\tfor i, inst := range m.Instances {\r\n\t\t_, err := d.Dial(\"tcp\", inst.Host)\r\n\t\tif err != nil {\r\n\t\t\tif !m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, true)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as DOWN\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, false)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as UP\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn change\r\n}", "func UpdateDevs(name string, checkTresHold bool) (ok bool) {\n\tok = false\n\trequest := RpcRequest{\"{\\\"command\\\":\\\"devs\\\"}\", make(chan []byte), name}\n\n\tminerInfo := miners[name]\n\n\tvar devs DevsResponse\n\n\t//Ignore the error at the moment since it not implement in the Send() yet\n\tresponse, _ := request.Send()\n\n\t//Parse the data into a DevsResponse\n\tdevs.Parse(response)\n\n\t//If we got data back\n\tif len(response) != 0 {\n\t\t//Set ok to true\n\t\tok = true\n\t\t//Should we do a treshold check?\n\t\tif checkTresHold == true {\n\t\t\t//Need to sum up the mhs5s to get the current total hashrate for the miner\n\t\t\tmhs5s := 0.0\n\t\t\tfor i := 0; i < len(devs.Devs); i++ {\n\t\t\t\tvar dev = &devs.Devs[i]\n\t\t\t\tmhs5s += dev.MHS5s\n\t\t\t}\n\t\t\tCheckMhsThresHold(mhs5s, devs.Status[0].When, minerInfo.Client)\n\t\t\t//If the threshold is checked then do a alive check as well\n\t\t\tCheckAliveStatus(devs, name)\n\t\t}\n\t}\n\n\t//Lock it\n\tminerInfo.DevsWrap.Mu.Lock()\n\t//Save the summary\n\tminerInfo.DevsWrap.Devs = devs\n\t//Now unlock\n\tminerInfo.DevsWrap.Mu.Unlock()\n\n\treturn\n}", "func (p *PrivateEndpointConnectionsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func getUpdatesAPI(c *ConfUpdates) (header string, content string, err error) {\n\tvar r api.Response\n\treqURL := \"http://con/api?updates\"\n\tif c.Every != \"\" {\n\t\treqURL += fmt.Sprintf(\"&refresh&immediate&every=%s\", c.Every)\n\t}\n\theader, r, err = getUpdatesResponse(c.Address, reqURL, c.padL, c.padR)\n\tif err != nil {\n\t\treturn\n\t}\n\tif r.Error != \"\" {\n\t\tlog.Warnf(\"[updates] response contains error %s\", r.Error)\n\t\tcontent = fmt.Sprintf(\"%s\\n\", utils.Warn(r.Error))\n\t}\n\tif r.Queued != nil && *r.Queued == true {\n\t\tif r.Data == nil {\n\t\t\theader = fmt.Sprintf(\"%s: No data, refreshing\\n\", utils.Wrap(\"Updates\", c.padL, c.padR))\n\t\t} else {\n\t\t\theader = fmt.Sprintf(\"%s: %d pending, refreshing\\n\", utils.Wrap(\"Updates\", c.padL, c.padR), len(r.Data.Updates))\n\t\t}\n\t} else {\n\t\tif r.Data == nil {\n\t\t\theader = fmt.Sprintf(\"%s: No data\\n\", utils.Wrap(\"Updates\", c.padL, c.padR))\n\t\t\treturn\n\t\t}\n\t\tt, err := time.Parse(time.RFC3339, r.Data.Checked)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"[updates] cannot parse timestamp %s: %v\", r.Data.Checked, err)\n\t\t\theader = fmt.Sprintf(\"%s: %d pending, cannot parse timestamp\\n\", utils.Wrap(\"Updates\", c.padL, c.padR), len(r.Data.Updates))\n\t\t}\n\t\tvar timeElapsed = time.Since(t)\n\t\theader = fmt.Sprintf(\"%s: %d pending, checked %s ago\\n\",\n\t\t\tutils.Wrap(\"Updates\", c.padL, c.padR), len(r.Data.Updates), timeStr(timeElapsed, 2, c.ShortNames))\n\t}\n\tif r.Data == nil || c.Show == nil || *c.Show == false {\n\t\treturn\n\t}\n\tcontent += fmt.Sprint(utils.Wrap(r.Data.String(), c.padL, c.padR))\n\treturn\n}", "func (mgr *l3Manager) listen() {\n\tfor {\n\n\t\tselect {\n\t\tcase noti, ok := <-mgr.vswch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif vif, ok := noti.Target.(*vswitch.VifInfo); ok {\n\t\t\t\tvrfrd := vif.Vrf().VrfRD()\n\t\t\t\tl3mod := mgr.vrfs[vrfrd]\n\t\t\t\tif l3mod == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch value := noti.Value.(type) {\n\t\t\t\tcase nil:\n\t\t\t\t\t// TODO: delete VIF, delete interface info.\n\n\t\t\t\tcase net.HardwareAddr:\n\t\t\t\t\t// TODO: update mac address of self interface.\n\t\t\t\t\tif noti.Type == notifier.Update {\n\t\t\t\t\t}\n\t\t\t\tcase vswitch.IPAddr:\n\t\t\t\t\tif noti.Type == notifier.Add {\n\t\t\t\t\t\t// TODO: add ip address of self interface.\n\t\t\t\t\t} else if noti.Type == notifier.Update {\n\t\t\t\t\t\t// TODO: update ip address of self interface.\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// TODO: delete ip address of self interface.\n\t\t\t\t\t}\n\t\t\t\tcase vswitch.Neighbour:\n\t\t\t\t\tae := ArpEntry{\n\t\t\t\t\t\tVrfRd: vrfrd,\n\t\t\t\t\t\tInterface: uint32(vif.VifIndex()),\n\t\t\t\t\t\tIpAddress: value.Dst,\n\t\t\t\t\t\tMacAddress: value.LinkLocalAddr,\n\t\t\t\t\t}\n\t\t\t\t\tupdateArpEntry(l3mod, noti.Type, ae)\n\t\t\t\tcase vswitch.LinkStatus:\n\t\t\t\t\t// nothing to do.\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Printf(\"L3MGR(%s): Unexpected value: %v\\n\", l3mod.Name(), vif)\n\t\t\t\t}\n\n\t\t\t} else if vrf, ok := noti.Target.(*vswitch.VrfInfo); ok {\n\t\t\t\tvrfrd := vrf.VrfRD()\n\t\t\t\tl3mod := mgr.vrfs[vrfrd]\n\t\t\t\tif l3mod == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch vif := noti.Value.(type) {\n\t\t\t\tcase nil:\n\t\t\t\t\t// TODO: VRF created, nothing to do.\n\n\t\t\t\tcase vswitch.Route:\n\t\t\t\t\tones, _ := vif.Dst.Mask.Size()\n\t\t\t\t\tif vif.Dst.IP.To4() == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tre := RouteEntry{\n\t\t\t\t\t\tVrfRd: vrfrd,\n\t\t\t\t\t\tBridgeId: uint32(vif.VifIndex), // TODO\n\t\t\t\t\t\tPrefix: uint32(ones),\n\t\t\t\t\t\tDestAddr: vif.Dst.IP,\n\t\t\t\t\t\tNextHop: vif.Gw,\n\t\t\t\t\t\tInterface: uint32(vif.VifIndex),\n\t\t\t\t\t\tScope: uint32(vif.Scope),\n\t\t\t\t\t\tMetric: uint32(vif.Metrics),\n\t\t\t\t\t}\n\t\t\t\t\tupdateRouteEntry(l3mod, noti.Type, re)\n\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Printf(\"L3MGR(%s): not supported vif: vif = %v\",\n\t\t\t\t\t\tl3mod.Name(), vif)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"L3MGR: not supported target: %v\\n\", noti.Target)\n\t\t\t}\n\t\tdefault:\n\t\t\t// not supported.\n\t\t}\n\t}\n}", "func (TelegramBotApp *TelegramBotApp) getUpdates() (tgbotapi.UpdatesChannel, error) {\n\t// Select between pooling and webhook (heroku works only with webhook)\n\tif TelegramBotApp.conf.UseWebhook != true {\n\t\treturn TelegramBotApp.setupPolling()\n\t}\n\treturn TelegramBotApp.setupWebhook()\n}", "func DAHDIDialOffhook(client Client, actionID, channel, number string) (Response, error) {\n\treturn send(client, \"DAHDIDialOffhook\", actionID, map[string]string{\n\t\t\"DAHDIChannel\": channel,\n\t\t\"Number\": number,\n\t})\n}", "func (s *Server) Listen(system server.System) error {\n\ts.instruments.Log(octo.LOGINFO, s.info.UUID, \"udp.Server.Listen\", \"Started : %#v\", s.Attr)\n\n\tif s.IsRunning() {\n\t\ts.instruments.Log(octo.LOGINFO, s.info.UUID, \"udp.Server.Listen\", \"Completed\")\n\t\treturn nil\n\t}\n\n\tvar version string\n\n\tswitch s.Attr.Version {\n\tcase Ver0:\n\t\tversion = \"udp\"\n\tcase Ver4:\n\t\tversion = \"udp4\"\n\tcase Ver6:\n\t\tversion = \"udp6\"\n\t}\n\n\tudpAddr, err := net.ResolveUDPAddr(version, s.Attr.Addr)\n\tif err != nil {\n\t\ts.instruments.Log(octo.LOGERROR, s.info.UUID, \"udp.Server.Listen\", \"Completed : Error : %s\", err.Error())\n\t\treturn err\n\t}\n\n\ts.ip = udpAddr\n\n\tvar conn *net.UDPConn\n\n\tif s.Attr.MulticastInterface != nil {\n\t\tconn, err = net.ListenMulticastUDP(version, s.Attr.MulticastInterface, s.ip)\n\t} else {\n\t\tconn, err = net.ListenUDP(version, s.ip)\n\t}\n\n\tif err != nil {\n\t\ts.instruments.Log(octo.LOGERROR, s.info.UUID, \"udp.Server.Listen\", \"Completed : Error : %s\", err.Error())\n\t\treturn err\n\t}\n\n\ts.conn = conn\n\ts.auth = system\n\ts.base = jsoni.NewSxConversations(system, jsoniserver.CloseServer{}, jsoniserver.ContactServer{}, jsoniserver.ConversationServer{}, &jsoniserver.AuthServer{\n\t\tCredentials: s,\n\t})\n\n\t// Set the server state as active.\n\ts.rl.Lock()\n\t{\n\t\ts.running = true\n\t\ts.doClose = false\n\t}\n\ts.rl.Unlock()\n\n\ts.wg.Add(1)\n\n\tgo s.handleConnections(system)\n\n\ts.instruments.Log(octo.LOGINFO, s.info.UUID, \"udp.Server.Listen\", \"Completed\")\n\treturn nil\n}", "func Listener() {\n\tfor {\n\t\tfor p, _ := range Config.Feeds {\n\t\t\t//fmt.Print(\"Updating feed: \", Config.Feeds[p].Feed.Title, \"\\n\")\n\t\t\t// maybe only do at init step?\n\t\t\tstr := Config.Feeds[p].Feed.UpdateURL\n\t\t\tfeed, err := rss.Fetch(str)\n\t\t\tif feed != nil {\n\t\t\t\tConfig.Feeds[p].Feed = *feed\n\t\t\t} else {\n\t\t\t\t//fmt.Println(\"Got a nil pointer for feed in commits for \", str, \" as \", err)\n\t\t\t}\n\t\t\t//err := Config.Feeds[p].Feed.Update()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error in updating RSS feed, see: x/mux/commits.go\")\n\t\t\t\tfmt.Printf(\"%s\\n\\n\", err)\n\t\t\t} else {\n\t\t\t\tadditem := true\n\t\t\t\tfor j, _ := range Config.Feeds[p].Recent {\n\t\t\t\t\tif Config.Feeds[p].Recent[j] == Config.Feeds[p].Feed.Items[0].Title {\n\t\t\t\t\t\t//fmt.Println(\"Checking Recent \", j, \" against \", Config.Feeds[p].Feed.Items[0].Title)\n\t\t\t\t\t\tadditem = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif additem {\n\t\t\t\t\t// x y z → x y z 0 → y z 0\n\t\t\t\t\tfmt.Println(\"Updating: \", Config.Feeds[p].Feed.Title)\n\t\t\t\t\tConfig.Feeds[p].Recent = append(Config.Feeds[p].Recent, Config.Feeds[p].Feed.Items[0].Title)\n\t\t\t\t\tConfig.Feeds[p].Recent = Config.Feeds[p].Recent[1:]\n\t\t\t\t\tNotify(p)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(2 * time.Minute)\n\t\t}\n\t\ttime.Sleep(10 * time.Minute)\n\t\t// Dump config to file regularly\n\t\t//fmt.Println(\"\", dump())\n\t}\n}", "func (p PollingListener) ListenAndServe(handler Handler) {\n\tpollingURL := \"https://\" + path.Join(\"api.telegram.org/\", \"bot\"+p.Token, \"getUpdates\")\n\tpollingURL += \"?timeout=\" + strconv.Itoa(p.Timeout)\n\tvar offset = -1\nmainLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-p.s:\n\t\t\tbreak mainLoop\n\t\tdefault:\n\t\t\tif resp, err := p.Client.Get(pollingURL + \"&offset=\" + strconv.Itoa(offset)); err == nil {\n\t\t\t\tvar result getResult\n\t\t\t\terr = json.NewDecoder(resp.Body).Decode(&result)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !result.OK {\n\t\t\t\t\tlog.Println(\"Result not OK\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor _, u := range result.Result {\n\t\t\t\t\toffset = u.UpdateID + 1\n\t\t\t\t\tgo handler.Handle(p.r, &u)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func Update(s *discordgo.Session, m *discordgo.MessageCreate) {\n\tif *R == false {\n\t\ts.ChannelMessageSend(support.Config.FactorioChannelID, \"Server is not running!\")\n\t\treturn\n\t}\n\n\ts.ChannelMessageSend(support.Config.FactorioChannelID, \"Server received factorio client update command.\")\n\t*QuitFlag = 1\n\tio.WriteString(*P, \"/quit\\n\")\n\ttime.Sleep(600 * time.Millisecond)\n\tfor {\n\t\tif *QuitFlag == 2 {\n\t\t\ts.ChannelMessageSend(support.Config.FactorioChannelID, \"server is closed.\")\n\t\t\t*QuitFlag = 0\n\t\t\tbreak\n\t\t}\n\t}\n\n\t*R = false\n\tUpdateCmd = 1\n\n\treturn\n}", "func (client *SyncClient) RequestUpdates(alsoSubscribe bool) error {\n\treturn cCall(func() C.obx_err {\n\t\treturn C.obx_sync_updates_request(client.cClient, C.bool(alsoSubscribe))\n\t})\n}", "func (p *BindingsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (p *DiscoveryProtocol) onNotify() {\n\tlog.Println(\" pending requests: \", p.pendingReq)\n\tfor req := range p.pendingReq {\n\t\tif !p.requestExpired(req) {\n\t\t\tlog.Println(\"Request not expired, trying to send response\")\n\t\t\tif p.createSendResponse(req) {\n\t\t\t\tdelete(p.pendingReq, req)\n\t\t\t}\n\t\t}\n\t}\n}", "func updServer() {\n\t// starts a udp listener (connection) on port \"udpPort\"\n\t// remember connections are resources and need to be closed (aka 'freed') if opened ;)\n\t// use a \"for loop\" to continuously \"handle\" incoming messages (i.e use \"handleMessage\")\n\t// if there's an error when starting server, log.Fatal ;)\n}", "func (n *GNode) Dial(la, ra *GspAddr, w ConnHandler) (*GspConn, error) {\n\treturn n.addFilter(la, ra, w)\n}", "func DAHDIDialOffhook(ctx context.Context, client Client, actionID, channel, number string) (Response, error) {\n\treturn send(ctx, client, \"DAHDIDialOffhook\", actionID, map[string]string{\n\t\t\"DAHDIChannel\": channel,\n\t\t\"Number\": number,\n\t})\n}", "func GetAllOffers(stopchan chan struct{}, links dynamic.ActiveLinks, accounts []dynamic.Account) bool {\n\tgetOffers := make(chan dynamic.DHTGetReturn, len(links.Links))\n\tfor _, link := range links.Links {\n\t\tvar linkBridge = NewBridge(link, accounts)\n\t\tdynamicd.GetLinkRecord(linkBridge.LinkAccount, linkBridge.MyAccount, getOffers)\n\t}\n\tutil.Info.Println(\"GetAllOffers started\")\n\tfor i := 0; i < len(links.Links); i++ {\n\t\tselect {\n\t\tdefault:\n\t\t\toffer := <-getOffers\n\t\t\tlinkBridge := NewLinkBridge(offer.Sender, offer.Receiver, accounts)\n\t\t\tlinkBridge.Get = offer.DHTGetJSON\n\t\t\tlinkBridge.SessionID = i\n\t\t\tif offer.DHTGetJSON.NullRecord == \"true\" {\n\t\t\t\tutil.Info.Println(\"GetAllOffers null offer found for\", offer.Sender, offer.Receiver)\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif offer.GetValueSize > MinimumOfferValueLength && offer.Minutes() <= OfferExpireMinutes {\n\t\t\t\tpc, err := ConnectToIceServices(config)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = util.DecodeObject(offer.GetValue, &linkBridge.Offer)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutil.Info.Println(\"GetAllOffers error with DecodeObject\", linkBridge.LinkAccount, linkBridge.LinkID(), err)\n\t\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tlinkBridge.PeerConnection = pc\n\t\t\t\t\tlinkBridge.State = StateSendAnswer\n\t\t\t\t\tutil.Info.Println(\"Offer found for\", linkBridge.LinkAccount, linkBridge.LinkID())\n\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t} else {\n\t\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t\t}\n\t\t\t} else if offer.Minutes() > OfferExpireMinutes && offer.GetValueSize > MinimumOfferValueLength {\n\t\t\t\tutil.Info.Println(\"Stale Offer found for\", linkBridge.LinkAccount, linkBridge.LinkID(), \"minutes\", offer.Minutes())\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t} else {\n\t\t\t\tutil.Info.Println(\"Offer NOT found for\", linkBridge.LinkAccount, linkBridge.LinkID())\n\t\t\t\tlinkBridges.unconnected[linkBridge.LinkID()] = &linkBridge\n\t\t\t}\n\t\tcase <-stopchan:\n\t\t\tutil.Info.Println(\"GetAllOffers stopped\")\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *client) queryListener() {\n\t// Close the Transporter on exit\n\tdefer c.Close()\n\n\t// Set up connection for slave\n\tfor qry := range c.queries {\n\t\tqry := qry\n\t\ttime.Sleep(15 * time.Millisecond)\n\t\td, e := c.Send(qry.Query)\n\t\tgo qry.sendResponse(d, e)\n\t}\n}", "func StatusUpdate(pkt event.Packet) client.RegistryFunc {\n\treturn func(clients client.Registry) error {\n\t\tfrom := pkt.UIDs()[0]\n\n\t\tif _, ok := clients[from]; !ok {\n\t\t\treturn fmt.Errorf(\"for packet numbered %v client %v is not connected\", pkt.Sequence(), from)\n\t\t}\n\n\t\ttargetClient := clients[from]\n\n\t\tfor uid := range targetClient.Followers {\n\t\t\tfollower, ok := clients[uid]\n\t\t\tif !ok {\n\t\t\t\t// Client is no longer present, delete from followers\n\t\t\t\tdelete(targetClient.Followers, uid)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !follower.IsActive() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := follower.Send(pkt); err != nil {\n\t\t\t\tlog.Debug(fmt.Sprintf(\"notify.StatusUpdate: for client %v, got error %#q\", uid, err))\n\t\t\t\tdelete(targetClient.Followers, uid)\n\n\t\t\t\tclient.UnregisterFunc(uid)(clients)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (p Database) Changes(handler ChangeHandler,\n\toptions map[string]interface{}) error {\n\n\tlargest := i64defopt(options, \"since\", 0)\n\n\theartbeatTime := i64defopt(options, \"heartbeat\", 5000)\n\n\ttimeout := time.Minute\n\tif heartbeatTime > 0 {\n\t\ttimeout = time.Millisecond * time.Duration(heartbeatTime*2)\n\t}\n\n\tfor largest >= 0 {\n\t\tparams := url.Values{}\n\t\tfor k, v := range options {\n\t\t\tparams.Set(k, fmt.Sprintf(\"%v\", v))\n\t\t}\n\t\tif largest > 0 {\n\t\t\tparams.Set(\"since\", fmt.Sprintf(\"%v\", largest))\n\t\t}\n\n\t\tif heartbeatTime > 0 {\n\t\t\tparams.Set(\"heartbeat\", fmt.Sprintf(\"%d\", heartbeatTime))\n\t\t} else {\n\t\t\tparams.Del(\"heartbeat\")\n\t\t}\n\n\t\tfullURL := fmt.Sprintf(\"%s/_changes?%s\", p.DBURL(),\n\t\t\tparams.Encode())\n\n\t\tvar conn net.Conn\n\n\t\t// Swapping out the transport to work around a bug.\n\t\tclient := &http.Client{Transport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDial: func(n, addr string) (net.Conn, error) {\n\t\t\t\tvar err error\n\t\t\t\tconn, err = p.changesDialer(n, addr)\n\t\t\t\treturn conn, err\n\t\t\t},\n\t\t}}\n\n\t\tresp, err := client.Get(fullURL)\n\t\tif err == nil {\n\t\t\tfunc() {\n\t\t\t\tdefer resp.Body.Close()\n\t\t\t\tdefer conn.Close()\n\n\t\t\t\ttc := timeoutClient{resp.Body, conn, timeout}\n\t\t\t\tlargest = handler(&tc)\n\t\t\t}()\n\t\t} else {\n\t\t\tlog.Printf(\"Error in stream: %v\", err)\n\t\t\ttime.Sleep(p.changesFailDelay)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *sessionManager) manageUpdate(u api.Update) {\n\tchatID := u.Message.Chat.ID\n\tv, ok := s.channels[chatID]\n\n\tif !ok {\n\t\tv = s.startConversation(u)\n\t}\n\tif v != nil {\n\t\tv <- u\n\t}\n}", "func (m metrics) Dials() prometheus.Counter {\n\treturn m.dials\n}", "func (s *Service) Dial(cfg Config) error {\n\n\tcert, err := tls.LoadX509KeyPair(cfg.Cert, cfg.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.Server = grpc.NewServer(\n\t\tgrpc.Creds(credentials.NewServerTLSFromCert(&cert)),\n\t\tgrpc.ConnectionTimeout(time.Duration(cfg.ConnectionTimeout)*time.Second),\n\t\tgrpc.NumStreamWorkers(uint32(cfg.NumStreamWorkers)),\n\t\tgrpc.MaxRecvMsgSize(int(cfg.MaxRecvMsgSize)),\n\t)\n\n\ts.WrappedGrpcServer = grpcweb.WrapServer(s.Server,\n\t\tgrpcweb.WithOriginFunc(func(origin string) bool {\n\t\t\tif _, ok := cfg.Origin[origin]; !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t}),\n\t)\n\n\ts.Register()\n\n\treturn nil\n}", "func (bot *Bot) Polling(messages chan Message, edites chan Message) {\n\tfor {\n\t\tupdates, err := bot.GetUpdates()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Polling error (tgapi/Polling):\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, update := range updates {\n\t\t\tif update.Message != nil {\n\t\t\t\tmessages <- *update.Message\n\t\t\t} else if update.EditedMessage != nil {\n\t\t\t\tedites <- *update.EditedMessage\n\t\t\t}\n\n\t\t\tbot.Offset = update.UpdateID + 1\n\t\t}\n\t}\n}", "func synchRequest() {\n\n\tfmt.Println(\" Network: \", getLocalConfigValue(_LEDGER_NETWORK_KEY))\n\tok, err := pingServer(_LEDGER)\n\t//ok, err := pingServer(_ATLAS)\n\t//ok := false\n\tif ok {\n\t\t// things are good.\n\t\tfmt.Println(\" Current ledger node is ACTIVE at address:\", getLocalConfigValue(_LEDGER_ADDRESS_KEY))\n\t\treturn // done.\n\t}\n\n\t// could not successful access the current ledger node. Proceed to check for other nodes.\n\tfmt.Println(\" Default ledger node is NOT ACTIVE:\", getLocalConfigValue(_LEDGER_ADDRESS_KEY))\n\tfmt.Println(\" Searching for a new primary ledger node .....\")\n\n\t// Obtain current list of available ledger nodes from look up directory (atlas)\n\tnodeList, err := getLedgerNodeList()\n\tif err != nil {\n\t\tfmt.Println(\" \", err)\n\t\t// Suggest a fix for certain circumstances\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\tfmt.Printf(\" You may need to set or update local config variable: '%s'\\n\", _LEDGER_NETWORK_KEY)\n\t\t\tfmt.Printf(\" To view local and global variables try: %s config --list\\n\", filepath.Base(os.Args[0]))\n\t\t}\n\t\treturn\n\t}\n\t// Check if list is empty\n\tif len(nodeList) == 0 {\n\t\tfmt.Printf(\" The network '%s' has no ledger nodes registered\\n\", getLocalConfigValue(_LEDGER_NETWORK_KEY))\n\t\treturn\n\t}\n\tnewNodeFound := false\n\tfor _, node := range nodeList {\n\t\tif newNodeFound {\n\t\t\tbreak // from for loop.\n\t\t}\n\t\t//fmt.Println(\" Checking node:\", node.APIURL)\n\t\tok, err := pingServer(node.APIURL)\n\t\tif err != nil {\n\t\t\t//fmt.Println(\" \", err)\n\t\t}\n\t\tif ok {\n\t\t\tnewNodeFound = true\n\t\t\tsetLocalConfigValue(_LEDGER_ADDRESS_KEY, node.APIURL)\n\t\t\tfmt.Printf(\" Found ACTIVE ledger node at: '%s'\\n\", node.APIURL)\n\t\t\tfmt.Println(\" UPDATING default ledger node in config to:\", node.APIURL)\n\t\t}\n\t}\n\tif newNodeFound == false {\n\t\tfmt.Printf(\" Not able to locate an active ledger node referring the %s directory\\n\", _ATLAS)\n\t}\n}", "func pollConn(s *discordgo.Session) {\n\tc := config.Get()\n\tfor {\n\t\ttime.Sleep(10 * time.Second)\n\t\tfound := false\n\t\tguilds, err := s.UserGuilds()\n\t\tfor _, g := range guilds {\n\t\t\tif g.ID == c.Guild {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tlog.Warningf(\"Could not find membership matching guild ID. %s\", c.Guild)\n\t\t\tlog.Warningf(\"Maybe I need a new invite? Using code %s\", c.InviteID)\n\t\t\tif s.Token != \"\" {\n\t\t\t\ts.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Could not fetch guild info %v\", err)\n\t\t\tif s.Token != \"\" {\n\t\t\t\ts.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func update(vs *ViewServer, primary string, backup string){\n\tvs.currentView.Viewnum += 1\n\tvs.currentView.Primary = primary\n\tvs.currentView.Backup = backup\n\tvs.idleServer = \"\"\n\tvs.primaryACK = false\n\tvs.backupACK = false\n}", "func (p *ClientUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (l *Light) ConnectAndUpdate(dev *models.Device, versionInDev *uint64) (err error) {\n\tl.lc.Debug(\"Bat dau tien trinh kiem tra ket noi va dong bo thiet bi\")\n\tdefer l.lc.Debug(\"Ket thuc tien trinh kiem tra ket noi va dong bo thiet bi\")\n\n\topstate := dev.OperatingState\n\tconnected := db.DB().GetConnectedStatus(dev.Name)\n\n\tif versionInDev == nil {\n\t\tif (connected == false && opstate == models.Disabled) || (connected == true && opstate == models.Enabled) {\n\t\t\tl.lc.Debug(fmt.Sprintf(\"Ket thuc tien trinh kiem tra ket noi thiet bi vi: connected=%t & opstate=%s\", connected, opstate))\n\t\t\treturn nil\n\t\t}\n\n\t\t// do something: ...\n\t\t// time.Sleep(2 * time.Second)\n\t\tver, err := appModels.ReadVersionConfigFromDevice(l, dev, PingDr)\n\t\tif err != nil {\n\t\t\tl.lc.Error(fmt.Sprintf(\"Ket thuc tien trinh kiem tra ket noi va dong bo thiet bi vi:%s\", err.Error()))\n\t\t\treturn err\n\t\t}\n\t\tversionInDev = &ver\n\t}\n\n\tif appModels.GetVersionFromDB(*dev) != *versionInDev {\n\t\terr = l.syncConfig(dev)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tl.lc.Debug(fmt.Sprintf(\"cau hinh da duoc dong bo\"))\n\t// dong bo cau hinh la buoc cuoi cung de ket luan: OpState co = true hay khong\n\t// OpState chi = true khi da duoc cap phep, kiem tra ket noi, cap nhap cau hinh ma khong co bat ky loi gi\n\t_, err = appModels.UpdateOpState(dev.Name, true)\n\treturn\n}", "func (a *Announcement) Dial(p *pool.Pool) (*grpc.ClientConn, error) {\n\tif p == nil {\n\t\tp = pool.Global\n\t}\n\tif a.NetAddress == \"\" {\n\t\treturn nil, errors.New(\"No address known for this component\")\n\t}\n\tnetAddress := strings.Split(a.NetAddress, \",\")[0]\n\tif a.Certificate == \"\" {\n\t\treturn p.DialInsecure(netAddress)\n\t}\n\ttlsConfig, _ := a.TLSConfig()\n\treturn p.DialSecure(netAddress, credentials.NewTLS(tlsConfig))\n}", "func (c *Client) Dial(stampStr string) (*ResolverInfo, error) {\n\tstamp, err := dnsstamps.NewServerStampFromString(stampStr)\n\tif err != nil {\n\t\t// Invalid SDNS stamp\n\t\treturn nil, err\n\t}\n\n\tif stamp.Proto != dnsstamps.StampProtoTypeDNSCrypt {\n\t\treturn nil, ErrInvalidDNSStamp\n\t}\n\n\treturn c.DialStamp(stamp)\n}", "func (r *Raft) serviceAppendEntriesReq(request AppendEntriesReq, HeartBeatTimer *time.Timer, waitTime int, state int) int {\n\t//replicates entry wise , one by one\n\tbecomeFollower := false //for candidate caller only\n\twaitTime_msecs := msecs * time.Duration(waitTime)\n\tappEntriesResponse := AppendEntriesResponse{} //make object for responding to leader\n\tappEntriesResponse.FollowerId = r.Myconfig.Id\n\tappEntriesResponse.Success = false //false by default\n\tappEntriesResponse.IsHeartBeat = false //by default\n\tvar myLastIndexTerm, myLastIndex int\n\tmyLastIndex = r.MyMetaData.LastLogIndex\n\tif request.Term >= r.myCV.CurrentTerm { //valid leader\n\t\tleaderId := request.LeaderId\n\t\tr.UpdateLeaderInfo(leaderId) //update leader info\n\t\tif request.Term > r.myCV.CurrentTerm {\n\t\t\tr.myCV.CurrentTerm = request.Term //update self Term\n\t\t\tr.myCV.VotedFor = -1 //update votedfor whenever CT is changed\n\t\t\tr.WriteCVToDisk()\n\t\t}\n\t\tif state == follower {\n\t\t\tHeartBeatTimer.Reset(waitTime_msecs) //reset the timer if this is HB or AE req from valid leader\n\t\t}\n\t\tif len(r.MyLog) == 0 { //if log is empty\n\t\t\tmyLastIndexTerm = -1\n\t\t} else {\n\t\t\tmyLastIndexTerm = r.MyLog[myLastIndex].Term\n\t\t}\n\t\t//This is a HB,here log is empty on both sides so Term must not be checked (as leader has incremented its Term due to elections)\n\t\tif request.Entries == nil {\n\t\t\tif len(r.MyLog) == 0 { //just to be sure ===must be satisfied otherwise leader is invalid and logic bug is there.\n\t\t\t\tappEntriesResponse.Success = true\n\t\t\t\tappEntriesResponse.IsHeartBeat = true\n\t\t\t\tbecomeFollower = true\n\t\t\t}\n\t\t} else { //log has Data so-- for heartbeat, check the index and Term of last entry\n\t\t\tif request.LeaderLastLogIndex == myLastIndex && request.LeaderLastLogTerm == myLastIndexTerm {\n\t\t\t\t//this is heartbeat as last entry is already present in self log\n\t\t\t\tappEntriesResponse.Success = true\n\t\t\t\tappEntriesResponse.IsHeartBeat = true\n\t\t\t\tr.MyMetaData.CommitIndex = request.LeaderCommitIndex //update the CI for last entry that leader got majority acks for!\n\t\t\t\tbecomeFollower = true\n\t\t\t} else { //this is not a heartbeat but append request\n\t\t\t\tif request.PrevLogTerm == myLastIndexTerm && request.PrevLogIndex == myLastIndex { //log is consistent except new entry\n\t\t\t\t\tbecomeFollower = true\n\t\t\t\t\tif state == follower { //when caller is follower then only append to log\n\t\t\t\t\t\tr.AppendToLog_Follower(request) //append to log\n\t\t\t\t\t\tappEntriesResponse.Success = true\n\t\t\t\t\t\tappEntriesResponse.IsHeartBeat = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tappEntriesResponse.Term = r.myCV.CurrentTerm\n\tappEntriesResponse.LastLogIndex = r.MyMetaData.LastLogIndex\n\tr.send(request.LeaderId, appEntriesResponse)\n\tif state == candidate && becomeFollower { //this is candidate call\n\t\treturn follower\n\t} else {\n\t\treturn -1\n\t}\n}", "func (r *Raft) ClientListener(listener net.Conn) {\n\tcommand, rem := \"\", \"\"\n\tdefer listener.Close()\t\n\tfor {\t\t\t//this is one is outer for\n\tinput := make([]byte, 1000)\n\tlistener.SetDeadline(time.Now().Add(3 * time.Second)) // 3 second timeout\n\tlistener.Read(input)\n\tinput_ := string(Trim(input))\n\tif len(input_) == 0 { continue }\n\tif r.Id != r.LeaderId {\n\t\tleader := r.ClusterConfigV.Servers[r.LeaderId]\n\n\t\traft.Output_ch <- raft.String_Conn{\"ERR_REDIRECT \" + leader.Hostname + \" \" + strconv.Itoa(leader.ClientPort), listener}\n\t\tinput = input[:0]\n\t\tcontinue\n\t}\n\tcommand, rem = GetCommand(rem + input_)\n\tfor {\n\t\t\tif command != \"\" {\n\t\t\t//\tif command[0:3] == \"get\" {\t\t\t\t\t\n\t\t\t//\t\tInput_ch <- Log_Conn{LogEntry{0,0,[]byte(command),true}, listener}\n\t\t\t//\t} else {\n\t\t\t\t\tcommandbytes := []byte(command)\t\t\n\t\t\t\t\tlogMutex.Lock()\t\t\t\n\t\t\t\t\t\tvar logentry=LogEntry{r.CurrentTerm,len(r.Log),commandbytes,false}\n\t\t\t\t\t\tr.Log=append(r.Log,logentry)\n\t\t\t\t\t\tlog.Println(\"Appennding log \",logentry.SequenceNumber)\n\t\t\t\t\t\tAppend_ch <- Log_Conn{logentry, listener}\n\t\t\t\t\tlogMutex.Unlock()\n\t\t\t\t//}\n\t\t\t} else { \n\t\t\t\t//fmt.Println(\"I m breaking yaaar. Sorry\")\n\t\t\t\t break \t} //end of outer if\n\t\t\tcommand, rem = GetCommand(rem)\n\t\t}//end of for\n\t}//end of outer for\n}", "func (m *DomainMonitor) Listen() <-chan DomainUpdate {\n\treturn m.bc.Listen()\n}", "func (d *delegate) NotifyUpdate(n *memberlist.Node) {\n\tlevel.Debug(d.logger).Log(\"received\", \"NotifyUpdate\", \"node\", n.Name, \"addr\", n.Address())\n}", "func (m Messenge) ListenChat(request messengers.ListenChatRequest, output messengers.ListenChatOutput) {\n\tif !m.Available() {\n\t\tlog.Println(\"bot not available\")\n\t\treturn\n\t}\n\tbot := m.bot\n\ttgu := tgbotapi.NewUpdate(0)\n\ttgu.Timeout = 60\n\n\tupdates, err := bot.GetUpdatesChan(tgu)\n\tif err != nil {\n\t\tlog.Panic(\"can't get updates chanel \", err)\n\t}\n\n\tfor update := range updates {\n\t\tchatID := update.Message.Chat.ID\n\t\tmustRegistered := false\n\t\t// is contact?\n\t\tcon := update.Message.Contact\n\t\tif con != nil {\n\t\t\tmustRegistered = true\n\t\t\trequest.Phone = con.PhoneNumber\n\t\t\trequest.Messenger = m.name\n\t\t\trequest.ChatID = int(chatID)\n\t\t\toutput.OnResponse(request)\n\t\t}\n\t\t// is document?\n\t\tdoc := update.Message.Document\n\t\tif doc != nil {\n\t\t\turl, err := m.bot.GetFileDirectURL(doc.FileID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"can't get url for file from chat %e\", err)\n\n\t\t\t} else {\n\t\t\t\trequest.Messenger = m.name\n\t\t\t\trequest.ChatID = int(chatID)\n\t\t\t\trequest.FileURL = url\n\t\t\t\trequest.FileName = doc.FileName\n\t\t\t\trequest.FileSize = doc.FileSize\n\t\t\t\trequest.Description = update.Message.Caption\n\t\t\t\toutput.OnResponse(request)\n\t\t\t}\n\t\t}\n\n\t\tregistered := m.isRegisteredWait(request, mustRegistered, int(chatID), 10)\n\t\tif registered {\n\t\t\tmsg := tgbotapi.NewMessage(chatID, upload)\n\t\t\tmsg.ParseMode = \"HTML\"\n\t\t\tbot.Send(msg)\n\t\t\tmsg = tgbotapi.NewMessage(chatID, m.server)\n\t\t\tbot.Send(msg)\n\t\t} else {\n\t\t\tmsg := tgbotapi.NewMessage(chatID, register)\n\t\t\tvar keyboard = tgbotapi.NewReplyKeyboard(\n\t\t\t\ttgbotapi.NewKeyboardButtonRow(\n\t\t\t\t\ttgbotapi.NewKeyboardButtonContact(\"\\xF0\\x9F\\x93\\x9E Send phone\"),\n\t\t\t\t),\n\t\t\t)\n\t\t\tmsg.ReplyMarkup = keyboard\n\t\t\tbot.Send(msg)\n\t\t}\n\t}\n}", "func listenForBtChanges() {\n\tlastExitCode := 999\n\tfor {\n\t\tcmd := exec.Command(\"ls\", \"/dev/input/event0\")\n\t\t_ = cmd.Run()\n\t\texitCode := cmd.ProcessState.ExitCode()\n\t\tif exitCode == 2 {\n\t\t\t// not connected\n\t\t\tif lastExitCode == 0 {\n\t\t\t\tlogger.Info(\"Re-run mplayer (2)... \")\n\t\t\t\tbluetoothConnected = false\n\t\t\t\tstationMutex.Lock()\n\t\t\t\tnewStation()\n\t\t\t\tstationMutex.Unlock()\n\t\t\t}\n\t\t\tfor _, btDevice := range btDevices {\n\t\t\t\t// logger.Info(fmt.Sprintf(\"Trying to connect device #%d %s\", idx, btDevice))\n\t\t\t\tcmd = exec.Command(\"bluetoothctl\", \"connect\", btDevice)\n\t\t\t\t_ = cmd.Run()\n\t\t\t\tconnectExitCode := cmd.ProcessState.ExitCode()\n\t\t\t\tif connectExitCode == 0 {\n\t\t\t\t\tlogger.Info(\"Success with device \" + btDevice)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else if exitCode == 0 {\n\t\t\t// connected\n\t\t\tif lastExitCode == 2 {\n\t\t\t\tlogger.Info(\"Re-run mplayer (0)... \")\n\t\t\t\tbluetoothConnected = true\n\t\t\t\tstationMutex.Lock()\n\t\t\t\tnewStation()\n\t\t\t\tstationMutex.Unlock()\n\t\t\t}\n\t\t}\n\t\tlastExitCode = exitCode\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}", "func (TelegramBotApp *TelegramBotApp) setupPolling() (tgbotapi.UpdatesChannel, error) {\n\tTelegramBotApp.bot.RemoveWebhook()\n\tupdateConfig := tgbotapi.NewUpdate(0)\n\tupdateConfig.Timeout = 5\n\tfmt.Println(\"[+] Pooling method selected\")\n\treturn TelegramBotApp.bot.GetUpdatesChan(updateConfig)\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 (s *SSR) DialUDP(network, addr string) (net.PacketConn, net.Addr, error) {\n\treturn nil, nil, errors.New(\"[ssr] udp not supported now\")\n}", "func udpDaemon() {\n\tserverAddr := Port\n\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", serverAddr)\n\tprintError(err)\n\t// Listen the request\n\tlisten, err := net.ListenUDP(\"udp\", udpAddr)\n\tprintError(err)\n\n\t// Use waitgroup\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\tuserCmd := make(chan string)\n\n\tgo readCommand(userCmd)\n\n\tglobal_wg.Add(1)\n\tgo udpDaemonHandle(listen)\n\tgo periodicPing()\n\tgo periodicPingIntroducer()\n\n\tfor {\n\t\ts := <-userCmd\n\t\tswitch s {\n\t\tcase \"join\":\n\t\t\tif CurrentList.Size() > 0 {\n\t\t\t\tfmt.Println(\"Already in the group\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglobal_wg.Done()\n\n\t\t\tif LocalIP == IntroducerIP {\n\t\t\t\tCurrentMember.State |= (StateIntro | StateMonit)\n\t\t\t\tCurrentList.Insert(CurrentMember)\n\t\t\t} else {\n\t\t\t\t// New member, send Init Request to the introducer\n\t\t\t\tinitRequest(CurrentMember)\n\t\t\t}\n\n\t\tcase \"showlist\":\n\t\t\tCurrentList.PrintMemberList()\n\n\t\tcase \"showid\":\n\t\t\tfmt.Printf(\"Member (%d, %s)\\n\", CurrentMember.TimeStamp, LocalIP)\n\n\t\tcase \"leave\":\n\t\t\tif CurrentList.Size() < 1 {\n\t\t\t\tfmt.Println(\"Haven't join the group\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglobal_wg.Add(1)\n\t\t\tinitiateLeave()\n\n\t\tdefault:\n\t\t\tfmt.Println(\"Invalid Command, Please use correct one\")\n\t\t\tfmt.Println(\"# join\")\n\t\t\tfmt.Println(\"# showlist\")\n\t\t\tfmt.Println(\"# showid\")\n\t\t\tfmt.Println(\"# leave\")\n\t\t}\n\t}\n\n\twg.Wait()\n}", "func Dial(dial func (string,string) (*rpc.Client, error), network, address string) (*rpc.Client, error) {\n\tconn, err := net.Dial(network,address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rpc.NewClientWithCodec(NewClientCodec(conn)), err\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 (c *dialCall) dial(ctx context.Context, addr string) {\n\tconst singleUse = false // shared conn\n\tc.res, c.err = c.p.t.dialClientConn(ctx, addr, singleUse)\n\n\tc.p.mu.Lock()\n\tdelete(c.p.dialing, addr)\n\tif c.err == nil {\n\t\tc.p.addConnLocked(addr, c.res)\n\t}\n\tc.p.mu.Unlock()\n\n\tclose(c.done)\n}", "func updateStatus(e *event) {\n\tfMap := followers[e.from]\n\tfor _, f := range fMap {\n\t\tif h, ok := clients.Get(f); ok {\n\t\t\th.Write(e)\n\t\t}\n\t}\n}", "func (m *endpointManager) OnUpdate(msg interface{}) {\n\tswitch msg := msg.(type) {\n\tcase *proto.WorkloadEndpointUpdate:\n\t\tlog.WithField(\"workloadEndpointId\", msg.Id).Info(\"Processing WorkloadEndpointUpdate\")\n\t\tm.pendingWlEpUpdates[*msg.Id] = msg.Endpoint\n\tcase *proto.WorkloadEndpointRemove:\n\t\tlog.WithField(\"workloadEndpointId\", msg.Id).Info(\"Processing WorkloadEndpointRemove\")\n\t\tm.pendingWlEpUpdates[*msg.Id] = nil\n\tcase *proto.ActivePolicyUpdate:\n\t\tlog.WithField(\"policyID\", msg.Id).Info(\"Processing ActivePolicyUpdate\")\n\t\tm.ProcessPolicyProfileUpdate(policysets.PolicyNamePrefix + msg.Id.Name)\n\tcase *proto.ActiveProfileUpdate:\n\t\tlog.WithField(\"profileId\", msg.Id).Info(\"Processing ActiveProfileUpdate\")\n\t\tm.ProcessPolicyProfileUpdate(policysets.ProfileNamePrefix + msg.Id.Name)\n\t}\n}", "func handleUpdate(update tgbotapi.Update) {\n\ttext := update.Message.Text\n\tchatID := update.Message.Chat.ID\n\tmsgID := update.Message.MessageID\n\n\tsampleMsg := tgbotapi.NewMessage(chatID,\n\t\tsampleReply)\n\n\tif text == \"/start\" {\n\t\tstartMsg := tgbotapi.NewMessage(chatID, startReply)\n\t\tstartMsg.ReplyToMessageID = msgID\n\t\tbot.Send(startMsg)\n\t\tbot.Send(sampleMsg)\n\t\treturn\n\n\t}\n\n\t// Windows end of line\n\tuserPass := strings.Split(text, \"\\r\\n\")\n\tif len(userPass) == 1 {\n\t\tuserPass = strings.Split(text, \"\\n\")\n\t}\n\tif len(userPass) != 2 {\n\t\twrongMsg := tgbotapi.NewMessage(chatID, wrongReply)\n\t\twrongMsg.ReplyToMessageID = msgID\n\t\tbot.Send(wrongMsg)\n\t\tbot.Send(sampleMsg)\n\t\treturn\n\t}\n\n\tusers[chatID] = mail.Cred{Username: userPass[0], Password: userPass[1]}\n\tlog.Println(users)\n\tokMsg := tgbotapi.NewMessage(chatID, okReply)\n\tokMsg.ReplyToMessageID = msgID\n\tbot.Send(okMsg)\n}", "func listen2listen(listen1, listen2 string) {\n\tclient1 := make(chan net.Conn)\n\tclient2 := make(chan net.Conn)\n\tgo ListenTCP(listen1, client1)\n\tgo ListenTCP(listen2, client2)\n\n\tfor {\n\t\tgo link(<-client1, <-client2)\n\t}\n}", "func (h *Handler) serveUpdateDBUser(w http.ResponseWriter, r *http.Request) {}", "func Dial(endp string) (*ServerQueryAPI, error) {\n\tconn, err := net.Dial(\"tcp\", endp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapi := NewServerQueryAPI(NewServerQueryReadWriter(conn))\n\tif err := api.waitForServerIntro(); err != nil {\n\t\tconn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn api, nil\n}", "func DialC(iPort int,szHost string,cbR cbRead,cbD cbDiscon)(int,bool,string) {\n if iPort <= 0 || iPort >= 65535{\n return -1,false,\"port is invalued!\"\n }\n if szHost==\"\"{\n return -1,false,\"host is invalued!\"\n }\n if nil == cbR || nil == cbD{\n return -1,false,\"callback function is invalued!!\"\n }\n conn,err := net.Dial(\"tcp\",fmt.Sprintf(\"%s:%d\",szHost,iPort))\n if nil != err{\n L.W(fmt.Sprintf(\"connect to %s:%d fail,err:\",szHost,iPort,err),L.Level_Error)\n return -1,false,fmt.Sprintf(\"%s\",err)\n }\n iId := getNewID()\n if iId == -1{\n conn.Close()\n return -1,false,\"socket id use up!!\"\n }\n if !updateConInfo(iId,iPort,szHost,conn,cbD,false,true){\n conn.Close()\n return -1,false,\"socket id exsist!!\"\n }\n go conRead(cbR,iId,conn,false)\n return iId,true,\"start client suc!!\"\n}", "func (host *DinnerHost) Listen() {\n\tname := \"\"\n\tfor {\n\t\tselect {\n\t\tcase name = <-host.requestChannel:\n\t\t\tfmt.Println(name + \" WOULD LIKE TO EAT.\")\n\n\t\t\tresponse := host.AllowEating(name)\n\t\t\tkickOut := false\n\t\t\tswitch response {\n\t\t\tcase \"OK\":\n\t\t\t\tfmt.Println(name + \" STARTS EATING.\")\n\t\t\tcase \"E:CHOPSTICKS\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: REQUIRED CHOPSTICKS ARE NOT AVAILABLE.\")\n\t\t\tcase \"E:FULL\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: TWO OTHER PHILOSOPHERS ARE ALREADY EATING.\")\n\t\t\tcase \"E:JUSTFINISHED\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: JUST FINISHED THE PREVIOUS MEAL.\")\n\t\t\tcase \"E:EATING\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY EATING.\")\n\t\t\tcase \"E:LIMIT\":\n\t\t\t\tfmt.Println(name + \" CANNOT EAT: ALREADY HAD THREE DINNERS; MUST LEAVE.\")\n\t\t\t\thost.freeSeats = append(host.freeSeats, host.phiData[name].Seat())\n\t\t\t\tkickOut = true\n\t\t\t}\n\t\t\tfmt.Println()\n\n\t\t\thost.phiData[name].RespChannel() <- response\n\n\t\t\tif kickOut {\n\t\t\t\tdelete(host.phiData, name)\n\t\t\t}\n\t\tcase name = <-host.finishChannel:\n\t\t\thost.SomeoneFinished(name)\n\t\t}\n\t\thost.PrintReport(false)\n\t}\n}", "func (rm *ResponseManager) GetUpdates(p peer.ID, requestID graphsync.RequestID, updatesChan chan<- []gsmsg.GraphSyncRequest) {\n\trm.send(&responseUpdateRequest{responseKey{p, requestID}, updatesChan}, nil)\n}", "func Dial(notifyChan *proto.NotificationChan, ob *proto.DebugObserver, network, address string) (*Client, error) {\n\tconn, err := net.Dial(network, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewClientWithCodec(notifyChan, codec.NewClientCodec(ob, conn)), err\n}", "func (x *x509Handler) handleUpdates() {\n\tfor {\n\t\tselect {\n\t\tcase <-x.changes:\n\t\t\tbreak\n\t\tcase <-x.stopChan:\n\t\t\treturn\n\t\t}\n\n\tSendUpdate:\n\t\tx.mtx.RLock()\n\t\tlatest := x.latest\n\t\tx.mtx.RUnlock()\n\n\t\tselect {\n\t\tcase x.updChan <- latest:\n\t\t\tcontinue\n\t\tcase <-x.changes:\n\t\t\tgoto SendUpdate\n\t\tcase <-x.stopChan:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *CassandraDataCentersClientUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (p *DatabaseAccountsClientUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (p *DomainsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) {\n\treturn p.pt.Poll(ctx)\n}", "func (urls *url) urlUpdater(config *rest.Config, i *int, namespace string) {\n\tfor {\n\t\td := time.Duration(*i)\n\t\ttime.Sleep(d * time.Second)\n\t\t*urls = getIngressUrls(config, namespace)\n\t\tlog.Info(\"Updated host list.\")\n\t}\n}", "func (vs *ViewServer) Ping(args *PingArgs, reply *PingReply) error {\n\n\tvs.mu.Lock()\n\tlog.Printf(\"[viewserver]%+v PING, vs state: vs.view=%+v, vs.primaryAck=%d\", args, vs.view, vs.primaryAck)\n\t// Your code here.\n\n\t//0. keep track by setting pingMap\n\t// if primary viewnum lag behind more than 1 with viewserver, we consider the priamry is dead\n\tif !(vs.view.Primary == args.Me && vs.view.Viewnum > args.Viewnum + 1) {\n\t\tvs.pingTrack[args.Me] = time.Now()\n\t}\n\t\n\tif vs.view.Primary == \"\" && vs.view.Backup == \"\" {\n\t\t// Should prevent uninitialized server to be primary\n\t\t// When primary crashes while there is no backup, we must reboot primary to recovery the service\n\t\t// When primary crashes while backup crashes simultaneously, we can recovery the service through both primary and backup \n\t\tif vs.view.Viewnum == 0 && vs.view.Viewnum == vs.primaryAck {\n\t\t\tvs.view.Primary = args.Me\n\t\t\tvs.view.Viewnum += 1\n\t\t\tlog.Printf(\"[viewserver]add primary %s, reply=%+v\", args.Me, vs.view)\n\t\t}\n\t} else if vs.view.Primary != \"\" && vs.view.Backup == \"\" {\n\t\tif vs.view.Primary == args.Me {\n\t\t\t//primary acknowledge\n\t\t\tif vs.primaryAck == args.Viewnum - 1 {\n\t\t\t\tvs.primaryAck = args.Viewnum\n\t\t\t\tlog.Printf(\"[viewserver]Primary %s ack %d\",args.Me, vs.primaryAck)\n\t\t\t}\n\t\t} else if vs.view.Viewnum == vs.primaryAck {\n\t\t\t//Add Backup \n\t\t\tvs.view.Backup = args.Me\n\t\t\tvs.view.Viewnum += 1\n\t\t}\n\t} else if vs.view.Primary != \"\" && vs.view.Backup != \"\" {\n\t\tif vs.view.Primary == args.Me {\n\t\t\t//primary acknowledge\n\t\t\tif vs.primaryAck == args.Viewnum - 1 {\n\t\t\t\tvs.primaryAck = args.Viewnum\n\t\t\t\tlog.Printf(\"[viewserver]Primary %s ack %d\",args.Me, vs.primaryAck)\n\t\t\t}\n\t\t}\n\t}\n\treply.View = vs.view\n\tvs.mu.Unlock()\n\treturn nil\n}", "func Relay(addr, password string, queries chan rcon.RCONQuery) {\n\tfor req := range queries {\n\t\tres, err := Query(addr, rconPacket(password, req.Command))\n\t\tif err != nil {\n\t\t\tlog.Println(\"RCON request timed out:\", req.Command)\n\t\t}\n\n\t\tif req.Response != nil {\n\t\t\treq.Response <- res\n\t\t}\n\n\t\t// only two RCON commands per second (server only accepts two)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}", "func (notifee *Notifee) Listen(network.Network, multiaddr.Multiaddr) {}", "func (c networkDependencyCollector) Update(ch chan<- prometheus.Metric) error {\n\ttraffic := darkstat.Get()\n\tserverProcesses, upstreams, downstreams := socketstat.Get()\n\tlocalInventory := inventory.GetLocalInventory()\n\n\tfor _, m := range traffic {\n\t\tch <- prometheus.MustNewConstMetric(c.traffic, prometheus.GaugeValue, m.Bandwidth,\n\t\t\tm.LocalHostgroup, m.Direction, m.RemoteHostgroup, m.RemoteIPAddr, m.LocalDomain, m.RemoteDomain)\n\t}\n\tfor _, m := range upstreams {\n\t\tch <- prometheus.MustNewConstMetric(c.upstream, prometheus.GaugeValue, 1,\n\t\t\tm.LocalHostgroup, m.RemoteHostgroup, m.LocalAddress, m.RemoteAddress, m.Port, m.Protocol, m.ProcessName)\n\t}\n\tfor _, m := range downstreams {\n\t\tch <- prometheus.MustNewConstMetric(c.downstream, prometheus.GaugeValue, 1,\n\t\t\tm.LocalHostgroup, m.RemoteHostgroup, m.LocalAddress, m.RemoteAddress, m.Port, m.Protocol, m.ProcessName)\n\t}\n\tfor _, m := range serverProcesses {\n\t\tch <- prometheus.MustNewConstMetric(c.serverProcesses, prometheus.GaugeValue, 1,\n\t\t\tlocalInventory.Hostgroup, m.Bind, m.Name, m.Port)\n\t}\n\n\treturn nil\n}" ]
[ "0.56095344", "0.55318636", "0.55113477", "0.54187083", "0.53517175", "0.5322763", "0.5301367", "0.5290845", "0.52050334", "0.52011144", "0.51694024", "0.5144419", "0.51231486", "0.5108113", "0.50921655", "0.5088653", "0.5079346", "0.5072482", "0.5057227", "0.5051531", "0.5045758", "0.50301045", "0.501935", "0.5012999", "0.49944916", "0.49924853", "0.49843225", "0.49784553", "0.49769175", "0.49666584", "0.49635932", "0.49156746", "0.49086016", "0.49080738", "0.490056", "0.4898088", "0.48972517", "0.4896976", "0.48908818", "0.4889629", "0.48881137", "0.48853025", "0.4883718", "0.4882908", "0.48772824", "0.48699188", "0.48608667", "0.4854436", "0.4846742", "0.48463857", "0.48453453", "0.48444784", "0.48371178", "0.48316777", "0.48251736", "0.4817958", "0.48174185", "0.481334", "0.48078212", "0.4799566", "0.47907683", "0.4789234", "0.4776109", "0.47635078", "0.47613427", "0.47578427", "0.47578156", "0.47542286", "0.47476494", "0.47470668", "0.47426108", "0.47265118", "0.4714546", "0.4712762", "0.47125763", "0.4704638", "0.47028887", "0.4694949", "0.46924916", "0.46881884", "0.46862042", "0.46844882", "0.46771047", "0.46749476", "0.4672068", "0.46654725", "0.4662114", "0.46602237", "0.46597075", "0.46569836", "0.4653015", "0.46473113", "0.46461847", "0.46379897", "0.46366087", "0.46339187", "0.46337825", "0.46305865", "0.46293035", "0.46267995" ]
0.50818026
16
constantly listeing if srv sends opt ode 255, then we wants to update the lang file.
func update(connection net.Conn) { tmp := make([]byte, 1) for { connection.Read(tmp) if tmp[0] == 255 { updateFile(connection) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func updateFile(connection net.Conn) {\n\tfmt.Println(\"Updating file...\")\n\tlang := make([]byte, 10)\n\tvar content string //content for the new file\n\t\n\tconnection.Read(lang) //read what lang file to change\n\n\t\n\t\n\ttmp := make([]byte, 255) //tmp for holdning the content from the srv\n\tfor {\n\t\tread,_ := connection.Read(tmp) //reads what the srv wants to update the file with\n\t\tif tmp[read-1] == 4 { //the update from the srv will end will 4 ascii = end of transmission\n\t\t\tbreak\n\t\t}\n\t\tcontent += string(tmp) //store the content of the file\n\t}\n\t\n\n\t//search for the input lang and if we can change it.\n\texist := false\n\tfor _,currentlang := range languages {\n\t\tif currentlang == strings.TrimSpace(string(lang)) {\n\t\t\texist = true\n\t\t}\n\t}\n\n\t//the lang did exists! so we append the lang to the global languages list.\n\tif exist == false {\n\t\tlanguages = append(languages, strings.TrimSpace(string(lang)))\n\t}\n\n\t//We will override already existing languages and create a new file if its a totally new language\n\tfilename := strings.TrimSpace(string(lang)) + \".txt\"\n\n\tnewcontent := string(content) //the content from the srv\n\t\n\toverrideFile(filename, newcontent) //overridefile will take all the content and replace all content with the new content\n\n\n\t// check if the clients current lang is the new lang\n\tif custlang == strings.TrimSpace(string(lang)) {\n\t\ttmplines := make([]string,0) //we must replace all old lines from the lang file\n\t\tfile, err := os.Open(filename) //open the file\n\t\tcheck(err)\n\t\t\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\ttmplines = append(tmplines, scanner.Text())\n\t\t}\n\t\tfile.Close()\n\t\t*(&lines) = tmplines //replace all old lines with the new content \n\t\tcheck(scanner.Err())\n\t}\n\t\n}", "func (this *GenericController) setLangVer() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\n\t// 1. Check URL arguments.\n\tpreferredLang := this.GetString(\"preferredLang\", \"\")\n\n\t// 2. Get language information from cookies.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = this.Ctx.GetCookie(\"preferredLang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(preferredLang) {\n\t\tpreferredLang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(preferredLang) == 0 {\n\t\tal := this.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tpreferredLang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = \"ta-LK\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := lang.LangType{\n\t\tLang: preferredLang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.Ctx.SetCookie(\"preferredLang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\trestLangs := make([]*lang.LangType, 0, len(lang.LangTypes)-1)\n\tfor _, v := range lang.LangTypes {\n\t\tif preferredLang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\t// Set language properties.\n\tthis.Lang = preferredLang\n\tthis.Data[\"Lang\"] = curLang.Lang\n\tthis.Data[\"CurLang\"] = curLang.Name\n\tthis.Data[\"RestLangs\"] = restLangs\n\treturn isNeedRedir\n}", "func validateLang() {\n\t\n\t//print all lang options\n\tfmt.Println(intro)\n\tfor _, lang := range languages {\n\t\tfmt.Println(lang)\n\t}\n\n\t//local lines that will hold all lines in the choosen lang file\n\tlines = make([]string,0)\n\t//l will be our predefined languages\n\tl := languages\n\n\t//infinit loop for reading user input language, loop ends if correct lang was choosen \n\tfor {\n\t\tpicked := strings.TrimSpace(userInput()) //read the input from Stdin, trim spaces \n\n\t\t//looping through our predefined languages\n\t\tfor _,lang := range(l) {\n\t\t\tfmt.Println(lang)\n\t\t\tif (picked == lang) {\n\t\t\t\t//fmt.Println(\"Found language!\", lang, picked)\n\t\t\t\tcustlang = lang //variable to hold current lang for client\n\t\t\t\tlang = lang + \".txt\" //append .txt because we are reading from files\n\t\t\t\n\t\t\t\tfile, err := os.Open(lang) //open the given languge file\n\t\t\t\tcheck(err) //check if correct\n\n\t\t\t\tscanner := bufio.NewScanner(file) //scanning through the file\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tlines = append(lines, scanner.Text()) //appending each line in the given langue file to lines\n\t\t\t\t }\n\t\t\t\tfile.Close() //close the file\n\t\t\t\tcheck(scanner.Err()) //check for errors so nothing is left in the file to read\n\t\t\t\tbreak\n\t\t\t} \n\t\t}\n\t\t//check so we actually got something in len, if we have, we have successfully changed language\n\t\tif (len(lines) != 0) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(end) //print error msg\n\t\t}\n\t}\n}", "func (this *BaseRouter) setLang() bool {\n\tfmt.Println(\"setLang() function\")\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tlangs := conf.Langs\n\n\t// 1. Check URL arguments.\n\tlang := this.GetString(\"lang\")\n\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = this.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\tif len(lang) == 0 && this.IsLogin {\n\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t}\n\n\t// 4. Get language information from 'Accept-Language'.\n\tif len(lang) == 0 {\n\t\tal := this.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. DefaucurLang language is English.\n\tif len(lang) == 0 {\n\t\tlang = \"en-US\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tthis.Data[\"Lang\"] = lang\n\tthis.Data[\"Langs\"] = langs\n\n\tthis.Lang = lang\n\n\treturn isNeedRedir\n}", "func setLang(lang string) {\n\tif lang == \"pl\" {\n\t\tl = langTexts[\"pl\"]\n\t} else if lang == \"en\" {\n\t\tl = langTexts[\"en\"]\n\t}\n}", "func (c *IndexController) setLang() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\t// get all lang names from i18n\n\tbeego.Debug(len(Langs))\n\tif len(Langs) == 0 {\n\t\tsettingLocales()\n\t}\n\n\t///*\n\tbeego.Debug(hasCookie)\n\tbeego.Debug(isNeedRedir)\n\t//*/ // 1. Check URL arguments.\n\tlang := c.GetString(\"lang\")\n\t//beego.Debug(lang)\n\t//*\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = c.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify by purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. check if isLogin then use user setting\n\t/*\n\t\tif len(lang) == 0 && this.IsLogin {\n\t\t\tlang = i18n.GetLangByIndex(this.User.Lang)\n\t\t}\n\t\t//*/\n\t// 4. Get language information from 'Accept-Language'.\n\t//beego.Debug(\"浏览器是什么语言\", c.Ctx.Input.Header(\"Accept-Language\"))\n\t//*\n\tif len(lang) == 0 {\n\t\tal := c.Ctx.Input.Header(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\t//*/\n\t// 4. DefaucurLang language is English.\n\t//*\n\tif len(lang) == 0 {\n\t\tlang = \"zh-TW\"\n\t\tisNeedRedir = false\n\t}\n\n\t// Save language information in cookies.\n\t//*\n\tif !hasCookie {\n\t\tc.setLangCookie(lang)\n\t}\n\n\t// Set language properties.\n\tc.Data[\"Lang\"] = lang\n\tc.Data[\"Langs\"] = Langs\n\n\tc.Lang = lang\n\t//\tbeego.Debug(\"坑货的值 :\", isNeedRedir)\n\treturn isNeedRedir\n\t//*/\n}", "func (_obj *Apilangpack) Langpack_getLanguage(params *TLlangpack_getLanguage, _opt ...map[string]string) (ret LangPackLanguage, 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, \"langpack_getLanguage\", _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 (c *ExtendedBeegoController) SetLanguange() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\tLoadLanguages()\n\n\t// 1. Check URL arguments.\n\tlang := c.Input().Get(\"lang\")\n\n\t// 2. Get language information from cookies.\n\tif len(lang) == 0 {\n\t\tlang = c.Ctx.GetCookie(\"lang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(lang) {\n\t\tlang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(lang) == 0 {\n\t\tal := c.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tlang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(lang) == 0 {\n\t\tlang = \"en-US\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := langType{\n\t\tLang: lang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tc.Ctx.SetCookie(\"lang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\tvar langLength = len(i18n.ListLangs())\n\n\tfmt.Println(langLength - 1)\n\n\trestLangs := make([]*langType, 0, langLength-1)\n\tfor _, v := range langTypes {\n\t\tif lang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\n\t// Set language properties.\n\tc.Lang = lang\n\tc.Data[\"Lang\"] = curLang.Lang\n\tc.Data[\"CurLang\"] = curLang.Name\n\tc.Data[\"RestLangs\"] = restLangs\n\n\treturn isNeedRedir\n}", "func (_obj *Apilangpack) Langpack_getLangPack(params *TLlangpack_getLangPack, _opt ...map[string]string) (ret LangPackDifference, 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, \"langpack_getLangPack\", _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 Loadlangdata(id1 string, id2 int) {\n\n\t/*\n\t\t// arcanesData\n\n\t\turl := \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/arcanesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/arcanesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ := http.NewRequest(\"GET\", url, nil)\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\tarcanesData[id1] = string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// conclaveData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/conclaveData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/conclaveData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tconclaveData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// eventsData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/eventsData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/eventsData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\teventsData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// operationTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/operationTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/operationTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\toperationTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// persistentEnemyData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/persistentEnemyData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/persistentEnemyData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tpersistentEnemyData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\t// solNodes\n\turl := Dirpath + \"data/\" + id1 + \"/solNodes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"solNodes.json\"\n\t}\n\treq, err := os.Open(url)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tdefer req.Close()\n\tbody, _ := ioutil.ReadAll(req)\n\tfmt.Println(id1)\n\tvar result map[string]interface{}\n\tjson.Unmarshal([]byte(body), &result)\n\tSortieloc[id1] = result\n\n\t// sortieData\n\turl = Dirpath + \"data/\" + id1 + \"/sortieData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"sortieData.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\terr = json.Unmarshal(body, &Sortielang)\n\tSortiemodtypes[id1] = make(LangMap)\n\tSortiemodtypes[id1] = Sortielang[\"modifierTypes\"]\n\tSortiemoddesc[id1] = Sortielang[\"modifierDescriptions\"]\n\tSortiemodbosses[id1] = Sortielang[\"bosses\"]\n\n\t// FissureModifiers\n\turl = Dirpath + \"data/\" + id1 + \"/fissureModifiers.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"fissureModifiers.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFissureModifiers[id1] = result\n\n\t// MissionTypes\n\turl = Dirpath + \"data/\" + id1 + \"/missionTypes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"missionTypes.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tMissionTypes[id1] = result\n\n\t// languages\n\turl = Dirpath + \"data/\" + id1 + \"/languages.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"languages.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tLanguages[id1] = result\n\n\t// FactionsData\n\turl = Dirpath + \"data/\" + id1 + \"/factionsData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"factionsData.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFactionsData[id1] = result\n\n\t// sortieRewards\n\turl = Dirpath + \"data/\" + id1 + \"/sortieRewards.json\"\n\tif id1 != \"en\" {\n\t\t// url = \"https://drops.warframestat.us/data/sortieRewards.json\"\n\t\treturn\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tvar result2 string\n\n\tjson.Unmarshal([]byte(body), &result2)\n\tSortieRewards = body\n\n\t/*\n\t\t// syndicatesData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/syndicatesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/syndicatesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsyndicatesData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// synthTargets\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/synthTargets.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/synthTargets.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsynthTargets[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// upgradeTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/upgradeTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/upgradeTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tupgradeTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// warframes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/warframes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/warframes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\twarframes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// weapons\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/weapons.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/weapons.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tweapons[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\treturn\n}", "func checkLang() {\n\tif flag_lang == \"\" {\n\t\treturn\n\t}\n\n\tvar err error\n\tlangWant, err = parseLang(flag_lang)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid value %q for -lang: %v\", flag_lang, err)\n\t}\n\n\tif def := currentLang(); flag_lang != def {\n\t\tdefVers, err := parseLang(def)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"internal error parsing default lang %q: %v\", def, err)\n\t\t}\n\t\tif langWant.major > defVers.major || (langWant.major == defVers.major && langWant.minor > defVers.minor) {\n\t\t\tlog.Fatalf(\"invalid value %q for -lang: max known version is %q\", flag_lang, def)\n\t\t}\n\t}\n}", "func (a *App) updateViews() {\n\t// if a.state.Settings[\"TLDSubstitutions\"] {\n\t// \ta.writeView(viewSettings, \"[X] TLD substitutions\")\n\t// } else {\n\t// \ta.writeView(viewSettings, \"[ ] TLD substitutions\")\n\t// }\n}", "func langFetch(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tprintln(\"📝 Currently on Language Control page.\")\n\n\tglobals.Tmpl.ExecuteTemplate(w, \"langs_fetch.gohtml\", langCtrl.FetchLangs())\n}", "func goLanguages(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar langs Languages = getLanguages();\n\tif err := json.NewEncoder(w).Encode(langs); err != nil {\n\t\tpanic(err)\n\t}\n}", "func goLanguages(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\n\tvar langs Languages = getLanguages();\n\tif err := json.NewEncoder(w).Encode(langs); err != nil {\n\t\tpanic(err)\n\t}\n}", "func detectLanguage(in string, addrs []*ofac.Address) whatlanggo.Lang {\n\tinfo := whatlanggo.Detect(in)\n\tif info.IsReliable() {\n\t\t// Return the detected language if whatlanggo is confident enough\n\t\treturn info.Lang\n\t}\n\n\tif len(addrs) == 0 {\n\t\t// If no addresses are associated to this text blob then fallback to English\n\t\treturn whatlanggo.Eng\n\t}\n\n\t// Return the countries primary language associated to the primary address for this SDN.\n\t//\n\t// TODO(adam): Should we do this only if there's one address? If there are multiple should we\n\t// fallback to English or a mixed set?\n\tcountry, err := gountries.New().FindCountryByName(addrs[0].Country)\n\tif len(country.Languages) == 0 || err != nil {\n\t\treturn whatlanggo.Eng\n\t}\n\n\t// If the language is spoken in the country and we're somewhat confident in the original detection\n\t// then return that language.\n\tif info.Confidence > minConfidence {\n\t\tfor key := range country.Languages {\n\t\t\tif strings.EqualFold(key, info.Lang.Iso6393()) {\n\t\t\t\treturn info.Lang\n\t\t\t}\n\t\t}\n\t}\n\tif len(country.Languages) == 1 {\n\t\tfor key := range country.Languages {\n\t\t\treturn whatlanggo.CodeToLang(key)\n\t\t}\n\t}\n\n\t// How should we pick the language for countries with multiple languages? A hardcoded map?\n\t// What if we found the language whose name is closest to the country's name and returned that?\n\t//\n\t// Should this fallback be the mixed set that contains stop words from several popular languages\n\t// in the various data sets?\n\n\treturn whatlanggo.Eng\n}", "func ChangeLang(socketID uuid.UUID, lang int) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\tif _, ok := sessionCache[socketID]; ok && sessionCache[socketID].lang != lang {\n\t\tsessionVar := sessionCache[socketID]\n\t\tsessionVar.lang = lang\n\t\tsessionCache[socketID] = sessionVar\n\t}\n}", "func I18n(options ...Options) macaron.Handler {\n\topt := prepareOptions(options)\n\tinitLocales(opt)\n\treturn func(ctx *macaron.Context) {\n\t\tisNeedRedir := false\n\t\thasCookie := false\n\n\t\t// 1. Check URL arguments.\n\t\tlang := ctx.Query(opt.Parameter)\n\n\t\t// 2. Get language information from cookies.\n\t\tif len(lang) == 0 {\n\t\t\tlang = ctx.GetCookie(\"lang\")\n\t\t\thasCookie = true\n\t\t} else {\n\t\t\tisNeedRedir = true\n\t\t}\n\n\t\t// Check again in case someone modify by purpose.\n\t\tif !i18n.IsExist(lang) {\n\t\t\tlang = \"\"\n\t\t\tisNeedRedir = false\n\t\t\thasCookie = false\n\t\t}\n\n\t\t// 3. Get language information from 'Accept-Language'.\n\t\tif len(lang) == 0 {\n\t\t\tal := ctx.Req.Header.Get(\"Accept-Language\")\n\t\t\tif len(al) > 4 {\n\t\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\t\tif i18n.IsExist(al) {\n\t\t\t\t\tlang = al\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 4. Default language is the first element in the list.\n\t\tif len(lang) == 0 {\n\t\t\tlang = i18n.GetLangByIndex(0)\n\t\t\tisNeedRedir = false\n\t\t}\n\n\t\tcurLang := LangType{\n\t\t\tLang: lang,\n\t\t}\n\n\t\t// Save language information in cookies.\n\t\tif !hasCookie {\n\t\t\tctx.SetCookie(\"lang\", curLang.Lang, 1<<31-1, \"/\"+strings.TrimPrefix(opt.SubURL, \"/\"))\n\t\t}\n\n\t\trestLangs := make([]LangType, 0, i18n.Count()-1)\n\t\tlangs := i18n.ListLangs()\n\t\tnames := i18n.ListLangDescs()\n\t\tfor i, v := range langs {\n\t\t\tif lang != v {\n\t\t\t\trestLangs = append(restLangs, LangType{v, names[i]})\n\t\t\t} else {\n\t\t\t\tcurLang.Name = names[i]\n\t\t\t}\n\t\t}\n\n\t\t// Set language properties.\n\t\tlocale := Locale{i18n.Locale{lang}}\n\t\tctx.Map(locale)\n\t\tctx.Locale = locale\n\t\tctx.Data[opt.TmplName] = locale\n\t\tctx.Data[\"Tr\"] = i18n.Tr\n\t\tctx.Data[\"Lang\"] = locale.Lang\n\t\tctx.Data[\"LangName\"] = curLang.Name\n\t\tctx.Data[\"AllLangs\"] = append([]LangType{curLang}, restLangs...)\n\t\tctx.Data[\"RestLangs\"] = restLangs\n\n\t\tif opt.Redirect && isNeedRedir {\n\t\t\tctx.Redirect(opt.SubURL + ctx.Req.RequestURI[:strings.Index(ctx.Req.RequestURI, \"?\")])\n\t\t}\n\t}\n}", "func checkVersion(message string) string {\n\tfmt.Println(CarVersionMap)\n\tfor key, Val := range CarVersionMap {\n\t\tfmt.Println(strings.ToLower(key))\n\t\tfmt.Println(strings.ToLower(message))\n\t\tif strings.Contains(strings.ToLower(message), strings.ToLower(key)) {\n\t\t\tChatStage++\n\t\t\turl =\"https://egypt.yallamotor.com\"+Val\n\t\t\tfmt.Println(url)\n\t\t\tUser.CarPerson.Version = strings.ToLower(key)\n\t\t\tfmt.Println(User.CarPerson.Version)\n\t\t\tfmt.Println(User)\n\t\t\t//retturn 3la to karims method\n\t\t\treturn finalresult()\n\t\t}\n\t\n}\n\t\t\t\treturn \"mesh fahem bardo 3ayez anhy version meen dool\"\n\n}", "func detectDirLangsByEnryLib(dir string) Languages {\n\n\tlangMap := make(map[string]float64, 0)\n\n\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\tif !f.Mode().IsDir() && !f.Mode().IsRegular() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif isDiceLogo := func(path string, f os.FileInfo) bool {\n\t\t\tif f.IsDir() {\n\t\t\t} else {\n\t\t\t\t// SPA\n\t\t\t\tif f.Name() == bptype.DICE_SPA_MARK {\n\t\t\t\t\tlangMap[bptype.DICE_SPA] += -float64(f.Size())\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\t// Herd\n\t\t\t\tif f.Name() == bptype.HERD_MARK {\n\t\t\t\t\tcontent, err := readFile(path, -1)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\tif strings.Contains(string(content), \"herd \") {\n\t\t\t\t\t\tlangMap[bptype.HERD] += -float64(f.Size())\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// root of dir\n\t\t\t\tif filepath.Dir(path) == dir {\n\t\t\t\t\tif f.Name() == bptype.DICE_DOCKERFILE_MARK {\n\t\t\t\t\t\tcontent, err := readFile(path, -1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif strings.Contains(string(content), \"#!dice\") ||\n\t\t\t\t\t\t\tstrings.Contains(string(content), \"# dice-tags: dice-buildpack-dockerfile\") {\n\t\t\t\t\t\t\tlangMap[bptype.DICE_DOCKERFILE] += -float64(f.Size())\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif f.Name() == bptype.TOMCAT_MARK {\n\t\t\t\t\t\tcontent, err := readFile(path, -1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif strings.Contains(string(content), \"<packaging>war</packaging>\") {\n\t\t\t\t\t\t\tlangMap[bptype.TOMCAT] += -float64(f.Size())\n\t\t\t\t\t\t\treturn true\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\treturn false\n\t\t}(path, f); isDiceLogo {\n\t\t\treturn nil\n\t\t}\n\n\t\trelativePath, err := filepath.Rel(dir, path)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif relativePath == \".\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tif f.IsDir() {\n\t\t\trelativePath = relativePath + \"/\"\n\t\t}\n\n\t\tif enry.IsVendor(relativePath) || enry.IsDotFile(relativePath) ||\n\t\t\tenry.IsDocumentation(relativePath) || enry.IsConfiguration(relativePath) {\n\t\t\tif f.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif f.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tlang, ok := enry.GetLanguageByExtension(path)\n\t\tif !ok {\n\t\t\tif lang, ok = enry.GetLanguageByFilename(path); !ok {\n\t\t\t\tcontent, err := readFile(path, int64(16*1024*1024))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tlang := enry.GetLanguage(filepath.Base(path), content)\n\t\t\t\tif lang == enry.OtherLanguage {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// NOTE: check enry.IsConfiguration etc above\n\t\tcanForcePass := func(lang string) bool {\n\t\t\tswitch strings.ToLower(lang) {\n\t\t\tcase \"dockerfile\":\n\t\t\t\treturn true\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\t// only programming Language\n\t\tif enry.GetLanguageType(lang) != enry.Programming {\n\t\t\t// some Language is not programming Language but pass\n\t\t\tif !canForcePass(lang) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tlangMap[lang] += float64(f.Size())\n\n\t\treturn nil\n\t})\n\n\t// get total count\n\tvar total float64\n\tfor _, count := range langMap {\n\t\tif count > 0 {\n\t\t\ttotal += count\n\t\t}\n\t}\n\n\tvar langs Languages\n\tfor lang, count := range langMap {\n\t\tper, err := strconv.ParseFloat(fmt.Sprintf(\"%.4f\", count/total*100.00), 64)\n\t\tif err != nil {\n\t\t\tper = float64(count) / float64(total) * 100.00\n\t\t}\n\t\tlangs = append(langs, Language{Type: lang, Percent: per, Internal: bptype.IsInternalLang(lang)})\n\t}\n\n\t// order by Language.Percent desc\n\tsort.Sort(sort.Reverse(langs))\n\n\treturn langs\n}", "func initLocales(opt Options) {\n\tfor i, lang := range opt.Langs {\n\t\tfname := fmt.Sprintf(opt.Format, lang)\n\t\t// Append custom locale file.\n\t\tcustom := []interface{}{}\n\t\tcustomPath := path.Join(opt.CustomDirectory, fname)\n\t\tif com.IsFile(customPath) {\n\t\t\tcustom = append(custom, customPath)\n\t\t}\n\n\t\tvar locale interface{}\n\t\tif data, ok := opt.Files[fname]; ok {\n\t\t\tlocale = data\n\t\t} else {\n\t\t\tlocale = path.Join(opt.Directory, fname)\n\t\t}\n\n\t\terr := i18n.SetMessageWithDesc(lang, opt.Names[i], locale, custom...)\n\t\tif err != nil && err != i18n.ErrLangAlreadyExist {\n\t\t\tpanic(fmt.Errorf(\"fail to set message file(%s): %v\", lang, err))\n\t\t}\n\t}\n}", "func (g *Generator) UseLangWordlist(lang string) error {\n\tvar ok bool\n\tg.wordlist, ok = wordlists[lang]\n\tif !ok {\n\t\treturn fmt.Errorf(\"language \\\"%s\\\" has no matching wordlist\", lang)\n\t}\n\treturn nil\n}", "func (_obj *Apilangpack) Langpack_getLanguages(params *TLlangpack_getLanguages, _opt ...map[string]string) (ret []LangPackLanguage, 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, \"langpack_getLanguages\", _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, have, ty = _is.SkipToNoCheck(0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\tret = make([]LangPackLanguage, length)\n\t\tfor i10, e10 := int32(0), length; i10 < e10; i10++ {\n\n\t\t\terr = ret[i10].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\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 (c *Translations) getMinialConfigsFromOSEnv() bool {\n\n\tcheck := false\n\n\tif c.FlowDirection == \"\" {\n\t\tc.FlowStartSysUpTime = \"flowStartSysUpTime, flowStartMilliseconds\"\n\t\tcheck = true\n\t}\n\n\tif c.FlowEndSysUpTime == \"\" {\n\t\tc.FlowEndSysUpTime = \"flowEndSysUpTime, flowEndMilliseconds\"\n\t\tcheck = true\n\t}\n\n\tif c.OctetDeltaCount == \"\" {\n\t\tc.OctetDeltaCount = \"octetDeltaCount, octetTotalCount\"\n\t\tcheck = true\n\t}\n\n\tif c.PacketDeltaCount == \"\" {\n\t\tc.PacketDeltaCount = \"packetDeltaCount, packetTotalCount\"\n\t\tcheck = true\n\t}\n\n\tif c.IngressInterface == \"\" {\n\t\tc.IngressInterface = \"ingressInterface, ingressPhysicalInterface\"\n\t\tcheck = true\n\t}\n\n\tif c.EgressInterface == \"\" {\n\t\tc.EgressInterface = \"egressInterface, egressPhysicalInterface\"\n\t\tcheck = true\n\t}\n\n\tif c.IpNextHopIPv4Address == \"\" {\n\t\tc.IpNextHopIPv4Address = \"ipNextHopIPv4Address\"\n\t\tcheck = true\n\t}\n\n\tif c.SourceIPv4Address == \"\" {\n\t\tc.SourceIPv4Address = \"sourceIPv4Address\"\n\t\tcheck = true\n\t}\n\n\tif c.DestinationIPv4Address == \"\" {\n\t\tc.DestinationIPv4Address = \"destinationIPv4Address\"\n\t\tcheck = true\n\t}\n\n\tif c.ProtocolIdentifier == \"\" {\n\t\tc.ProtocolIdentifier = \"protocolIdentifier\"\n\t\tcheck = true\n\t}\n\n\tif c.SourceTransportPort == \"\" {\n\t\tcheck = true\n\t\tc.SourceTransportPort = \"sourceTransportPort\"\n\t}\n\n\tif c.DestinationTransportPort == \"\" {\n\t\tcheck = true\n\t\tc.DestinationTransportPort = \"destinationTransportPort\"\n\t}\n\n\tif c.TcpControlBits == \"\" {\n\t\tc.TcpControlBits = \"tcpControlBits\"\n\t\tcheck = true\n\t}\n\n\tif c.FlowDirection == \"\" {\n\t\tcheck = true\n\t\tc.FlowDirection = \"flowDirection\"\n\t}\n\n\tif c.SourceIPv4PrefixLength == \"\" {\n\t\tcheck = true\n\t\tc.SourceIPv4PrefixLength = \"sourceIPv4PrefixLength\"\n\t}\n\n\tif c.DestinationIPv4PrefixLength == \"\" {\n\t\tcheck = true\n\t\tc.DestinationIPv4PrefixLength = \"destinationIPv4PrefixLength\"\n\t}\n\n\treturn check\n\n}", "func (y *Handler) setLanguages(ctx context.Context, direction string) error {\n\tfromLanguage, toLanguage, err := y.detectLanguages(ctx, direction, y.text)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif knowLanguages(fromLanguage, toLanguage) {\n\t\ty.fromLanguage, y.toLanguage = fromLanguage, toLanguage\n\t\treturn nil\n\t}\n\n\tlanguages, err := y.loadLanguages(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not set languages: %w\", err)\n\t}\n\n\tif !languages.Contains(fromLanguage, toLanguage) {\n\t\treturn fmt.Errorf(\"unknown language direction: %s -> %s\\n%v\", fromLanguage, toLanguage, languages.String())\n\t}\n\n\ty.fromLanguage, y.toLanguage = fromLanguage, toLanguage\n\treturn nil\n}", "func (e *HTMLApplet) Lang(v string) *HTMLApplet {\n\te.a[\"lang\"] = v\n\treturn e\n}", "func (g *Goi18n) add(lc *locale) bool {\n\tif _, ok := g.localeMap[lc.lang]; ok {\n\t\treturn false\n\t}\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tif err := lc.Reload(g.option.Path); err != nil {\n\t\treturn false\n\t}\n\tlc.id = len(g.localeMap)\n\tg.localeMap[lc.lang] = lc\n\tg.langs = append(g.langs, lc.lang)\n\tg.langDescs[lc.lang] = lc.langDesc\n\treturn true\n}", "func openLangJSON(updated interface{}) CustError {\n\tfile, err := ioutil.ReadFile(\"languages.json\")\n\n\t// Failed reading the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to load local file: languages.json\"}\n\t}\n\n\terr = json.Unmarshal(file, &updated)\n\n\t// Failed unmarshaling the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to unmarshal local file: languages.json\"}\n\t}\n\n\t// Nothing bad happened\n\treturn CustError{0, errorStr[0]}\n}", "func ChangeDigitLanguage(str *string, lang string) {\n\tconfigStr := \"language.\" + lang + \".\"\n\tfor _, c := range *str {\n\t\tcs := string(c)\n\t\tif IsDigit(cs) {\n\t\t\tchar := viper.GetString(configStr + cs)\n\t\t\t*str = strings.Replace(*str, cs, char, -1)\n\t\t}\n\t}\n}", "func (a *Api) refreshLocal(res http.ResponseWriter, req *http.Request, vars map[string]string) {\n\tlog.Println(\"refresh locales files from remote system!\")\n\tsuccess := a.localeManager.DownloadLocales(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif !success {\n\t\tlog.Printf(\"error while retriving locales from localizer service!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlocalizer, err := localize.NewI18nLocalizer(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading locales files!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\temailTemplates, err := templates.New(a.Config.I18nTemplatesPath, localizer)\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading templates!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\ta.templates = emailTemplates\n}", "func handleSentence(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf( w, \"<h1>%s</h1>\\n\", \"Endpoint for gopher Sentence translation\" )\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tfmt.Println(readErr)\n\t\treturn\n\t}\n\n\tsentence := Sentence{}\n\terr := json.Unmarshal(body, &sentence)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tsen := strings.Split(sentence.Sentence, \" \")\n\n\tvar gophSen []string\n\tfor i := range sen {\n\t\tif strings.IndexAny(sen[i], \".,!?\") != -1 {\n\t\t\tword, sign := separateSign(sen[i])\n\t\t\tgoph, err := translateWord(word)\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\tgophSen = append(gophSen, goph + sign)\n\t\t} else {\n\t\t\tgoph, err := translateWord(sen[i])\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\tgophSen = append(gophSen, goph )\n\t\t}\n\t}\n\n\tgS := strings.Join(gophSen, \" \")\n\n\ttextBytes, err := json.Marshal(map[string]interface{}{\"gopher-sentence\": gS})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgopherTranslated := string(textBytes)\n\tfmt.Println(gopherTranslated)\n\tfmt.Fprintf( w, \"<h3>%s</h3>\\n\",gopherTranslated )\n}", "func (E_OpenconfigOfficeAp_System_SshServer_Config_ProtocolVersion) IsYANGGoEnum() {}", "func main() {\n\t//predef of 4 languages\n\tlanguages[0] = \"english\"\n\tlanguages[1] = \"日本語\"\n\tlanguages[2] = \"deutsch\"\n\tlanguages[3] = \"svenska\"\n\n\t//starting client\n\tclient()\n}", "func (session *session) updateFrontendOptions(request *irma.FrontendOptionsRequest) (*irma.SessionOptions, error) {\n\tif session.Status != irma.ServerStatusInitialized {\n\t\treturn nil, errors.New(\"Frontend options can only be updated when session is in initialized state\")\n\t}\n\tif request.PairingMethod == \"\" {\n\t\treturn &session.Options, nil\n\t} else if request.PairingMethod == irma.PairingMethodNone {\n\t\tsession.Options.PairingCode = \"\"\n\t} else if request.PairingMethod == irma.PairingMethodPin {\n\t\tsession.Options.PairingCode = common.NewPairingCode()\n\t} else {\n\t\treturn nil, errors.New(\"Pairing method unknown\")\n\t}\n\tsession.Options.PairingMethod = request.PairingMethod\n\treturn &session.Options, nil\n}", "func (_obj *Apilangpack) Langpack_getLanguageOneWayWithContext(tarsCtx context.Context, params *TLlangpack_getLanguage, _opt ...map[string]string) (ret LangPackLanguage, 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\n\terr = _obj.s.Tars_invoke(tarsCtx, 1, \"langpack_getLanguage\", _os.ToBytes(), _status, _context, _resp)\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 DeepLTranslate(txt []string, cfg config.File) []string {\n\tvar reqURL string\n\tif cfg.Translation.DeepL.Premium {\n\t\treqURL = \"https://api.deepl.com/v2/translate\"\n\t} else {\n\t\treqURL = \"https://api-free.deepl.com/v2/translate\"\n\t}\n\n\tparams := url.Values{}\n\tfor i := range txt {\n\t\tparams.Add(\"text\", txt[i])\n\t}\n\tparams.Add(\"auth_key\", cfg.Translation.DeepL.APIKey)\n\tparams.Add(\"source_lang\", `JA`)\n\tparams.Add(\"target_lang\", `EN`)\n\treqBody := strings.NewReader(params.Encode())\n\n\tresp, err := http.Post(reqURL, \"application/x-www-form-urlencoded\", reqBody)\n\tif err != nil {\n\t\tlog.Errorf(\"http.Post: %v\", err)\n\t\treturn TranslationError(\"Translation request failed, ensure that your internet connection is stable.\", txt)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Debugf(\"Translation request response: %v\", resp)\n\n\tdata, err2 := ioutil.ReadAll(resp.Body)\n\tif err2 != nil {\n\t\tlog.Errorf(\"Error reading response body: %v \\n\", err2)\n\t\treturn TranslationError(\"Translation request failed, ensure that your internet connection is stable and your API key is correct.\", txt)\n\t}\n\n\t// Empty response body, something went wrong.\n\tif len(data) == 0 {\n\t\tlog.Error(\"Empty response body from translation request\")\n\t\treturn TranslationError(\"Translation request failed, ensure that your API key is correct.\", txt)\n\t}\n\n\tvar jsonData DeepLResponse\n\tif err := json.Unmarshal(data, &jsonData); err != nil {\n\t\tlog.Errorf(\"Parse response failed: %v\", err)\n\t\treturn TranslationError(\"Translation request failed, ensure that your internet connection is stable and your API key is correct.\", txt)\n\t}\n\tlog.Debugf(\"Translation response body: %v\", jsonData)\n\n\tif !(resp.StatusCode >= 200 && resp.StatusCode <= 299) {\n\t\tlog.Error(\"Non-200 status code\")\n\t\tif strings.HasPrefix(jsonData.Message, \"Wrong endpoint.\") {\n\t\t\t// Wrong tier in config, fix the config and retry.\n\t\t\tlog.Warning(\"Wrong DeepL translation tier selected. Fixing config file.\")\n\t\t\tcfg.Translation.DeepL.Premium = !cfg.Translation.DeepL.Premium\n\t\t\tconfig.SaveConfig(cfg)\n\t\t\treturn DeepLTranslate(txt, cfg)\n\t\t}\n\n\t\treturn TranslationError(\"Translation request failed, ensure that your API key is correct.\", txt)\n\t}\n\n\tvar translated []string\n\tfor _, t := range jsonData.Translations {\n\t\ttranslated = append(translated, t.Text)\n\t}\n\n\tlog.WithField(\"text\", translated).Info(\"Translated Text\")\n\n\treturn translated\n}", "func SetLang(newLang string) error {\n\tfound := false\n\tfor _, l := range availLangs {\n\t\tif newLang == l {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn ErrNoLanguageFn(newLang)\n\t}\n\tlang = newLang\n\treturn nil\n}", "func currentLang() string {\n\treturn fmt.Sprintf(\"go1.%d\", goversion.Version)\n}", "func ChangePreferedLanguage(r *http.Request) {\n\tvar matcher = language.NewMatcher([]language.Tag{\n\t\tlanguage.English, // The first language is used as fallback.\n\t\tlanguage.Chinese,\n\t})\n\n\taccept := r.Header.Get(\"Accept-Language\")\n\ttag, _ := language.MatchStrings(matcher, accept)\n\tif strings.HasPrefix(tag.String(), \"zh\") {\n\t\tchangeLocale(\"zh_CN\")\n\t} else {\n\t\tchangeLocale(\"en_US\")\n\t}\n}", "func setTranslateAddr(resp http.ResponseWriter, active bool) {\n\tif active {\n\t\tresp.Header().Set(\"X-Consul-Translate-Addresses\", \"true\")\n\t}\n}", "func usage(dictPath string) {\n fmt.Println(\"Usage:\")\n flag.PrintDefaults()\n fmt.Println(\"\")\n fmt.Println(\"Available languages\")\n fmt.Println(\"===================\")\n filepath.Walk(\n dictPath,\n func(path string, f os.FileInfo, err error) error {\n if !f.IsDir() && f.Mode()&os.ModeSymlink == 0 && f.Name() != \"README.select-wordlist\"{\n fmt.Printf(\" - %s\\n\", f.Name())\n }\n return nil\n },\n )\n}", "func (h *MemHome) Lang(path string) Lang { return h.langs.lang(path) }", "func (_obj *Apilangpack) Langpack_getDifference(params *TLlangpack_getDifference, _opt ...map[string]string) (ret LangPackDifference, 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, \"langpack_getDifference\", _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 (y *Handler) loadLanguages(ctx context.Context) (result.Languages, error) {\n\tif y.isDictionary {\n\t\treturn dictionary.LoadLanguages(ctx, y.client, y.config)\n\t}\n\treturn translation.LoadLanguages(ctx, y.client, y.config)\n}", "func handleUpdateSettings(msg []byte, id int) {\n\t// decode JSON request\n\tvar request UpdateSettingsRequest\n\terr := json.Unmarshal(msg, &request)\n\tif err != nil {\n\t\tresponse := UpdateSettingsResponse{OK: false, Cmd: \"setting\", Setting: request.Setting}\n\t\tsendJsonToOnlineID(id, &response)\n\t\treturn\n\t}\n\n\t// update database\n\tif request.Setting.Sign != \"\" {\n\t\terr = database.SetSignature(id, request.Setting.Sign)\n\t\tif err != nil {\n\t\t\tresponse := UpdateSettingsResponse{OK: false, Cmd: \"setting\", Setting: request.Setting}\n\t\t\tsendJsonToOnlineID(id, &response)\n\t\t\treturn\n\t\t}\n\t}\n\tif request.Setting.Avatar != \"\" {\n\t\terr = database.SetAvatar(id, request.Setting.Avatar)\n\t\tif err != nil {\n\t\t\tresponse := UpdateSettingsResponse{OK: false, Cmd: \"setting\", Setting: request.Setting}\n\t\t\tsendJsonToOnlineID(id, &response)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// 通知朋友\n\tfriendships, err := database.GetFriendships(id)\n\tif err == nil {\n\t\tif request.Setting.Sign != \"\" {\n\t\t\tfor i := 0; i < len(friendships); i++ {\n\t\t\t\tfmt.Printf(\"%d 通知 %d 換簽名檔\\n\", id, friendships[i].FriendID)\n\t\t\t\tsendJsonToUnknownStatusID(\n\t\t\t\t\tfriendships[i].FriendID,\n\t\t\t\t\tSignCmd{Cmd: \"change_sign\", Who: id, Sign: request.Setting.Sign},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif request.Setting.Avatar != \"\" {\n\t\t\tfor i := 0; i < len(friendships); i++ {\n\t\t\t\tfmt.Printf(\"%d 通知 %d 換大頭貼\\n\", id, friendships[i].FriendID)\n\t\t\t\tsendJsonToUnknownStatusID(\n\t\t\t\t\tfriendships[i].FriendID,\n\t\t\t\t\tAvatarCmd{Cmd: \"change_avatar\", Who: id, Avatar: request.Setting.Avatar},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"getFriendships: %s\", err.Error())\n\t}\n\t// send success response\n\tresponse := UpdateSettingsResponse{OK: true, Cmd: \"setting\", Setting: request.Setting}\n\tsendJsonToOnlineID(id, &response)\n}", "func descargarlocal(message dn_proto.PropRequest){\n\tmensaje := dn_proto.ChunkRequest{}\n\tpaldn1, err := strconv.Atoi(message.Cantidadn1) \n\tif err != nil {\n\t\tlog.Fatalf(\"Error convirtiendo: %s\", err)\n\t}\n\tpaldn2, err := strconv.Atoi(message.Cantidadn2) \n\tif err != nil {\n\t\tlog.Fatalf(\"Error convirtiendo: %s\", err)\n\t}\n\tpart2 := \"\" \n\tcontdn2 := 0 \n\tfor{\n\t\tif paldn2 != 0 && contdn2 < paldn2 {\n\t\t\taux := paldn1+contdn2+1\n\t\t\tpart2 = strconv.Itoa(aux)\n\t\t\tmensaje = dn_proto.ChunkRequest{\n\t\t\t\tChunk: libroactual[paldn1+contdn2].chunks,\n\t\t\t\tParte: part2,\n\t\t\t\tCantidad: message.Cantidadtotal,\n\t\t\t\tNombrel: message.Nombrel,\n\t\t\t}\n\t\t\tcontdn2 = contdn2 + 1\n\t\t}else{\n\t\t\tbreak\n\t\t}\n\t\tparteaux, err := strconv.Atoi(mensaje.Parte)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error convirtiendo: %s\", err)\n\t\t}\n\t\tparteaux = parteaux - 1\n\t\tpartee := strconv.Itoa(parteaux)\n\t\tfileName := \"chunks/\" + mensaje.Nombrel + \"_\" + partee\n\t\t_, err = os.Create(fileName)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tioutil.WriteFile(fileName, mensaje.Chunk, os.ModeAppend)\n\t}\n\tvar librovacio []Pagina\n\tlibroactual = librovacio\n}", "func NotifyUILanguageChange(dwFlags DWORD, pcwstrNewLanguage string, pcwstrPreviousLanguage string, dwReserved DWORD, pdwStatusRtrn *DWORD) bool {\n\tpcwstrNewLanguageStr := unicode16FromString(pcwstrNewLanguage)\n\tpcwstrPreviousLanguageStr := unicode16FromString(pcwstrPreviousLanguage)\n\tret1 := syscall6(notifyUILanguageChange, 5,\n\t\tuintptr(dwFlags),\n\t\tuintptr(unsafe.Pointer(&pcwstrNewLanguageStr[0])),\n\t\tuintptr(unsafe.Pointer(&pcwstrPreviousLanguageStr[0])),\n\t\tuintptr(dwReserved),\n\t\tuintptr(unsafe.Pointer(pdwStatusRtrn)),\n\t\t0)\n\treturn ret1 != 0\n}", "func DetectDirLangs(dir string) Languages {\n\t//langs, err := detectDirLangsByEnryCmd(dir)\n\t//if err == nil {\n\t//\treturn langs\n\t//}\n\treturn detectDirLangsByEnryLib(dir)\n}", "func loadLangInfo(fn string) (li *LangInfo, err error) {\n fin, err := os.Open(fn)\n if err != nil {return}\n defer fin.Close()\n bn := filepath.Base(fn)\n dat := strings.Split(bn, \".\")\n if len(dat) != 3 || dat[2] != \"lm\" {\n return nil, errors.New(\"bad format filename: \" + bn)\n }\n li = &LangInfo{fmap:make(map[string]int)}\n i, err := strconv.ParseInt(dat[1], 10, 16)\n if err != nil {\n return nil, err\n }\n li.id, li.name = int(i), dat[0]\n cnt := 0\n scanner := bufio.NewScanner(fin)\n for scanner.Scan() {\n cols := splitByByte(scanner.Text(), []byte(\" \\r\\n\\t\"))\n li.fmap[strings.TrimSpace(cols[0])] = cnt\n cnt++\n if cnt >= lMax {break}\n }\n return\n}", "func (cc *CommonController) SwitchLanguage() {\n\tlang := cc.GetString(\"lang\")\n\thash := cc.GetString(\"hash\")\n\tif _, exist := supportLanguages[lang]; !exist {\n\t\tlang = defaultLang\n\t}\n\tcc.SetSession(\"lang\", lang)\n\tcc.Data[\"Lang\"] = lang\n\tcc.Redirect(cc.Ctx.Request.Header.Get(\"Referer\")+hash, http.StatusFound)\n}", "func updateConfig() {\n\t// going to v1 apply these changes\n\tif instance.CfgVersion < 1 {\n\t\t// new known mod extension\n\t\tif !strings.Contains(instance.ModExtensions, \".pke\") {\n\t\t\tinstance.ModExtensions = instance.ModExtensions + \".pke\"\n\t\t}\n\t\t// additional known iwads\n\t\tinstance.IWADs = append(instance.IWADs, \"boa.ipk3\", \"plutonia.wad\", \"tnt.wad\", \"heretic.wad\")\n\t}\n\n\t// v2\n\tif instance.CfgVersion < 2 {\n\t\tif !strings.Contains(instance.ModExtensions, \".zip\") {\n\t\t\tinstance.ModExtensions = instance.ModExtensions + \".zip\"\n\t\t}\n\t}\n\n\tinstance.CfgVersion = CFG_VERSION\n\tgo Persist()\n}", "func conf_ISOlanguages() []string {\n\tconf = createorreturnconfig(conf)\n\tlanguages := []string{}\n\tfor key, _ := range conf.Languages {\n\t\tlanguages = append(languages, key)\n\t}\n\tsort.Strings(languages)\n\treturn languages\n}", "func (c *Client) UpdateResLang(rl *ResLang) error {\n\treturn c.UpdateResLangs([]int64{rl.Id.Get()}, rl)\n}", "func (_obj *Apilangpack) Langpack_getLanguageWithContext(tarsCtx context.Context, params *TLlangpack_getLanguage, _opt ...map[string]string) (ret LangPackLanguage, 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\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"langpack_getLanguage\", _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 (c *Lang) cleanLang(code string) error {\n\ts := c.langFileName(\"tmp_dir\", code)\n\terr := ioutil.WriteFile(s, []byte(\"[]\"), 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(s)\n\treturn i18n.LoadTranslationFile(s)\n}", "func updateDemoTraffic(icao uint32, tail string, relAlt float32, gs float64, offset int32) {\n\tvar ti TrafficInfo\n\n\t// Retrieve previous information on this ICAO code.\n\tif val, ok := traffic[icao]; ok { // if we've already seen it, copy it in to do updates\n\t\tti = val\n\t\t//log.Printf(\"Existing target %X imported for ES update\\n\", icao)\n\t} else {\n\t\t//log.Printf(\"New target %X created for ES update\\n\",newTi.Icao_addr)\n\t\tti.Last_seen = stratuxClock.Time // need to initialize to current stratuxClock so it doesn't get cut before we have a chance to populate a position message\n\t\tti.Icao_addr = icao\n\t\tti.ExtrapolatedPosition = false\n\t}\n\thdg := float64((int32(stratuxClock.Milliseconds/1000)+offset)%720) / 2\n\t// gs := float64(220) // knots\n\tradius := gs * 0.2 / (2 * math.Pi)\n\tx := radius * math.Cos(hdg*math.Pi/180.0)\n\ty := radius * math.Sin(hdg*math.Pi/180.0)\n\t// default traffic location is Oshkosh if GPS not detected\n\tlat := 43.99\n\tlng := -88.56\n\tif isGPSValid() {\n\t\tlat = float64(mySituation.GPSLatitude)\n\t\tlng = float64(mySituation.GPSLongitude)\n\t}\n\ttraffRelLat := y / 60\n\ttraffRelLng := -x / (60 * math.Cos(lat*math.Pi/180.0))\n\n\tti.Icao_addr = icao\n\tti.OnGround = false\n\tti.Addr_type = uint8(icao % 4) // 0 == ADS-B; 1 == reserved; 2 == TIS-B with ICAO address; 3 == TIS-B without ICAO address; 6 == ADS-R\n\tif ti.Addr_type == 1 { // reassign \"reserved value\" to ADS-R\n\t\tti.Addr_type = 6\n\t}\n\n\tif ti.Addr_type == 0 {\n\t\tti.TargetType = TARGET_TYPE_ADSB\n\t} else if ti.Addr_type == 3 {\n\t\tti.TargetType = TARGET_TYPE_TISB\n\t} else if ti.Addr_type == 6 {\n\t\tti.TargetType = TARGET_TYPE_ADSR\n\t} else if ti.Addr_type == 2 {\n\t\tti.TargetType = TARGET_TYPE_TISB_S\n\t\tif (ti.NIC >= 7) && (ti.Emitter_category > 0) { // If NIC is sufficiently high and emitter type is transmitted, we'll assume it's ADS-R.\n\t\t\tti.TargetType = TARGET_TYPE_ADSR\n\t\t}\n\t}\n\n\tti.Emitter_category = 1\n\tti.Lat = float32(lat + traffRelLat)\n\tti.Lng = float32(lng + traffRelLng)\n\n\tti.Distance, ti.Bearing = distance(float64(lat), float64(lng), float64(ti.Lat), float64(ti.Lng))\n\tti.BearingDist_valid = true\n\n\tti.Position_valid = true\n\tti.ExtrapolatedPosition = false\n\tti.Alt = int32(mySituation.GPSAltitudeMSL + relAlt)\n\tti.Track = uint16(hdg)\n\tti.Speed = uint16(gs)\n\tif hdg >= 240 && hdg < 270 {\n\t\tti.OnGround = true\n\t}\n\tif hdg > 135 && hdg < 150 {\n\t\tti.Speed_valid = false\n\t} else {\n\t\tti.Speed_valid = true\n\t}\n\tti.Vvel = 0\n\tti.Tail = tail // \"DEMO1234\"\n\tti.Timestamp = time.Now()\n\tti.Last_seen = stratuxClock.Time\n\tti.Last_alt = stratuxClock.Time\n\tti.Last_speed = stratuxClock.Time\n\tti.NACp = 8\n\tti.NIC = 8\n\n\t//ti.Age = math.Floor(ti.Age) + hdg / 1000\n\tti.Last_source = 1\n\tif icao%5 == 1 { // make some of the traffic look like it came from UAT\n\t\tti.Last_source = 2\n\t}\n\n\tif hdg < 150 || hdg > 240 {\n\t\t// now insert this into the traffic map...\n\t\ttrafficMutex.Lock()\n\t\tdefer trafficMutex.Unlock()\n\t\ttraffic[ti.Icao_addr] = ti\n\t\tregisterTrafficUpdate(ti)\n\t\tseenTraffic[ti.Icao_addr] = true\n\t}\n}", "func (th *translationHandler) TranslateSentence(w http.ResponseWriter, r *http.Request) {\n\tenglish := &data.English{}\n\n\terr := th.codec.Decode(r, english)\n\n\tif err != nil {\n\t\tth.logger.Fatal(err)\n\t}\n\n\tvar gopherSentence string\n\tregex := regexp.MustCompile(`[a-z]+`)\n\twords := regex.FindAllString(english.Sentence, -1)\n\t\n\tfor _, word := range words {\n\t\tenglish.Word = word\n\t\tgopherWord := th.translate(english)\n\t\tgopherSentence += gopherWord + helpers.EmptySpace\n\t}\n\t\n\tlastIndex := len(english.Sentence) - 1\n\tsentenceSign := english.Sentence[lastIndex]\n\tgopherSentence = gopherSentence[:lastIndex] + string(sentenceSign)\n\n\tif !th.doesKeyExistInDb(english.Sentence) {\n\t\tth.pushKeyIntoDb(english.Sentence, gopherSentence)\n\t}\n\n\tth.codec.Encode(w, &data.Gopher{Sentence: gopherSentence})\n}", "func main() {\n\tflag.Parse()\n\n\t/////\n\taliveTimer = time.Now()\n\n\tlginfo.Init()\n\n\t// parse server ip need valid\n\tserverIp := net.ParseIP(server);\n\tserverAdd := net.UDPAddr{\n\t\tIP: serverIp,\n\t\tPort: 38302,\n\t}\n\n\t// 本机地址\n\thostIp := net.ParseIP(host)\n\thostAdd := net.UDPAddr{\n\t\tIP: hostIp,\n\t\tPort: 38300,\n\t}\n\t// Can卡固定IP\n\tcanAddr := net.UDPAddr{\n\t\tIP: net.IPv4(192, 168, 1, 10),\n\t\tPort: 8002,\n\t}\n\tlg, err := net.DialUDP(\"udp\", nil, &serverAdd)\n\ttool.CheckError(err)\n\tcan, err := net.DialUDP(\"udp\", &hostAdd, &canAddr)\n\ttool.CheckError(err)\n\n\tdefer lg.Close()\n\tdefer can.Close()\n\n\t//\n\tgo rpc.KeepAlive(lg)\n\tgo timeOutHandler();\n\tgo writeToVehicle(can)\n\t//go read(can)\n\n\tbuf := make([]byte, 12)\n\tfor {\n\t\t_, err := lg.Read(buf)\n\t\tif err != nil {\n\t\t\tfmt.Print(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// 读取 状态\n\t\tlginfo.ReadDriver(buf)\n\t\taliveTimer = time.Now()\n\t\t// 反馈状态\n\t\tlg.Write(lginfo.Pong(1))\n\t}\n\n}", "func (e *Env) loe(err error) {\n\tif err != nil {\n\t\te.log.Warn(err)\n\t}\n}", "func (E_OpenconfigSystem_System_SshServer_Config_ProtocolVersion) IsYANGGoEnum() {}", "func main() {\n\topts := make([]uconfig.YAMLOption, 0)\n\topts = append(opts, uconfig.Static(defaultConfig))\n\topts = append(opts, uconfig.Expand(os.LookupEnv))\n\tif configFile != \"\" {\n\t\topts = append(opts, uconfig.File(configFile))\n\t}\n\tif envConfig, ok := os.LookupEnv(\"WITNESS_CONFIG\"); ok {\n\t\topts = append(opts, uconfig.RawSource(strings.NewReader(envConfig)))\n\t}\n\tyaml, err := uconfig.NewYAML(opts...)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tvar cfg Configuration\n\tif err := yaml.Get(uconfig.Root).Populate(&cfg); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif url, ok := os.LookupEnv(\"WITNESS_DB_URL\"); ok {\n\t\tcfg.DB.URL = url\n\t}\n\tif client, ok := os.LookupEnv(\"WITNESS_ETH_CLIENT\"); ok {\n\t\tcfg.Ethereum.Client = client\n\t}\n\tif pk, ok := os.LookupEnv(\"WITNESS_ETH_PRIVATE_KEY\"); ok {\n\t\tcfg.Ethereum.PrivateKey = pk\n\t}\n\tif pk, ok := os.LookupEnv(\"WITNESS_IOTEX_PRIVATE_KEY\"); ok {\n\t\tcfg.IoTeX.PrivateKey = pk\n\t}\n\tutil.SetSlackURL(cfg.SlackWebHook)\n\tauth, witnessOnIoTeX, witnessOnEthereum, err := createWitnessServices(cfg)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tlog.Println(\"Starting fetching auth data\")\n\trefresher, err := dispatcher.NewRunner(cfg.RefreshInterval, auth.Refresh)\n\tif err := refresher.Start(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer refresher.Close()\n\tfor {\n\t\tif auth.LastUpdateTime().After(time.Time{}) {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\tlog.Println(\"Starting IoTeX witness service\")\n\tif err := witnessOnIoTeX.Start(context.Background()); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer witnessOnIoTeX.Stop(context.Background())\n\tlog.Println(\"Starting Ethereum witness service\")\n\tif err := witnessOnEthereum.Start(context.Background()); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer witnessOnEthereum.Stop(context.Background())\n\tlog.Println(\"Service is up\")\n\tlog.Println(\"Starting metrics service\")\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmetricsServer := httputil.Server(fmt.Sprintf(\":%d\", cfg.HTTPPort), mux)\n\tdefer metricsServer.Close()\n\tln, err := httputil.LimitListener(metricsServer.Addr)\n\tif err != nil {\n\t\tlog.Panicf(\"Failed to listen on probe port %d\", cfg.HTTPPort)\n\t\treturn\n\t}\n\tif err := metricsServer.Serve(ln); err != nil {\n\t\tlog.Panicf(\"Probe server stopped: %v\\n\", err)\n\t}\n\tselect {}\n}", "func (E_OpenconfigLacp_LacpSynchronizationType) IsYANGGoEnum() {}", "func (f *Frontend) detectLanguage(r *http.Request) []language.Tag {\n\tpreferred := []language.Tag{}\n\tif lang := strings.TrimSpace(r.FormValue(\"l\")); lang != \"\" {\n\t\tif l, err := language.Parse(lang); err == nil {\n\t\t\tpreferred = append(preferred, l)\n\t\t}\n\t}\n\n\ttags, _, err := language.ParseAcceptLanguage(r.Header.Get(\"Accept-Language\"))\n\tif err != nil {\n\t\tlog.Info.Println(err)\n\t\treturn preferred\n\t}\n\n\tpreferred = append(preferred, tags...)\n\treturn preferred\n}", "func updateTLC(g *core.Gossiper, t *core.TLCMessage) {\n\tfor idx, tlc := range g.KnownTLCs {\n\t\tif strings.Compare(tlc.Origin, t.Origin) == 0 && tlc.ID == t.ID {\n\t\t\tg.KnownTLCs[idx] = *t\n\t\t}\n\t}\n}", "func (e *engine) setDefaults(ctx *Context) {\n\tif ctx.Req.Locale == nil {\n\t\tctx.Req.Locale = ahttp.NewLocale(AppConfig().StringDefault(\"i18n.default\", \"en\"))\n\t}\n}", "func (kl *KubeLego) paramsLego() error {\n\n\tkl.legoEmail = os.Getenv(\"LEGO_EMAIL\")\n\tif len(kl.legoEmail) == 0 {\n\t\treturn errors.New(\"Please provide an email address for cert recovery in LEGO_EMAIL\")\n\t}\n\n\tkl.LegoNamespace = os.Getenv(\"LEGO_NAMESPACE\")\n\tif len(kl.LegoNamespace) == 0 {\n\t\tkl.LegoNamespace = k8sApi.NamespaceDefault\n\t}\n\n\tkl.legoURL = os.Getenv(\"LEGO_URL\")\n\tif len(kl.legoURL) == 0 {\n\t\tkl.legoURL = \"https://acme-staging.api.letsencrypt.org/directory\"\n\t}\n\n\tkl.LegoSecretName = os.Getenv(\"LEGO_SECRET_NAME\")\n\tif len(kl.LegoSecretName) == 0 {\n\t\tkl.LegoSecretName = \"kube-lego-account\"\n\t}\n\n\tkl.LegoServiceName = os.Getenv(\"LEGO_SERVICE_NAME\")\n\tif len(kl.LegoServiceName) == 0 {\n\t\tkl.LegoServiceName = \"kube-lego\"\n\t}\n\n\tkl.LegoIngressName = os.Getenv(\"LEGO_INGRESS_NAME\")\n\tif len(kl.LegoIngressName) == 0 {\n\t\tkl.LegoIngressName = \"kube-lego\"\n\t}\n\n\tcheckIntervalString := os.Getenv(\"LEGO_CHECK_INTERVAL\")\n\tif len(checkIntervalString) == 0 {\n\t\tkl.legoCheckInterval = 8 * time.Hour\n\t} else {\n\t\td, err := time.ParseDuration(checkIntervalString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d < 5*time.Minute {\n\t\t\treturn fmt.Errorf(\"Minimum check interval is 5 minutes: %s\", d)\n\t\t}\n\t\tkl.legoCheckInterval = d\n\t}\n\n\thttpPortStr := os.Getenv(\"LEGO_PORT\")\n\tif len(httpPortStr) == 0 {\n\t\tkl.legoHTTPPort = intstr.FromInt(8080)\n\t} else {\n\t\ti, err := strconv.Atoi(httpPortStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif i <= 0 || i >= 65535 {\n\t\t\treturn fmt.Errorf(\"Wrong port: %d\", i)\n\t\t}\n\t\tkl.legoHTTPPort = intstr.FromInt(i)\n\t}\n\n\treturn nil\n}", "func check_change(){\nn:=0/* the number of discrepancies found */\nif compare_runes(buffer,change_buffer)!=0{\nreturn\n}\nchange_pending= false\nif!changed_section[section_count]{\nif_section_start_make_pending(true)\nif!change_pending{\nchanged_section[section_count]= true\n}\n}\nfor true{\nchanging= true\nprint_where= true\nchange_line++\nif err:=input_ln(change_file);err!=nil{\nerr_print(\"! Change file ended before @y\")\n\nchange_buffer= nil\nchanging= false\nreturn\n}\nif len(buffer)> 1&&buffer[0]=='@'{\nvar xyz_code rune\nif unicode.IsUpper(buffer[1]){\nxyz_code= unicode.ToLower(buffer[1])\n}else{\nxyz_code= buffer[1]\n}\n\n\n/*28:*/\n\n\n//line gocommon.w:333\n\nif xyz_code=='x'||xyz_code=='z'{\nloc= 2\nerr_print(\"! Where is the matching @y?\")\n\n}else if xyz_code=='y'{\nif n> 0{\nloc= 2\nerr_print(\"! Hmm... %d of the preceding lines failed to match\",n)\n\n}\nchange_depth= include_depth\nreturn\n}\n\n\n\n/*:28*/\n\n\n//line gocommon.w:309\n\n}\n\n\n/*23:*/\n\n\n//line gocommon.w:222\n\n{\nchange_buffer= buffer\nbuffer= nil\n}\n\n\n\n/*:23*/\n\n\n//line gocommon.w:311\n\nchanging= false\nline[include_depth]++\nfor input_ln(file[include_depth])!=nil{/* pop the stack or quit */\nif include_depth==0{\nerr_print(\"! GOWEB file ended during a change\")\n\ninput_has_ended= true\nreturn\n}\ninclude_depth--\nline[include_depth]++\n}\nif compare_runes(buffer,change_buffer)!=0{\nn++\n}\n}\n}", "func (upr UpdatePathResponse) ContentLanguage() string {\n\treturn upr.rawResponse.Header.Get(\"Content-Language\")\n}", "func (E_OpenconfigLacp_LacpPeriodType) IsYANGGoEnum() {}", "func updateCipherMode(seed, key, iv, nonce, prim, rng bool, s *Config) {\n\t// set everything to false\n\t// for k, _ := range s.widgets {\n\t//\t\t s.widgets[k].SetSensitive(false)\n\t// }\n s.widgets[\"modeCombo\"].SetSensitive(true)\n\n\tif seed {\n\t\ts.widgets[\"seedBox\"].SetSensitive(true)\n\t\ts.widgets[\"seedLabel\"].SetSensitive(true)\n\t}\n\n\tif key {\n\t\ts.widgets[\"keyBox\"].SetSensitive(true)\n\t\ts.widgets[\"keyLabel\"].SetSensitive(true)\n\t}\n\n\tif iv {\n\t\ts.widgets[\"ivBox\"].SetSensitive(true)\n\t\ts.widgets[\"ivLabel\"].SetSensitive(true)\n\t}\n\n\tif prim {\n\t\ts.widgets[\"primCombo\"].SetSensitive(true)\n\t\ts.widgets[\"primLabel\"].SetSensitive(true)\n\t}\n\n\treturn\n}", "func main() {\n\tmodelType := flag.String(\"model\", \"\", \"change model type,domain or initUser\")\n\tDomainName := flag.String(\"DomainName\", \"\", \"\")\n\tDCHostName := flag.String(\"DCHostName\", \"\", \"\")\n\tDNS := flag.String(\"DNS\", \"\", \"\")\n\tUserName := flag.String(\"UserName\", \"\", \"\")\n\tUserDN := flag.String(\"UserDN\", \"\", \"\")\n\tPwd := flag.String(\"UserPWD\", \"\", \"\")\n\t//Secret := flag.String(\"Secret\", \"\", \"\")\n\n\tflag.Parse()\n\n\tif *modelType == \"\" {\n\t\tfmt.Println(\"Please select operation model\")\n\t\treturn\n\t}\n\n\tswitch *modelType {\n\tcase \"domain\":\n\t\tif isNil(DomainName, DCHostName, DNS, UserName, UserDN, Pwd) {\n\t\t\tfmt.Println(\"Please enter the correct parameters, -DomainName -DCHostName -DNS -UserName -UserDN -UserPWD\")\n\t\t\treturn\n\t\t}\n\t\tsplit := strings.SplitN(*DomainName, \".\", 2)\n\t\tencrypt, err := util.PasswordEncrypt(*Pwd)\n\t\tif err != nil {\n\t\t\tlogger.Panicf(\"pass word encrypt err:%v\", err)\n\t\t}\n\t\tdomain := model.Domain{\n\t\t\tName: *DomainName,\n\t\t\tDCHostName: *DCHostName,\n\t\t\tDNS: *DNS,\n\t\t\tDN: fmt.Sprintf(\"DC=%s,DC=%s\", split[0], split[1]),\n\t\t\tUserName: *UserName,\n\t\t\tPassword: encrypt,\n\t\t\tUserDN: *UserDN,\n\t\t\tStatus: 0,\n\t\t\tErrMsg: \"\",\n\t\t\tCreatedAt: time.Time{},\n\t\t}\n\n\t\t_, err = service.InitLdapConn(domain.DNS, domain.UserDN, *Pwd)\n\t\tif err != nil {\n\t\t\tlogger.Panicf(\"Domain status failed err:%v\", err)\n\t\t}\n\n\t\terr = server.AddDomain(env.MysqlCli, domain)\n\t\tif err != nil {\n\t\t\tlogger.Panicf(\"add domain err:%v\", err)\n\t\t}\n\tcase \"initUser\":\n\t\tif isNil(UserName, Pwd) {\n\t\t\tfmt.Println(\"Please enter the correct parameters\")\n\t\t\treturn\n\t\t}\n\t\tplainPwd, err := bcrypt.GenerateFromPassword([]byte(*Pwd), bcrypt.MinCost)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"服务器内部错误\")\n\t\t\treturn\n\t\t}\n\t\tuser := model.User{\n\t\t\tID: 1,\n\t\t\tUserName: *UserName,\n\t\t\tPassword: string(plainPwd),\n\t\t\tPassStrength: \"high\",\n\t\t\tSecret: \"JYYFQWCDGQYTGQ2WI5EUYNBQHFETSSCX\",\n\t\t\tMfaStatus: \"enable\",\n\t\t\tCreatedAt: time.Now(),\n\t\t\tUpdatedAt: time.Now(),\n\t\t}\n\n\t\terr = server.CreateUser(env, user)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"add user err:%v\", err)\n\t\t\treturn\n\t\t}\n\n\t}\n\n}", "func determineLanguages(url string) ([]string, error) {\n\n\t// (try to) get json from url as []byte\n\trespJSON, getErr := getJSON(url)\n\tif getErr != nil {\n\t\treturn nil, getErr\n\t}\n\n\t// (try to) unmarshal json info into map of { language: bytes }\n\tvar data map[string]interface{}\n\tmarshalErr := json.Unmarshal([]byte(respJSON), &data)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\n\t// fill string slice with indexes from map (the languages) and return it\n\tret := make([]string, 0)\n\tfor index := range data {\n\t\tret = append(ret, index)\n\t}\n\n\treturn ret, nil\n}", "func handleAliyunExt(svcName string, service *kobject.ServiceConfig) {\n\tfor key, value := range service.Labels {\n\n\t\tvalue = strings.TrimSpace(value)\n\t\tvar err error\n\n\t\tswitch key {\n\n\t\tcase LABEL_SERVICE_SCALE:\n\t\t\tservice.Replicas, err = strconv.Atoi(value)\n\t\tcase LABEL_SERVICE_GLOBAL:\n\t\t\tif strings.ToLower(value) == \"true\" {\n\t\t\t\tservice.DeployMode = \"global\"\n\t\t\t}\n\t\tcase LABEL_SERVICE_PROBE_URL:\n\t\t\terr = parseServiceProbe(value, &service.HealthChecks)\n\t\tcase LABEL_SERVICE_PROBE_CMD:\n\t\t\tservice.HealthChecks.Test, err = shlex.Split(value)\n\t\tcase LABEL_SERVICE_PROBE_TIMEOUT_SECONDS:\n\t\t\tservice.HealthChecks.Timeout, err = parseProbeSeconds(value)\n\t\tcase LABEL_SERVICE_PROBE_INIT_DELAY_SECONDS:\n\t\t\tservice.HealthChecks.StartPeriod, err = parseProbeSeconds(value)\n\t\tcase LABEL_GPU:\n\t\t\tservice.GPUs, err = strconv.Atoi(value)\n\t\tdefault:\n\t\t\tif strings.HasPrefix(key, LABEL_SERVICE_LB_PORT_PREFIX) {\n\t\t\t\tservice.ServiceType = string(api.ServiceTypeLoadBalancer)\n\t\t\t\tservice.ServiceAnnotations, err = parseLbs(key, value)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = checkAndAddingPort(key[len(LABEL_SERVICE_LB_PORT_PREFIX):], service)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(key, LABEL_SERVICE_ROUTING_PORT_PREFIX) {\n\t\t\t\tvar routings []Routing\n\t\t\t\troutings, err = parseRouting(key, value)\n\t\t\t\tlog.Warnf(\"Handling aliyun routings label: %v\", routings)\n\t\t\t\tif err == nil && len(routings) > 0 {\n\t\t\t\t\tservice.ExposeService = routings[0].VirtualHost\n\t\t\t\t\tservice.ExposeServicePath = routings[0].ContextRoot\n\t\t\t\t\terr = checkAndAddingPort(key[len(LABEL_SERVICE_ROUTING_PORT_PREFIX):], service)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(key, LABEL_SLS_PREFIX) {\n\t\t\t\tvar logConfig *LogConfig\n\t\t\t\tlogConfig, err = parseLogConfig(key, value)\n\t\t\t\tif err == nil {\n\t\t\t\t\tservice.Environment = append(service.Environment, kobject.EnvVar{\n\t\t\t\t\t\tName: \"aliyun_logs_\" + logConfig.Name,\n\t\t\t\t\t\tValue: value,\n\t\t\t\t\t})\n\t\t\t\t\tif logConfig.Type == \"file\" {\n\t\t\t\t\t\t// Add mount point\n\t\t\t\t\t\tif service.LogVolumes == nil {\n\t\t\t\t\t\t\tservice.LogVolumes = make(map[string]string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tservice.LogVolumes[logConfig.Name] = logConfig.ContainerPath\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terrors.Wrap(err, fmt.Sprint(\"invalid value for %s label: %s\", key, value))\n\t\t}\n\t}\n}", "func (_obj *Apilangpack) Langpack_getLangPackOneWayWithContext(tarsCtx context.Context, params *TLlangpack_getLangPack, _opt ...map[string]string) (ret LangPackDifference, 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\n\terr = _obj.s.Tars_invoke(tarsCtx, 1, \"langpack_getLangPack\", _os.ToBytes(), _status, _context, _resp)\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 processRequest(req *CustomProtocol.Request) {\n\n\tpayload := CustomProtocol.ParsePayload(req.Payload)\n\tswitch req.OpCode {\n\tcase CustomProtocol.ActivateGPS:\n\t\tflagStolen(\"gps\", payload[0])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.FlagStolen:\n\t\tflagStolen(\"laptop\", payload[0])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.FlagNotStolen:\n\t\t//TODO: temp fix < 12\n\t\tif len(payload[0]) < 12 {\n\t\t\tflagNotStolen(\"gps\", payload[0])\n\t\t} else {\n\t\t\tflagNotStolen(\"laptop\", payload[0])\n\t\t}\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1 //TO DO CHANGE\n\t\treq.Response <- res\n\tcase CustomProtocol.NewAccount:\n\t\tSignUp(payload[0], payload[1], payload[2], payload[3], payload[4])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.NewDevice:\n\t\tregisterNewDevice(payload[0], payload[1], payload[2], payload[3])\n\t\tres := make([]byte, 2)\n\t\tres[0] = 1\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateDeviceGPS:\n\t\tupdated := updateDeviceGps(payload[0], payload[1], payload[2])\n\t\tres := make([]byte, 2)\n\t\tif updated == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.VerifyLoginCredentials:\n\t\taccountValid, passwordValid := VerifyAccountInfo(payload[0], payload[1])\n\t\tres := make([]byte, 2)\n\t\tif accountValid {\n\t\t\tres[0] = 1\n\t\t\tif passwordValid {\n\t\t\t\tres[1] = 1\n\t\t\t} else {\n\t\t\t\tres[0] = 0\n\t\t\t}\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t\tres[1] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.SetAccount:\n\t\taccSet := updateAccountInfo(payload[0], payload[1], payload[2])\n\t\tres := make([]byte, 1)\n\t\tif accSet == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.GetDevice:\n\t\tres := make([]byte, 5)\n\n\t\tif payload[0] == \"gps\" {\n\t\t\tres = getGpsDevices(payload[1])\n\t\t} else if payload[0] == \"laptop\" {\n\t\t\tres = getLaptopDevices(payload[1])\n\t\t} else {\n\t\t\tfmt.Println(\"CustomProtocol.GetDevice payload[0] must be either gps or laptop\")\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.SetDevice:\n\tcase CustomProtocol.GetDeviceList:\n\t\tres := []byte{}\n\t\tres = append(res, getLaptopDevices(payload[0])...)\n\t\tres = append(res, 0x1B)\n\t\tres = append(res, getGpsDevices(payload[0])...)\n\t\treq.Response <- res\n\tcase CustomProtocol.CheckDeviceStolen:\n\t\tisStolen := IsDeviceStolen(payload[0])\n\t\tres := make([]byte, 1)\n\t\tif isStolen == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateUserKeylogData:\n\t\tboolResult := UpdateKeylog(payload[0], payload[1])\n\t\tres := make([]byte, 1)\n\t\tif boolResult == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tcase CustomProtocol.UpdateUserIPTraceData:\n\t\tboolResult := UpdateTraceRoute(payload[0], payload[1])\n\t\tres := make([]byte, 1)\n\t\tif boolResult == true {\n\t\t\tres[0] = 1\n\t\t} else {\n\t\t\tres[0] = 0\n\t\t}\n\t\treq.Response <- res\n\tdefault:\n\t}\n}", "func (cf *cf) guessArgs(file *string, prob probCode, lang *int) error {\n\tf, l := *file, *lang\n\tneedExt := len(f) < 3\n\n\tif l == 0 && needExt {\n\t\t// search over disk\n\t\tf += \".\"\n\t\tvar match []string\n\t\tfor k := range cf.config {\n\t\t\tif st, err := os.Stat(f + k); err == nil && !st.IsDir() {\n\t\t\t\tmatch = append(match, k)\n\t\t\t}\n\t\t}\n\t\tif len(match) == 0 {\n\t\t\treturn fmt.Errorf(\"submit: could not found solution file for problem %q\", prob.task)\n\t\t}\n\t\tif len(match) > 1 {\n\t\t\tbuf := bytes.NewBufferString(\"submit: more than one file looks like solution for problem \")\n\t\t\tfmt.Fprintf(buf, \"%v, candidates (with lang IDs):\", prob.task)\n\t\t\tfor _, k := range match {\n\t\t\t\tfmt.Fprintf(buf, \"\\n%s%v (%s)\", f, k, cf.config[k])\n\t\t\t}\n\t\t\treturn errors.New(buf.String() + \"\\n\\nremove all but one of those files, or\\n\" +\n\t\t\t\t\" remove all but one of those extensions in conf, or\\n specify lang at command line\")\n\t\t}\n\n\t\t*file = f + match[0]\n\t\tl, err := strconv.Atoi(cf.config[match[0]])\n\t\t*lang = l\n\t\treturn err\n\t}\n\n\tif l != 0 && needExt {\n\t\ts := strconv.Itoa(l)\n\t\tfor k, v := range cf.config {\n\t\t\tif v == s {\n\t\t\t\t*file += \".\" + k\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"submit: extension must be specified for lang %q\", l)\n\t}\n\n\tif l == 0 {\n\t\text := filepath.Ext(f)\n\t\tif len(ext) < 2 {\n\t\t\treturn errors.New(\"submit: lang must be specified\")\n\t\t}\n\t\ts, ok := cf.config[ext[1:]]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"submit: unknown file extension %q, (you may add it in conf)\", ext)\n\t\t}\n\t\tl, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*lang = l\n\t}\n\treturn nil\n}", "func patchLocomotive(w http.ResponseWriter, r *http.Request) {\n\tvar document Locomotive\n\n\t//\tObtener la base de datos y colección a utilizar.-\n\tparams := mux.Vars(r)\n\tdatabaseName := params[\"databaseName\"]\n\tcollectionName := params[\"collectionName\"]\n\n\t//\tObtener el modelo a filtrar.-\n\tmodel := params[\"model\"]\n\n\t//\tConfigurar los filtros.-\n\tfilter := make(map[string]interface{})\n\tif model != \"\" {\n\t\tfilter[\"model\"] = model\n\t}\n\n\t//\tDecodificar el documento json recibido y dejarlo en la variable de tipo struct.-\n\t_ = json.NewDecoder(r.Body).Decode(&document)\n\n\t//\tConfigurar los updates.-\n\tupdate := make(map[string]interface{})\n\tif document.PowerType != \"\" {\n\t\tupdate[\"powertype\"] = document.PowerType\n\t}\n\tif document.Builder != \"\" {\n\t\tupdate[\"builder\"] = document.Builder\n\t}\n\tif document.BuildDate != \"\" {\n\t\tupdate[\"builddate\"] = document.BuildDate\n\t}\n\tif document.WheelSystem != \"\" {\n\t\tupdate[\"wheelsystem\"] = document.WheelSystem\n\t}\n\tif document.MaximunSpeed > 0 {\n\t\tupdate[\"maximunspeed\"] = document.MaximunSpeed\n\t}\n\tif document.PowerOutputHP > 0 {\n\t\tupdate[\"poweroutputhp\"] = document.PowerOutputHP\n\t}\n\n\t//\tActualizar la locomotora.-\n\tupdatedCount, err := UpdateDocument(databaseName, collectionName, filter, update)\n\tif err != nil {\n\t\thttputility.GetJsonResponseMessage(w, \"patchLocomotive: \"+err.Error())\n\t} else {\n\t\tif updatedCount == 0 {\n\t\t\thttputility.GetJsonResponseMessage(w, \"patchLocomotive: No se encontró ningun documento a actualizar en la Base de Datos (MongoDB).\")\n\t\t} else {\n\t\t\tif updatedCount == 1 {\n\t\t\t\thttputility.GetJsonResponseMessage(w, \"patchLocomotive: Se actualizó correctamente el documento de la Base de Datos (MongoDB).\")\n\t\t\t} else {\n\t\t\t\thttputility.GetJsonResponseMessage(w, \"patchLocomotive: Se actualizaron correctamente \"+string(updatedCount)+\" documentos de la Base de Datos (MongoDB).\")\n\t\t\t}\n\t\t}\n\t}\n}", "func ReplaceLines(data map[string]string)(err error){\n sourceDownload := map[string]map[string]string{}\n sourceDownload[\"ruleset\"] = map[string]string{}\n sourceDownload[\"ruleset\"][\"sourceDownload\"] = \"\"\n sourceDownload,err = GetConf(sourceDownload)\n pathDownloaded := sourceDownload[\"ruleset\"][\"sourceDownload\"]\n if err != nil {\n logs.Error(\"ReplaceLines error loading data from main.conf: \"+ err.Error())\n return err\n }\n \n //split path \n splitPath := strings.Split(data[\"path\"], \"/\")\n pathSelected := splitPath[len(splitPath)-2]\n\n saved := false\n rulesFile, err := os.Create(\"_creating-new-file.txt\")\n defer rulesFile.Close()\n var validID = regexp.MustCompile(`sid:(\\d+);`)\n\n newFileDownloaded, err := os.Open(pathDownloaded + pathSelected + \"/rules/\" + \"drop.rules\")\n\n scanner := bufio.NewScanner(newFileDownloaded)\n for scanner.Scan() {\n for x := range data{\n sid := validID.FindStringSubmatch(scanner.Text())\n if (sid != nil) && (sid[1] == string(x)) {\n if data[x] == \"N/A\"{\n saved = true\n continue\n }else{\n _, err = rulesFile.WriteString(string(data[x])) \n _, err = rulesFile.WriteString(\"\\n\") \n saved = true\n continue\n }\n }\n }\n if !saved{\n _, err = rulesFile.WriteString(scanner.Text())\n _, err = rulesFile.WriteString(\"\\n\") \n }\n saved = false\n }\n\n input, err := ioutil.ReadFile(\"_creating-new-file.txt\")\n err = ioutil.WriteFile(\"rules/drop.rules\", input, 0644)\n\n _ = os.Remove(\"_creating-new-file.txt\")\n\n if err != nil {\n logs.Error(\"ReplaceLines error writting new lines: \"+ err.Error())\n return err\n }\n return nil\n}", "func goGetLanguageById(w http.ResponseWriter, r *http.Request) {\n\t//parse array of input from request message\n\tvars := mux.Vars(r)\n\n\t//get id input\n\tvar langId string\n\tlangId = vars[\"languageId\"]\n\n\t//execute get method\n\tlang := getLanguageById(langId)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tif lang.Id != \"\" {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif err := json.NewEncoder(w).Encode(lang); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\t// If we didn't find it, 404\n\tw.WriteHeader(http.StatusNotFound)\n\tif err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: \"Not Found\"}); err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func goGetLanguageById(w http.ResponseWriter, r *http.Request) {\n\t//parse array of input from request message\n\tvars := mux.Vars(r)\n\n\t//get id input\n\tvar langId string\n\tlangId = vars[\"languageId\"]\n\n\t//execute get method\n\tlang := getLanguageById(langId)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tif lang.Id != \"\" {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif err := json.NewEncoder(w).Encode(lang); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\t// If we didn't find it, 404\n\tw.WriteHeader(http.StatusNotFound)\n\tif err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: \"Not Found\"}); err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (E_OpenconfigWifiTypes_CHANGE_REASON_TYPE) IsYANGGoEnum() {}", "func TestUpdateLoots(t *testing.T) {\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tchatid, lang, err := db.UpdateLoots(\"2000\", \"FFY37X9kRfvfGeDT8hZv\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif chatid != 344178872 || lang != \"ru\" {\n\t\tt.Errorf(\"I want see chatid , but %d and lang want see ,but lang = %s \", chatid, lang)\n\t}\n}", "func (o liteOnion) send(s [][]byte, hk, ad, msg []byte) (upd, ct []byte, err error) {\n\tsk, _, err := o.init()\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create new lite-onion states\")\n\t}\n\n\tn := len(s)\n\n\tk := make([]byte, 16)\n\tks := make([][]byte, n)\n\n\tfor i := 0; i < n; i++ {\n\t\ttmp := make([]byte, 16)\n\t\tif _, err := rand.Read(tmp); err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"unable to poll random source\")\n\t\t}\n\t\tk = primitives.Xor(k, tmp)\n\t\tks[i] = tmp\n\t}\n\n\tpt, err := binary.Marshal(liteOnionMessage{S: sk, Msg: msg})\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to encode onion message\")\n\t}\n\n\tc := make([][]byte, n+1)\n\tc[n], err = o.enc.Encrypt(k, pt)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to encrypt plaintext\")\n\t}\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tad = primitives.Digest(sha256.New(), hk, ad, c[i+1])\n\t\tc[i], err = o.otae.Encrypt(s[i], ks[i], ad)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"unable to encrypt message\")\n\t\t}\n\t}\n\n\tct, err = binary.Marshal(liteOnionCiphertext{CT: c})\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to encode ciphertext\")\n\t}\n\treturn sk, ct, nil\n}", "func (e *EDNS0_LOCAL) Option() uint16 { return e.Code }", "func EnFallback(flag bool) {\n\tenFallback = flag\n}", "func ChangeLanguage(c buffalo.Context) error {\n\tf := struct {\n\t\tOldLanguage string `form:\"oldLanguage\"`\n\t\tLanguage string `form:\"language\"`\n\t\tURL string `form:\"url\"`\n\t}{}\n\tif err := c.Bind(&f); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Set new language prefix\n\tif f.URL == fmt.Sprintf(\"/%s\", f.OldLanguage) {\n\t\tf.URL = \"\"\n\t} else {\n\t\tp := fmt.Sprintf(\"/%s/\", f.OldLanguage)\n\t\tf.URL = strings.TrimPrefix(f.URL, p)\n\t}\n\n\treturn c.Redirect(302, fmt.Sprintf(\"/%s/%s\", f.Language, f.URL))\n}", "func (c *Client) update(rsp *Response) {\n\tif rsp.Label == \"CAPABILITY\" {\n\t\tc.setCaps(rsp.Fields[1:])\n\t\treturn\n\t}\n\tswitch rsp.Type {\n\tcase Data:\n\t\tif c.Mailbox == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch rsp.Label {\n\t\tcase \"FLAGS\":\n\t\t\tc.Mailbox.Flags.Replace(rsp.Fields[1])\n\t\tcase \"EXISTS\":\n\t\t\tc.Mailbox.Messages = rsp.Value()\n\t\tcase \"RECENT\":\n\t\t\tc.Mailbox.Recent = rsp.Value()\n\t\tcase \"EXPUNGE\":\n\t\t\tc.Mailbox.Messages--\n\t\t\tif c.Mailbox.Recent > c.Mailbox.Messages {\n\t\t\t\tc.Mailbox.Recent = c.Mailbox.Messages\n\t\t\t}\n\t\t\tif c.Mailbox.Unseen == rsp.Value() {\n\t\t\t\tc.Mailbox.Unseen = 0\n\t\t\t}\n\t\t}\n\tcase Status:\n\t\tswitch rsp.Status {\n\t\tcase BAD:\n\t\t\t// RFC 3501 is a bit vague on how the client is expected to react to\n\t\t\t// an untagged BAD response. It's probably best to close this\n\t\t\t// connection and open a new one; leave this up to the caller. For\n\t\t\t// now, abort all active commands to avoid waiting for completion\n\t\t\t// responses that may never come.\n\t\t\tc.Logln(LogCmd, \"ABORT!\", rsp.Info)\n\t\t\tc.deliver(abort)\n\t\tcase BYE:\n\t\t\tc.Logln(LogConn, \"Logout reason:\", rsp.Info)\n\t\t\tc.setState(Logout)\n\t\t}\n\t\tfallthrough\n\tcase Done:\n\t\tif rsp.Label == \"ALERT\" {\n\t\t\tc.Logln(LogConn, \"ALERT!\", rsp.Info)\n\t\t\treturn\n\t\t} else if c.Mailbox == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch selected := (c.state == Selected); rsp.Label {\n\t\tcase \"PERMANENTFLAGS\":\n\t\t\tc.Mailbox.PermFlags.Replace(rsp.Fields[1])\n\t\tcase \"READ-ONLY\":\n\t\t\tif selected && !c.Mailbox.ReadOnly {\n\t\t\t\tc.Logln(LogState, \"Mailbox access change: RW -> RO\")\n\t\t\t}\n\t\t\tc.Mailbox.ReadOnly = true\n\t\tcase \"READ-WRITE\":\n\t\t\tif selected && c.Mailbox.ReadOnly {\n\t\t\t\tc.Logln(LogState, \"Mailbox access change: RO -> RW\")\n\t\t\t}\n\t\t\tc.Mailbox.ReadOnly = false\n\t\tcase \"UIDNEXT\":\n\t\t\tc.Mailbox.UIDNext = rsp.Value()\n\t\tcase \"UIDVALIDITY\":\n\t\t\tv := rsp.Value()\n\t\t\tif u := c.Mailbox.UIDValidity; selected && u != v {\n\t\t\t\tc.Logf(LogState, \"Mailbox UIDVALIDITY change: %d -> %d\", u, v)\n\t\t\t}\n\t\t\tc.Mailbox.UIDValidity = v\n\t\tcase \"UNSEEN\":\n\t\t\tc.Mailbox.Unseen = rsp.Value()\n\t\tcase \"UIDNOTSTICKY\":\n\t\t\tc.Mailbox.UIDNotSticky = true\n\t\t}\n\t}\n}", "func updateLocalizableStrings(project Project, str string) Project {\n\tfor _, lang := range project.Languages { //do it to all project's Localizable.strings file\n\t\tvar path = lang.Path + \"/Localizable.strings\"\n\t\tvar fileContents = readFile(path)\n\t\tif !strings.Contains(fileContents, str) { //if str does not exist in Localizable.strings...\n\t\t\tvar stringToWrite = str + \" = \\\"\\\";\" //equivalent to: \"word\" = \"\";\n\t\t\twriteToFile(path, \"\\n\"+stringToWrite) //write at the end\n\t\t}\n\t}\n\treturn project\n}", "func updateClientSrv(srv pb.APPackets_APPacketsInitNotifServer) bool {\n\tvar args []byte\n\n\tdbg.Println(\"update client srv:\", srv)\n\n\taddr, err := server_util.GetAddressFromCtx(srv.Context())\n\tif err == false {\n\t\tfmt.Println(\"srv update failed: peer address\", addr, \"not found\")\n\t\treturn false\n\t}\n\n\tci.pmux.Lock()\n\tif val, ok := ci.pconfig[addr]; ok {\n\t\tval.srv = srv\n\t\tci.pconfig[addr] = val\n\t} else {\n\t\tfmt.Println(\"srv update failed: subscription not found\")\n\t\tci.pmux.Unlock()\n\t\treturn false\n\t}\n\tci.pmux.Unlock()\n\n\tenable := (getSubscriberCount() > 0)\n\tif ci.pconfigured != enable {\n\t\tdbg.Println(\"Packet Configuration:\", ci.pconfigured, \"->\", enable)\n\t\tif enable {\n\t\t\targs = []byte(\"+tohost\")\n\t\t} else {\n\t\t\targs = []byte(\"-tohost\")\n\t\t}\n\t\terr := ioutil.WriteFile(\"/proc/aptrace/debug\", args, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error in configuring capture\", err)\n\t\t} else {\n\t\t\tci.pconfigured = enable\n\t\t}\n\t}\n\n\treturn true\n}", "func (this *Tidy) Language(val string) (bool, error) {\n\tv := (*C.tmbchar)(C.CString(val))\n\tdefer C.free(unsafe.Pointer(v))\n\treturn this.optSetString(C.TidyLanguage, v)\n}", "func (i *I18n) Serve(ctx context.Context) {\n\twasByCookie := false\n\n\tlanguage := i.Default\n\n\tlangKey := ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()\n\tif ctx.Values().GetString(langKey) == \"\" {\n\t\t// try to get by url parameter\n\t\tlanguage = ctx.URLParam(i.URLParameter)\n\t\tif language == \"\" {\n\t\t\t// then try to take the lang field from the cookie\n\t\t\tlanguage = ctx.GetCookie(langKey)\n\n\t\t\tif len(language) > 0 {\n\t\t\t\twasByCookie = true\n\t\t\t} else {\n\t\t\t\t// try to get by the request headers.\n\t\t\t\tlangHeader := ctx.GetHeader(\"Accept-Language\")\n\t\t\t\tif len(langHeader) > 0 {\n\t\t\t\t\tfor _, langEntry := range strings.Split(langHeader, \",\") {\n\t\t\t\t\t\tlc := strings.Split(langEntry, \";\")[0]\n\t\t\t\t\t\tfor _, tag := range i.Bundle.LanguageTags() {\n\t\t\t\t\t\t\tcode := strings.Split(lc, \"-\")[0]\n\t\t\t\t\t\t\tif strings.Contains(tag.String(), code) {\n\t\t\t\t\t\t\t\tlanguage = lc\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}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// if it was not taken by the cookie, then set the cookie in order to have it\n\t\tif !wasByCookie {\n\t\t\tctx.SetCookieKV(langKey, language)\n\t\t}\n\t}\n\n\tlocalizer := i18n.NewLocalizer(i.Bundle, language)\n\n\tctx.Values().Set(langKey, language)\n\ttranslateFuncKey := ctx.Application().ConfigurationReadOnly().GetTranslateFunctionContextKey()\n\t//wrap tr to raw func for ctx.Translate usage\n\tctx.Values().Set(translateFuncKey, func(translationID string, args ...interface{}) string {\n\t\tdesc := \"\"\n\t\tif len(args) > 0 {\n\t\t\tif v, ok := args[0].(string); ok {\n\t\t\t\tdesc = v\n\t\t\t}\n\t\t}\n\n\t\ttranslated, err := localizer.LocalizeMessage(&i18n.Message{ID: translationID, Description: desc})\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\treturn translated\n\t})\n\n\tctx.Next()\n}", "func GetLanguageFromVenture(venture string, languageOption string) string {\n\tswitch venture {\n\tcase \"sg\":\n\tcase \"my\":\n\tcase \"ph\":\n\t\treturn \"en\"\n\tcase \"id\":\n\t\treturn \"id\"\n\tcase \"tw\":\n\t\treturn \"zh\"\n\tcase \"hk\":\n\t\tif languageOption == \"secondary\" {\n\t\t\treturn \"zh\"\n\t\t}\n\t\treturn \"en\"\n\t}\n\treturn \"en\"\n}", "func (E_OpenconfigMessages_DEBUG_SERVICE) IsYANGGoEnum() {}", "func UpsertUserLanguage(userID, voiceToken string) error {\n\treturn upsertImpl(userID, voiceToken, \"language\")\n}", "func (g *Generator) UseWordlistEFFLarge() {\n\tg.wordlist = wordlists[\"en\"]\n}", "func doService(serviceRequest string) {\n\tif serviceRequest == \"update-youtube-dl\" {\n\t\tupdateYoutubeDl(GetConfVal(\"youtubeDownloader\"))\n\t} else {\n\t\tlogErr(\"Unknown service request %s\", serviceRequest)\n\t}\n}", "func check_complete(){\nif len(change_buffer)> 0{/* changing is false */\nbuffer= change_buffer\nchange_buffer= nil\nchanging= true\nchange_depth= include_depth\nloc= 0\nerr_print(\"! Change file entry did not match\")\n\n}\n}", "func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}", "func (E_OpenconfigLacp_LacpActivityType) IsYANGGoEnum() {}", "func processTranslation(w http.ResponseWriter, r *http.Request) {\n\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\tif b.translationProcessor == nil {\n\t\tp := &translationPage{\n\t\t\tMessage: \"Translation service not initialized\",\n\t\t\tTitle: title,\n\t\t\tPostProcessing: \"on\",\n\t\t}\n\t\tshowTranslationPage(w, b, p)\n\t}\n\tsource := r.FormValue(\"source\")\n\ttranslated := \"\"\n\tmessage := \"\"\n\tnotes := []transtools.Note{}\n\tdeepLChecked := \"checked\"\n\tgcpChecked := \"\"\n\tglossaryChecked := \"\"\n\tplatform := r.FormValue(\"platform\")\n\tif platform == \"gcp\" {\n\t\tdeepLChecked = \"\"\n\t\tgcpChecked = \"checked\"\n\t\tglossaryChecked = \"\"\n\t} else if platform == \"withGlossary\" {\n\t\tdeepLChecked = \"\"\n\t\tgcpChecked = \"\"\n\t\tglossaryChecked = \"checked\"\n\t}\n\tlog.Printf(\"processTranslation, glossaryChecked %s, source: %s\", glossaryChecked, source)\n\tprocessingChecked := r.FormValue(\"processing\")\n\tif len(source) > 0 {\n\t\tlog.Printf(\"platform: %s\", platform)\n\t\ttrText, err := translate(b, source, platform)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Translation error: %v\", err)\n\t\t\tmessage = err.Error()\n\t\t} else {\n\t\t\tlog.Printf(\"Translation result: %s\", *trText)\n\t\t\ttranslated = *trText\n\t\t}\n\t} else {\n\t\tmessage = \"Please enter translated text or click Translate for a machine translation\"\n\t}\n\tif len(translated) > 0 && processingChecked == \"on\" {\n\t\tresult := b.translationProcessor.Suggest(source, translated)\n\t\ttranslated = result.Replacement\n\t\tnotes = result.Notes\n\t\tlog.Printf(\"suggestion notes: %s, suggested translation: %s\", notes, translated)\n\t}\n\tlog.Printf(\"deepLChecked: %s, gcpChecked: %s, glossaryChecked: %s, processingChecked: %s, len(translated) = %d\",\n\t\tdeepLChecked, gcpChecked, glossaryChecked, processingChecked, len(translated))\n\tif config.PasswordProtected() {\n\t\tctx := context.Background()\n\t\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\n\t\tif !sessionInfo.Valid {\n\t\t\treturn\n\t\t}\n\t}\n\tpostProcessing := \"\"\n\tif processingChecked == \"on\" {\n\t\tpostProcessing = \"checked\"\n\t}\n\tp := &translationPage{\n\t\tSourceText: source,\n\t\tTranslatedText: translated,\n\t\tMessage: message,\n\t\tTitle: title,\n\t\tNotes: notes,\n\t\tDeepLChecked: deepLChecked,\n\t\tGCPChecked: gcpChecked,\n\t\tGlossaryChecked: glossaryChecked,\n\t\tPostProcessing: postProcessing,\n\t}\n\tshowTranslationPage(w, b, p)\n}", "func (context *context) WhisperLangAutoDetect(offset_ms int, n_threads int) ([]float32, error) {\n\tlangProbs, err := context.model.ctx.Whisper_lang_auto_detect(offset_ms, n_threads)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn langProbs, nil\n}" ]
[ "0.6413558", "0.60371095", "0.58385915", "0.5519052", "0.54779845", "0.5467058", "0.5310601", "0.52510947", "0.52062994", "0.5172734", "0.51532084", "0.50073725", "0.490693", "0.48996642", "0.48996642", "0.48512223", "0.48281896", "0.48088485", "0.47934917", "0.47850004", "0.47717094", "0.4702245", "0.46899906", "0.4673701", "0.4672992", "0.466984", "0.46588564", "0.46572244", "0.46558696", "0.46431583", "0.46116823", "0.45797518", "0.45691094", "0.45687047", "0.4567434", "0.4547623", "0.4520802", "0.45057997", "0.44946533", "0.44887245", "0.44830728", "0.4482388", "0.44781554", "0.44777974", "0.44725654", "0.44533664", "0.44462255", "0.4441585", "0.44235626", "0.44210297", "0.44167358", "0.43971142", "0.43909568", "0.4382052", "0.4381755", "0.43782577", "0.43702206", "0.43683183", "0.43681464", "0.43635842", "0.43614435", "0.43590966", "0.43583468", "0.435812", "0.4354535", "0.43495136", "0.43467674", "0.43388158", "0.43378335", "0.4328996", "0.43285054", "0.43244493", "0.4320132", "0.43187916", "0.43109447", "0.43013275", "0.4291183", "0.42908567", "0.42898557", "0.42898557", "0.42896748", "0.42867103", "0.4286429", "0.42800537", "0.4270767", "0.42681715", "0.42650518", "0.4255074", "0.4247209", "0.42469126", "0.4235618", "0.423206", "0.42285424", "0.42272705", "0.42254564", "0.42195508", "0.42188525", "0.42078772", "0.42058083", "0.42025772", "0.42008063" ]
0.0
-1
NewArtifactListerOK creates ArtifactListerOK with default headers values
func NewArtifactListerOK() *ArtifactListerOK { return &ArtifactListerOK{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *APIDefaults) ArtifactLister(params artifacts.ArtifactListerParams) middleware.Responder {\n\tpaginator := weles.ArtifactPagination{}\n\tif a.PageLimit != 0 {\n\t\tif (params.After != nil) && (params.Before != nil) {\n\t\t\treturn artifacts.NewArtifactListerBadRequest().WithPayload(&weles.ErrResponse{\n\t\t\t\tMessage: weles.ErrBeforeAfterNotAllowed.Error()})\n\t\t}\n\t\tpaginator = setArtifactPaginator(params, a.PageLimit)\n\t}\n\tfilter := setArtifactFilter(params.ArtifactFilterAndSort.Filter)\n\tsorter := setArtifactSorter(params.ArtifactFilterAndSort.Sorter)\n\n\tartifactInfoReceived, listInfo, err := a.Managers.AM.ListArtifact(filter, sorter, paginator)\n\n\tswitch err {\n\tdefault:\n\t\treturn artifacts.NewArtifactListerInternalServerError().WithPayload(\n\t\t\t&weles.ErrResponse{Message: err.Error()})\n\tcase weles.ErrArtifactNotFound:\n\t\treturn artifacts.NewArtifactListerNotFound().WithPayload(\n\t\t\t&weles.ErrResponse{Message: weles.ErrArtifactNotFound.Error()})\n\tcase nil:\n\t}\n\n\tartifactInfoReturned := artifactInfoReceivedToReturn(artifactInfoReceived)\n\n\tif (listInfo.RemainingRecords == 0) || (a.PageLimit == 0) { //last page...\n\t\treturn responderArtifact200(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n\t} //not last page...\n\treturn responderArtifact206(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n}", "func responderArtifact200(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerOK) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\tresponder = artifacts.NewArtifactListerOK()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tif paginator.ID != 0 { //not the first page\n\t\t// keep in mind that ArtifactPath in paginator is taken from query parameter,\n\t\t// not ArtifactManager\n\t\tif paginator.Forward {\n\t\t\ttmp := artifactInfoReturned[0].ID\n\t\t\tartifactListerURL.Before = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp\n\t\t\t}\n\t\t\tresponder.SetPrevious(artifactListerURL.String())\n\t\t} else {\n\t\t\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\t\t\tartifactListerURL.After = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp2 := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp2\n\t\t\t}\n\t\t\tresponder.SetNext(artifactListerURL.String())\n\t\t}\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}", "func (o *ArtifactListerOK) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerOK {\n\to.Payload = payload\n\treturn o\n}", "func generateListVersionsResponse(bucket, prefix, marker, delimiter, encodingType string, maxKeys int, resp ListObjectsInfo) ListVersionsResponse {\n\tvar versions []ObjectVersion\n\tvar prefixes []CommonPrefix\n\tvar owner = Owner{}\n\tvar data = ListVersionsResponse{}\n\n\towner.ID = globalMinioDefaultOwnerID\n\tfor _, object := range resp.Objects {\n\t\tvar content = ObjectVersion{}\n\t\tif object.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontent.Key = s3EncodeName(object.Name, encodingType)\n\t\tcontent.LastModified = object.ModTime.UTC().Format(timeFormatAMZLong)\n\t\tif object.ETag != \"\" {\n\t\t\tcontent.ETag = \"\\\"\" + object.ETag + \"\\\"\"\n\t\t}\n\t\tcontent.Size = object.Size\n\t\tcontent.StorageClass = object.StorageClass\n\t\tcontent.Owner = owner\n\t\tcontent.VersionID = \"null\"\n\t\tcontent.IsLatest = true\n\t\tversions = append(versions, content)\n\t}\n\tdata.Name = bucket\n\tdata.Versions = versions\n\n\tdata.EncodingType = encodingType\n\tdata.Prefix = s3EncodeName(prefix, encodingType)\n\tdata.KeyMarker = s3EncodeName(marker, encodingType)\n\tdata.Delimiter = s3EncodeName(delimiter, encodingType)\n\tdata.MaxKeys = maxKeys\n\n\tdata.NextKeyMarker = s3EncodeName(resp.NextMarker, encodingType)\n\tdata.IsTruncated = resp.IsTruncated\n\n\tfor _, prefix := range resp.Prefixes {\n\t\tvar prefixItem = CommonPrefix{}\n\t\tprefixItem.Prefix = s3EncodeName(prefix, encodingType)\n\t\tprefixes = append(prefixes, prefixItem)\n\t}\n\tdata.CommonPrefixes = prefixes\n\treturn data\n}", "func repoList(w http.ResponseWriter, r *http.Request) {}", "func NewArtifactListerBadRequest() *ArtifactListerBadRequest {\n\n\treturn &ArtifactListerBadRequest{}\n}", "func responderArtifact206(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerPartialContent) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\n\tresponder = artifacts.NewArtifactListerPartialContent()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tresponder.SetRemainingRecords(listInfo.RemainingRecords)\n\n\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\tartifactListerURL.After = &tmp\n\n\tif defaultPageLimit != paginator.Limit {\n\t\ttmp := paginator.Limit\n\t\tartifactListerURL.Limit = &tmp\n\t}\n\tresponder.SetNext(artifactListerURL.String())\n\n\tif paginator.ID != 0 { //... and not the first\n\t\t//paginator.ID is from query parameter not artifactmanager\n\t\tvar artifactListerURL artifacts.ArtifactListerURL\n\t\ttmp = artifactInfoReturned[0].ID\n\t\tartifactListerURL.Before = &tmp\n\t\tif defaultPageLimit != paginator.Limit {\n\t\t\ttmp := paginator.Limit\n\t\t\tartifactListerURL.Limit = &tmp\n\t\t}\n\t\tresponder.SetPrevious(artifactListerURL.String())\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}", "func (o *ArtifactListerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header Next\n\n\tnext := o.Next\n\tif next != \"\" {\n\t\trw.Header().Set(\"Next\", next)\n\t}\n\n\t// response header Previous\n\n\tprevious := o.Previous\n\tif previous != \"\" {\n\t\trw.Header().Set(\"Previous\", previous)\n\t}\n\n\t// response header TotalRecords\n\n\ttotalRecords := swag.FormatUint64(o.TotalRecords)\n\tif totalRecords != \"\" {\n\t\trw.Header().Set(\"TotalRecords\", totalRecords)\n\t}\n\n\trw.WriteHeader(200)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*weles.ArtifactInfo, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n\n}", "func TestApiLevelArtifactsCreate(t *testing.T) {\n\tctx := context.Background()\n\tregistryClient, err := connection.NewClient(ctx)\n\tif err != nil {\n\t\tt.Logf(\"Failed to create client: %+v\", err)\n\t\tt.FailNow()\n\t}\n\tdefer registryClient.Close()\n\n\t// Setup\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n\tcreateProject(ctx, registryClient, t, \"controller-test\")\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"test-api-1\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\n\t// Test API 2\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"test-api-2\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\n\t// Test the manifest\n\tmanifest := manifests[1]\n\tactions, err := ProcessManifest(ctx, registryClient, \"controller-test\", manifest)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t}\n\texpectedActions := []string{\n\t\t\"compute vocabulary projects/controller-test/apis/test-api-1\",\n\t\t\"compute vocabulary projects/controller-test/apis/test-api-2\"}\n\tif diff := cmp.Diff(expectedActions, actions, sortStrings); diff != \"\" {\n\t\tt.Errorf(\"ProcessManifest(%+v) returned unexpected diff (-want +got):\\n%s\", manifest, diff)\n\t}\n\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n}", "func NewArtifactListerNotFound() *ArtifactListerNotFound {\n\n\treturn &ArtifactListerNotFound{}\n}", "func NewAllDashboardsOK() *AllDashboardsOK {\n return &AllDashboardsOK{\n }\n}", "func (a *DefaultApiService) ListRetrievedFiles(ctx _context.Context, imageDigest string) ([]RetrievedFile, *_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 []RetrievedFile\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/images/{imageDigest}/artifacts/retrieved_files\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageDigest\"+\"}\", _neturl.QueryEscape(parameterToString(imageDigest, \"\")) , -1)\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\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Create(\n\tctx context.Context,\n\tcfg config.Config,\n\tdc downloads.DatasetClient,\n\tfc downloads.FilterClient,\n\tic downloads.ImageClient,\n\ts3 content.S3Client,\n\tvc content.VaultClient,\n\tzc *health.Client,\n\thc *healthcheck.HealthCheck) Download {\n\n\trouter := mux.NewRouter()\n\n\tdownloader := downloads.Downloader{\n\t\tFilterCli: fc,\n\t\tDatasetCli: dc,\n\t\tImageCli: ic,\n\t}\n\n\ts3c := content.NewStreamWriter(s3, vc, cfg.VaultPath, cfg.EncryptionDisabled)\n\n\td := handlers.Download{\n\t\tDownloader: downloader,\n\t\tS3Content: s3c,\n\t\tIsPublishing: cfg.IsPublishing,\n\t}\n\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.csv\").HandlerFunc(d.DoDatasetVersion(\"csv\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.csv-metadata.json\").HandlerFunc(d.DoDatasetVersion(\"csvw\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.xlsx\").HandlerFunc(d.DoDatasetVersion(\"xls\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/filter-outputs/{filterOutputID}.csv\").HandlerFunc(d.DoFilterOutput(\"csv\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/filter-outputs/{filterOutputID}.xlsx\").HandlerFunc(d.DoFilterOutput(\"xls\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/images/{imageID}/{variant}/{filename}\").HandlerFunc(d.DoImage(cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.HandleFunc(\"/health\", hc.Handler)\n\n\t// Create new middleware chain with whitelisted handler for /health endpoint\n\tmiddlewareChain := alice.New(middleware.Whitelist(middleware.HealthcheckFilter(hc.Handler)))\n\n\t// For non-whitelisted endpoints, do identityHandler or corsHandler\n\tif cfg.IsPublishing {\n\t\tlog.Event(ctx, \"private endpoints are enabled. using identity middleware\", log.INFO)\n\t\tidentityHandler := dphandlers.IdentityWithHTTPClient(clientsidentity.NewWithHealthClient(zc))\n\t\tmiddlewareChain = middlewareChain.Append(identityHandler)\n\t} else {\n\t\tcorsHandler := gorillahandlers.CORS(gorillahandlers.AllowedMethods([]string{\"GET\"}))\n\t\tmiddlewareChain = middlewareChain.Append(corsHandler)\n\t}\n\n\tr := middlewareChain.\n\t\tAppend(dphandlers.CheckHeader(dphandlers.UserAccess)).\n\t\tAppend(dphandlers.CheckHeader(dphandlers.CollectionID)).\n\t\tThen(router)\n\thttpServer := dphttp.NewServer(cfg.BindAddr, r)\n\n\treturn Download{\n\t\tfilterClient: fc,\n\t\timageClient: ic,\n\t\tdatasetClient: dc,\n\t\tvaultClient: vc,\n\t\trouter: router,\n\t\tserver: httpServer,\n\t\tshutdown: cfg.GracefulShutdownTimeout,\n\t\thealthCheck: hc,\n\t}\n}", "func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}", "func catalog_Get(t *testing.T, opts ...configOpt) {\n\tenv := newTestEnv(t, opts...)\n\tdefer env.Shutdown()\n\n\tsortedRepos := []string{\n\t\t\"2j2ar\",\n\t\t\"asj9e/ieakg\",\n\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\"hpgkt/bmawb\",\n\t\t\"jyi7b\",\n\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\"kb0j5/pic0i\",\n\t\t\"n343n\",\n\t\t\"sb71y\",\n\t}\n\n\t// shuffle repositories to make sure results are consistent regardless of creation order (it matters when running\n\t// against the metadata database)\n\tshuffledRepos := shuffledCopy(sortedRepos)\n\n\tfor _, repo := range shuffledRepos {\n\t\tcreateRepository(t, env, repo, \"latest\")\n\t}\n\n\ttt := []struct {\n\t\tname string\n\t\tqueryParams url.Values\n\t\texpectedBody catalogAPIResponse\n\t\texpectedLinkHeader string\n\t}{\n\t\t{\n\t\t\tname: \"no query parameters\",\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last query parameter\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last and n query parameters\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}, \"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"non integer n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"foo\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"1st page\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"2j2ar\",\n\t\t\t\t\"asj9e/ieakg\",\n\t\t\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=hpgkt%2Fbmawb&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"nth page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"hpgkt/bmawb\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=kb0j5%2Fpic0i&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"last page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"zero page size\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"0\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"page size bigger than full list\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"100\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"after marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"after non existent marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"does-not-exist\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t}\n\n\tfor _, test := range tt {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tresp, err := http.Get(catalogURL)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\tvar body catalogAPIResponse\n\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\terr = dec.Decode(&body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t})\n\t}\n\n\t// If the database is enabled, disable it and rerun the tests again with the\n\t// database to check that the filesystem mirroring worked correctly.\n\tif env.config.Database.Enabled && !env.config.Migration.DisableMirrorFS {\n\t\tenv.config.Database.Enabled = false\n\t\tdefer func() { env.config.Database.Enabled = true }()\n\n\t\tfor _, test := range tt {\n\t\t\tt.Run(fmt.Sprintf(\"%s filesystem mirroring\", test.name), func(t *testing.T) {\n\t\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp, err := http.Get(catalogURL)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\t\tvar body catalogAPIResponse\n\t\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\t\terr = dec.Decode(&body)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t\t})\n\t\t}\n\t}\n}", "func NewDescribeOK() *DescribeOK {\n\n\treturn &DescribeOK{}\n}", "func (o *ArtifactListerOK) WithPrevious(previous string) *ArtifactListerOK {\n\to.Previous = previous\n\treturn o\n}", "func handler() error {\n\n\t// get envars\n\tbucket := os.Getenv(\"bucket\")\n\trepo := os.Getenv(\"repo\")\n\n\tdry, err := strconv.ParseBool(os.Getenv(\"dry_run\"))\n\tif err != nil {\n\t\texitErrorf(\"could not convert type: \", err)\n\t}\n\n\tcreated, err := strconv.Atoi(os.Getenv(\"created\"))\n\tif err != nil {\n\t\texitErrorf(\"could not convert type: \", err)\n\t}\n\n\tmodified, err := strconv.Atoi(os.Getenv(\"modified\"))\n\tif err != nil {\n\t\texitErrorf(\"could not convert type: \", err)\n\t}\n\n\tdownloaded, err := strconv.Atoi(os.Getenv(\"downloaded\"))\n\tif err != nil {\n\t\texitErrorf(\"could not convert type: \", err)\n\t}\n\n\t// configure Artifactory client\n\tclient, err := lib.NewClientFromEnv()\n\tif err != nil {\n\t\texitErrorf(\"could not init Artifactory client: \", err)\n\t}\n\n\t// find old artifacts and upload the list to s3\n\treport, list, err := search(client, repo, created, modified, downloaded)\n\tif err != nil {\n\t\texitErrorf(\"could not list artifacts: \", err)\n\t}\n\n\terr = upload(report, bucket, repo)\n\tif err != nil {\n\t\texitErrorf(\"could not upload report: \", err)\n\t}\n\n\t// delete old artifacts\n\tif dry == false {\n\t\terr := delete(client, &list)\n\t\tif err != nil {\n\t\t\texitErrorf(\"could not delete artifacts: \", err)\n\t\t}\n\t}\n\treturn nil\n}", "func NewGetInventoryOK(body *GetResponseBody) *inventoryviews.InventoryView {\n\tv := &inventoryviews.InventoryView{\n\t\tID: body.ID,\n\t\tNumber: body.Number,\n\t\tCode: body.Code,\n\t\tType: body.Type,\n\t\tInventoryDate: body.InventoryDate,\n\t\tInAndOut: body.InAndOut,\n\t\tNote: body.Note,\n\t}\n\tv.Product = unmarshalProductResponseBodyToInventoryviewsProductView(body.Product)\n\tv.Warehouse = unmarshalWarehouseResponseBodyToInventoryviewsWarehouseView(body.Warehouse)\n\tv.Head = unmarshalHeadResponseBodyToInventoryviewsHeadView(body.Head)\n\tv.Founder = unmarshalFounderResponseBodyToInventoryviewsFounderView(body.Founder)\n\n\treturn v\n}", "func setArtifactPaginator(params artifacts.ArtifactListerParams, defaultPageLimit int32,\n) (paginator weles.ArtifactPagination) {\n\tpaginator.Forward = true\n\tif params.After != nil {\n\t\tpaginator.ID = *params.After\n\t} else if params.Before != nil {\n\t\tpaginator.ID = *params.Before\n\t\tpaginator.Forward = false\n\t}\n\tif params.Limit == nil {\n\t\tpaginator.Limit = defaultPageLimit\n\t} else {\n\t\tpaginator.Limit = *params.Limit\n\t}\n\treturn paginator\n}", "func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {\n\to.Next = next\n\treturn o\n}", "func NewArtifactListerPartialContent() *ArtifactListerPartialContent {\n\n\treturn &ArtifactListerPartialContent{}\n}", "func TestDerivedArtifactsCreate(t *testing.T) {\n\tctx := context.Background()\n\tregistryClient, err := connection.NewClient(ctx)\n\tif err != nil {\n\t\tt.Logf(\"Failed to create client: %+v\", err)\n\t\tt.FailNow()\n\t}\n\tdefer registryClient.Close()\n\n\t// Setup\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n\tcreateProject(ctx, registryClient, t, \"controller-test\")\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"petstore\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/complexity\")\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/complexity\")\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/complexity\")\n\n\t// Test the manifest\n\tmanifest := manifests[2]\n\tactions, err := ProcessManifest(ctx, registryClient, \"controller-test\", manifest)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t}\n\texpectedActions := []string{\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/complexity\"),\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/complexity\"),\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/complexity\"),\n\t}\n\tif diff := cmp.Diff(expectedActions, actions, sortStrings); diff != \"\" {\n\t\tt.Errorf(\"ProcessManifest(%+v) returned unexpected diff (-want +got):\\n%s\", manifest, diff)\n\t}\n\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n}", "func TestNewResponse(t *testing.T) {\n\n\tyml := `description: this is a response\nheaders:\n someHeader:\n description: a header\ncontent:\n something/thing:\n description: a thing\nx-pizza-man: pizza!\nlinks:\n someLink:\n description: a link! `\n\n\tvar idxNode yaml.Node\n\t_ = yaml.Unmarshal([]byte(yml), &idxNode)\n\tidx := index.NewSpecIndexWithConfig(&idxNode, index.CreateOpenAPIIndexConfig())\n\n\tvar n v3.Response\n\t_ = low.BuildModel(idxNode.Content[0], &n)\n\t_ = n.Build(idxNode.Content[0], idx)\n\n\tr := NewResponse(&n)\n\n\tassert.Len(t, r.Headers, 1)\n\tassert.Len(t, r.Content, 1)\n\tassert.Equal(t, \"pizza!\", r.Extensions[\"x-pizza-man\"])\n\tassert.Len(t, r.Links, 1)\n\tassert.Equal(t, 1, r.GoLow().Description.KeyNode.Line)\n\n}", "func (this *HttpClient) newBucket(resp *http.Response) (*Bucket, error) {\n\tlog.Println(\"Extracting keys from the response body\")\n\n\tbucket := &Bucket{}\n\n\terr := ffjson.NewDecoder().DecodeReader(resp.Body, bucket)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error decoding JSON\")\n\t}\n\n\tlog.Println(\"Fetched bucket \", bucket)\n\n\t// fetch and decode keys\n\treturn bucket, nil\n}", "func NewListResultOK(body *ListResponseBody) *inventory.ListResult {\n\tv := &inventory.ListResult{\n\t\tNextCursor: *body.NextCursor,\n\t\tTotal: *body.Total,\n\t}\n\tv.Items = make([]*inventory.Inventory, len(body.Items))\n\tfor i, val := range body.Items {\n\t\tv.Items[i] = unmarshalInventoryResponseBodyToInventoryInventory(val)\n\t}\n\n\treturn v\n}", "func (a *ImageApiService) HeadArtistImage(ctx _context.Context, name string, imageType ImageType, imageIndex int32, localVarOptionals *HeadArtistImageOpts) (*os.File, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodHead\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/Artists/{name}/Images/{imageType}/{imageIndex}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", _neturl.QueryEscape(parameterToString(name, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageType\"+\"}\", _neturl.QueryEscape(parameterToString(imageType, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageIndex\"+\"}\", _neturl.QueryEscape(parameterToString(imageIndex, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Tag.IsSet() {\n\t\tlocalVarQueryParams.Add(\"tag\", parameterToString(localVarOptionals.Tag.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Format.IsSet() {\n\t\tlocalVarQueryParams.Add(\"format\", parameterToString(localVarOptionals.Format.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MaxWidth.IsSet() {\n\t\tlocalVarQueryParams.Add(\"maxWidth\", parameterToString(localVarOptionals.MaxWidth.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MaxHeight.IsSet() {\n\t\tlocalVarQueryParams.Add(\"maxHeight\", parameterToString(localVarOptionals.MaxHeight.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PercentPlayed.IsSet() {\n\t\tlocalVarQueryParams.Add(\"percentPlayed\", parameterToString(localVarOptionals.PercentPlayed.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.UnplayedCount.IsSet() {\n\t\tlocalVarQueryParams.Add(\"unplayedCount\", parameterToString(localVarOptionals.UnplayedCount.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Width.IsSet() {\n\t\tlocalVarQueryParams.Add(\"width\", parameterToString(localVarOptionals.Width.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Height.IsSet() {\n\t\tlocalVarQueryParams.Add(\"height\", parameterToString(localVarOptionals.Height.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Quality.IsSet() {\n\t\tlocalVarQueryParams.Add(\"quality\", parameterToString(localVarOptionals.Quality.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CropWhitespace.IsSet() {\n\t\tlocalVarQueryParams.Add(\"cropWhitespace\", parameterToString(localVarOptionals.CropWhitespace.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.AddPlayedIndicator.IsSet() {\n\t\tlocalVarQueryParams.Add(\"addPlayedIndicator\", parameterToString(localVarOptionals.AddPlayedIndicator.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Blur.IsSet() {\n\t\tlocalVarQueryParams.Add(\"blur\", parameterToString(localVarOptionals.Blur.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.BackgroundColor.IsSet() {\n\t\tlocalVarQueryParams.Add(\"backgroundColor\", parameterToString(localVarOptionals.BackgroundColor.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.ForegroundLayer.IsSet() {\n\t\tlocalVarQueryParams.Add(\"foregroundLayer\", parameterToString(localVarOptionals.ForegroundLayer.Value(), \"\"))\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{\"image/_*\", \"application/json\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\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\tlocalVarHeaderParams[\"X-Emby-Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\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}\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 (suite *TestHarnessAPISuite) TestNewDefaultBuilderNoAcceptHeader() {\n\treq := httptest.NewRequest(\"POST\", \"/build/DefaultMove\", nil)\n\tchiRouteCtx := chi.NewRouteContext()\n\tchiRouteCtx.URLParams.Add(\"action\", \"DefaultMove\")\n\treq = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, chiRouteCtx))\n\trr := httptest.NewRecorder()\n\thandler := NewDefaultBuilder(suite.HandlerConfig())\n\thandler.ServeHTTP(rr, req)\n\n\tsuite.Equal(http.StatusOK, rr.Code)\n\tsuite.Equal(\"application/json\", rr.Header().Get(\"Content-type\"))\n}", "func generateListBucketsResponse(buckets []BucketInfo) ListBucketsResponse {\n\tvar listbuckets []Bucket\n\tvar data = ListBucketsResponse{}\n\tvar owner = Owner{}\n\n\towner.ID = globalMinioDefaultOwnerID\n\tfor _, bucket := range buckets {\n\t\tvar listbucket = Bucket{}\n\t\tlistbucket.Name = bucket.Name\n\t\tlistbucket.CreationDate = bucket.Created.UTC().Format(timeFormatAMZLong)\n\t\tlistbuckets = append(listbuckets, listbucket)\n\t}\n\n\tdata.Owner = owner\n\tdata.Buckets.Buckets = listbuckets\n\n\treturn data\n}", "func (client ArtifactsClient) listGenericArtifacts(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/generic/artifacts\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListGenericArtifactsResponse\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\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/registry/20160918/GenericArtifact/ListGenericArtifacts\"\n\t\terr = common.PostProcessServiceError(err, \"Artifacts\", \"ListGenericArtifacts\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func list_targets(w rest.ResponseWriter, r *rest.Request) {\n\tarch := r.PathParam(\"arch\")\n\tsoftware := r.PathParam(\"software\")\n\tversion := r.PathParam(\"version\")\n\n\t// Doesn't need to be cached, as its calls are already cached.\n\ttargets := BasicResults{}\n\tlatest_date := time.Time{}\n\ttarget_path := get_target_path(arch, version)\n\tfiles := get_files(cache_instance, db, target_path)\n\tfor _, file := range files {\n\t\tarchive := new(Archive)\n\t\tarchive = archive.Init(file.Path)\n\t\tif archive.Software == software {\n\t\t\tparsed_time, err := time.Parse(\"2006-01-02\", archive.Date)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tparsed_time = time.Time{}\n\t\t\t}\n\t\t\tif parsed_time.After(latest_date) {\n\t\t\t\tlatest_date = parsed_time\n\t\t\t}\n\t\t\ttargets = append(targets, BasicResult{archive.Tag, archive.Date})\n\t\t}\n\t}\n\ttargets = append(targets, BasicResult{\"latest\", latest_date.Format(\"2006-01-02\")})\n\n\t// Sort the targets by date descending.\n\tsort.Sort(targets)\n\n\tw.WriteJson(targets)\n}", "func (m *MockArtifactManager) ListArtifact(arg0 weles.ArtifactFilter, arg1 weles.ArtifactSorter, arg2 weles.ArtifactPagination) ([]weles.ArtifactInfo, weles.ListInfo, error) {\n\tret := m.ctrl.Call(m, \"ListArtifact\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]weles.ArtifactInfo)\n\tret1, _ := ret[1].(weles.ListInfo)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func New(opts ConsulOpts, queryOptions consul_api.QueryOptions, kvPrefix, kvFilter string, healthSummary bool, logger log.Logger) (*Exporter, error) {\n\turi := opts.URI\n\tif !strings.Contains(uri, \"://\") {\n\t\turi = \"http://\" + uri\n\t}\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid consul URL: %s\", err)\n\t}\n\tif u.Host == \"\" || (u.Scheme != \"http\" && u.Scheme != \"https\") {\n\t\treturn nil, fmt.Errorf(\"invalid consul URL: %s\", uri)\n\t}\n\n\ttlsConfig, err := consul_api.SetupTLSConfig(&consul_api.TLSConfig{\n\t\tAddress: opts.ServerName,\n\t\tCAFile: opts.CAFile,\n\t\tCertFile: opts.CertFile,\n\t\tKeyFile: opts.KeyFile,\n\t\tInsecureSkipVerify: opts.Insecure,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttransport := cleanhttp.DefaultPooledTransport()\n\ttransport.TLSClientConfig = tlsConfig\n\n\tconfig := consul_api.DefaultConfig()\n\tconfig.Address = u.Host\n\tconfig.Scheme = u.Scheme\n\tif config.HttpClient == nil {\n\t\tconfig.HttpClient = &http.Client{}\n\t}\n\tconfig.HttpClient.Timeout = opts.Timeout\n\tconfig.HttpClient.Transport = transport\n\n\tclient, err := consul_api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar requestLimitChan chan struct{}\n\tif opts.RequestLimit > 0 {\n\t\trequestLimitChan = make(chan struct{}, opts.RequestLimit)\n\t}\n\n\t// Init our exporter.\n\treturn &Exporter{\n\t\tclient: client,\n\t\tqueryOptions: queryOptions,\n\t\tkvPrefix: kvPrefix,\n\t\tkvFilter: regexp.MustCompile(kvFilter),\n\t\thealthSummary: healthSummary,\n\t\tlogger: logger,\n\t\trequestLimitChan: requestLimitChan,\n\t}, nil\n}", "func (suite *TestHarnessAPISuite) TestNewDefaultBuilderWithAcceptHeader() {\n\treq := httptest.NewRequest(\"POST\", \"/build/DefaultMove\", nil)\n\tchiRouteCtx := chi.NewRouteContext()\n\tchiRouteCtx.URLParams.Add(\"action\", \"DefaultMove\")\n\treq = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, chiRouteCtx))\n\treq.Header.Add(\"Accept\", \"text/html\")\n\trr := httptest.NewRecorder()\n\thandler := NewDefaultBuilder(suite.HandlerConfig())\n\thandler.ServeHTTP(rr, req)\n\n\tsuite.Equal(http.StatusOK, rr.Code)\n\tsuite.Equal(\"text/html\", rr.Header().Get(\"Content-type\"))\n}", "func compareRequest() {\n\tvar artifactList1, artifactList2 []ArtifactRecord\n\tvar artifactSetName1, artifactSetName2 string = \"111\", \"222\"\n\tvar listTitle1, listTitle2 string\n\tvar repoCount int\n\tvar err error\n\n\tif len(os.Args[1:]) == 1 {\n\t\tfmt.Println(_COMPARE_HELP_CONTENT)\n\t\treturn\n\t}\n\n\t// At least one additional argument.\n\t//scanner := bufio.NewScanner(os.Stdin)\n\trepoCount = 0\n\tfor i := 2; i < len(os.Args) && repoCount < 2; i++ {\n\t\t// Check if \"help\" is the second argument.\n\t\tartifact_arg := os.Args[i]\n\t\tswitch strings.ToLower(artifact_arg) {\n\t\tcase \"--help\", \"-help\", \"-h\":\n\t\t\tfmt.Println(_COMPARE_HELP_CONTENT)\n\t\t\treturn\n\t\tcase \"--dir\":\n\t\t\t////fmt.Println (len (os.Args[:i]))\n\t\t\tif len(os.Args[i:]) == 1 {\n\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing next argument: a directory was expected for argument %d\", i))\n\t\t\t\treturn // we are done. exit.\n\t\t\t} else {\n\t\t\t\tdirectory := os.Args[i+1]\n\t\t\t\ti++\n\t\t\t\tif !isDirectory(directory) {\n\t\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Argument %d: '%s' is not a directory\", i, directory))\n\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t}\n\t\t\t\tswitch repoCount {\n\t\t\t\tcase 0:\n\t\t\t\t\tartifactList1, _ = createEnvelopeFromDirectory(directory, false)\n\t\t\t\t\tartifactSetName1 = directory\n\t\t\t\t\tlistTitle1 = \" Directory** \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\tcase 1:\n\t\t\t\t\tartifactList2, _ = createEnvelopeFromDirectory(directory, false)\n\t\t\t\t\tartifactSetName2 = directory\n\t\t\t\t\tlistTitle2 = \" Directory++ \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"--env\":\n\t\t\tif len(os.Args[i:]) == 1 {\n\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing next argument: a directory was expected for argument %d\", i))\n\t\t\t\treturn // we are done. exit.\n\t\t\t} else {\n\t\t\t\tpart_uuid := os.Args[i+1]\n\t\t\t\ti++\n\t\t\t\tif !isValidUUID(part_uuid) {\n\t\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"'%s' is not valid uuid\", part_uuid))\n\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t}\n\t\t\t\tswitch repoCount {\n\t\t\t\tcase 0:\n\t\t\t\t\t//artifactList1, err = getPartArtifacts(part_uuid)\n\t\t\t\t\tartifactList1, err = getEnvelopeArtifactsFromLedger(part_uuid)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t\t}\n\t\t\t\t\tartifactSetName1, _ = getAliasUsingValue(part_uuid)\n\t\t\t\t\tif len(artifactSetName1) < 1 {\n\t\t\t\t\t\tartifactSetName1 = trimUUID(part_uuid, 5)\n\t\t\t\t\t}\n\t\t\t\t\tlistTitle1 = \" Ledger** \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\tcase 1:\n\t\t\t\t\t// artifactList2, err = getPartArtifacts(part_uuid)\n\t\t\t\t\tartifactList2, err = getEnvelopeArtifactsFromLedger(part_uuid)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t\t}\n\t\t\t\t\tartifactSetName2, _ = getAliasUsingValue(part_uuid)\n\t\t\t\t\tif len(artifactSetName2) < 1 {\n\t\t\t\t\t\tartifactSetName2 = trimUUID(part_uuid, 5)\n\t\t\t\t\t}\n\t\t\t\t\tlistTitle2 = \" Ledger++ \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tdisplayErrorMsg(fmt.Sprintf(\"'%s' is not a valid argument.\\n\", os.Args[i]))\n\t\t\treturn // we are done. exit.\n\t\t} // switch strings.ToLower(artifact_arg)\n\t} // for i :=\n\n\tif repoCount < 2 { // make sure we have two repositories to compare.\n\n\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing two repositories to compare. Try: %s %s --help\",\n\t\t\tfilepath.Base(os.Args[0]), os.Args[1]))\n\t\treturn\n\t}\n\t// check if any artifacts to display\n\tif len(artifactList1) == 0 {\n\t\tfmt.Printf(\"No artifacts are contained within repo %s\\n\", artifactSetName1)\n\t\treturn\n\t}\n\t// check if any artifacts to display.\n\tif len(artifactList2) == 0 {\n\t\tfmt.Printf(\"No artifacts are contained within repo %s\\n\", artifactSetName2)\n\t\treturn\n\t}\n\n\terr = displayListComparison(artifactList1, artifactList2, listTitle1, listTitle2, artifactSetName1, artifactSetName2)\n}", "func setHeaders(w http.ResponseWriter, h http.Header, u *users.User) {\n\tw.Header().Set(\"Docker-Distribution-Api-Version\", \"registry/2.0\")\n\tfor k, v := range h {\n\t\tif strings.ToLower(k) == \"content-length\" {\n\t\t\tcontinue\n\t\t}\n\t\tw.Header().Set(k, strings.Join(v, \",\"))\n\t}\n}", "func (*ListArtifactsResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_metadata_service_proto_rawDescGZIP(), []int{10}\n}", "func NewImportArchiveOK() *ImportArchiveOK {\n\treturn &ImportArchiveOK{}\n}", "func NewHeaders()(*Headers) {\n m := &Headers{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewDescribeDefault(code int) *DescribeDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DescribeDefault{\n\t\t_statusCode: code,\n\t}\n}", "func FilesDownloadHTTP(mgr *manager.Manager, filepath, version, arch string) error {\n\tkkzone := os.Getenv(\"KKZONE\")\n\tetcd := files.KubeBinary{Name: \"etcd\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultEtcdVersion}\n\tkubeadm := files.KubeBinary{Name: \"kubeadm\", Arch: arch, Version: version}\n\tkubelet := files.KubeBinary{Name: \"kubelet\", Arch: arch, Version: version}\n\tkubectl := files.KubeBinary{Name: \"kubectl\", Arch: arch, Version: version}\n\tkubecni := files.KubeBinary{Name: \"kubecni\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultCniVersion}\n\thelm := files.KubeBinary{Name: \"helm\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultHelmVersion}\n\n\tetcd.Path = fmt.Sprintf(\"%s/etcd-%s-linux-%s.tar.gz\", filepath, kubekeyapiv1alpha1.DefaultEtcdVersion, arch)\n\tkubeadm.Path = fmt.Sprintf(\"%s/kubeadm\", filepath)\n\tkubelet.Path = fmt.Sprintf(\"%s/kubelet\", filepath)\n\tkubectl.Path = fmt.Sprintf(\"%s/kubectl\", filepath)\n\tkubecni.Path = fmt.Sprintf(\"%s/cni-plugins-linux-%s-%s.tgz\", filepath, arch, kubekeyapiv1alpha1.DefaultCniVersion)\n\thelm.Path = fmt.Sprintf(\"%s/helm\", filepath)\n\n\tif kkzone == \"cn\" {\n\t\tetcd.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/etcd/release/download/%s/etcd-%s-linux-%s.tar.gz\", etcd.Version, etcd.Version, etcd.Arch)\n\t\tkubeadm.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubeadm\", kubeadm.Version, kubeadm.Arch)\n\t\tkubelet.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubelet\", kubelet.Version, kubelet.Arch)\n\t\tkubectl.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubectl\", kubectl.Version, kubectl.Arch)\n\t\tkubecni.Url = fmt.Sprintf(\"https://containernetworking.pek3b.qingstor.com/plugins/releases/download/%s/cni-plugins-linux-%s-%s.tgz\", kubecni.Version, kubecni.Arch, kubecni.Version)\n\t\thelm.Url = fmt.Sprintf(\"https://kubernetes-helm.pek3b.qingstor.com/linux-%s/%s/helm\", helm.Arch, helm.Version)\n\t\thelm.GetCmd = fmt.Sprintf(\"curl -o %s %s\", helm.Path, helm.Url)\n\t} else {\n\t\tetcd.Url = fmt.Sprintf(\"https://github.com/coreos/etcd/releases/download/%s/etcd-%s-linux-%s.tar.gz\", etcd.Version, etcd.Version, etcd.Arch)\n\t\tkubeadm.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubeadm\", kubeadm.Version, kubeadm.Arch)\n\t\tkubelet.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubelet\", kubelet.Version, kubelet.Arch)\n\t\tkubectl.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl\", kubectl.Version, kubectl.Arch)\n\t\tkubecni.Url = fmt.Sprintf(\"https://github.com/containernetworking/plugins/releases/download/%s/cni-plugins-linux-%s-%s.tgz\", kubecni.Version, kubecni.Arch, kubecni.Version)\n\t\thelm.Url = fmt.Sprintf(\"https://get.helm.sh/helm-%s-linux-%s.tar.gz\", helm.Version, helm.Arch)\n\t\thelm.GetCmd = fmt.Sprintf(\"curl -o %s/helm-%s-linux-%s.tar.gz %s && cd %s && tar -zxf helm-%s-linux-%s.tar.gz && mv linux-%s/helm . && rm -rf *linux-%s*\", filepath, helm.Version, helm.Arch, helm.Url, filepath, helm.Version, helm.Arch, helm.Arch, helm.Arch)\n\t}\n\n\tkubeadm.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubeadm.Path, kubeadm.Url)\n\tkubelet.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubelet.Path, kubelet.Url)\n\tkubectl.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubectl.Path, kubectl.Url)\n\tkubecni.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubecni.Path, kubecni.Url)\n\tetcd.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", etcd.Path, etcd.Url)\n\n\tbinaries := []files.KubeBinary{kubeadm, kubelet, kubectl, helm, kubecni, etcd}\n\n\tfor _, binary := range binaries {\n\t\tif binary.Name == \"etcd\" && mgr.EtcdContainer {\n\t\t\tcontinue\n\t\t}\n\t\tmgr.Logger.Infoln(fmt.Sprintf(\"Downloading %s ...\", binary.Name))\n\t\tif util.IsExist(binary.Path) == false {\n\t\t\tfor i := 5; i > 0; i-- {\n\t\t\t\tif output, err := exec.Command(\"/bin/sh\", \"-c\", binary.GetCmd).CombinedOutput(); err != nil {\n\t\t\t\t\tfmt.Println(string(output))\n\n\t\t\t\t\tif kkzone != \"cn\" {\n\t\t\t\t\t\tmgr.Logger.Warningln(\"Having a problem with accessing https://storage.googleapis.com? You can try again after setting environment 'export KKZONE=cn'\")\n\t\t\t\t\t}\n\t\t\t\t\treturn errors.New(fmt.Sprintf(\"Failed to download %s binary: %s\", binary.Name, binary.GetCmd))\n\t\t\t\t}\n\n\t\t\t\tif err := SHA256Check(binary, version); err != nil {\n\t\t\t\t\tif i == 1 {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\t_ = exec.Command(\"/bin/sh\", \"-c\", fmt.Sprintf(\"rm -f %s\", binary.Path)).Run()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tif err := SHA256Check(binary, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif mgr.Cluster.KubeSphere.Version == \"v2.1.1\" {\n\t\tmgr.Logger.Infoln(fmt.Sprintf(\"Downloading %s ...\", \"helm2\"))\n\t\tif util.IsExist(fmt.Sprintf(\"%s/helm2\", filepath)) == false {\n\t\t\tcmd := fmt.Sprintf(\"curl -o %s/helm2 %s\", filepath, fmt.Sprintf(\"https://kubernetes-helm.pek3b.qingstor.com/linux-%s/%s/helm\", helm.Arch, \"v2.16.9\"))\n\t\t\tif output, err := exec.Command(\"/bin/sh\", \"-c\", cmd).CombinedOutput(); err != nil {\n\t\t\t\tfmt.Println(string(output))\n\t\t\t\treturn errors.Wrap(err, \"Failed to download helm2 binary\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewExporter(uri string, cred config.Credentials, authMethod string, sslVerify bool, timeout time.Duration, logger log.Logger) (*Exporter, error) {\n\n\treturn &Exporter{\n\t\tURI: uri,\n\t\tcred: cred,\n\t\tauthMethod: authMethod,\n\t\tsslVerify: sslVerify,\n\t\ttimeout: timeout,\n\t\tup: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"up\",\n\t\t\tHelp: \"Was the last scrape of artifactory successful.\",\n\t\t}),\n\t\ttotalScrapes: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"exporter_total_scrapes\",\n\t\t\tHelp: \"Current total artifactory scrapes.\",\n\t\t}),\n\t\tjsonParseFailures: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"exporter_json_parse_failures\",\n\t\t\tHelp: \"Number of errors while parsing Json.\",\n\t\t}),\n\t\tlogger: logger,\n\t}, nil\n}", "func NewZebraFotaArtifact()(*ZebraFotaArtifact) {\n m := &ZebraFotaArtifact{\n Entity: *NewEntity(),\n }\n return m\n}", "func (*GetArtifact_Response) Descriptor() ([]byte, []int) {\n\treturn file_artifactstore_ArtifactStore_proto_rawDescGZIP(), []int{2, 0}\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n retentionEnabled := false\n headers[\"x-emc-retention-period\"] = []string{\"0\"}\n if ecsBucket.Retention != \"\" {\n days, err := strconv.ParseInt(ecsBucket.Retention, 10, 64)\n if err == nil {\n if days > 0 {\n seconds := days * 24 * 3600\n headers[\"x-emc-retention-period\"] = []string{int64toString(seconds)}\n retentionEnabled = true\n }\n }\n }\n var expirationCurrentVersions int64\n expirationCurrentVersions = 0\n if ecsBucket.ExpirationCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationCurrentVersions, 10, 64)\n if err == nil {\n expirationCurrentVersions = days\n }\n }\n var expirationNonCurrentVersions int64\n expirationNonCurrentVersions = 0\n if ecsBucket.ExpirationNonCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationNonCurrentVersions, 10, 64)\n if err == nil && ecsBucket.EnableVersioning {\n expirationNonCurrentVersions = days\n }\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n versioningStatusOK := true\n lifecyclePolicyStatusOK := true\n // If the bucket has been created\n if bucketCreateResponse.Code == 200 {\n if !retentionEnabled && ecsBucket.EnableVersioning {\n // Enable versioning\n enableVersioningHeaders := map[string][]string{}\n enableVersioningHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n versioningConfiguration := `\n <VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Status>Enabled</Status>\n <MfaDelete>Disabled</MfaDelete>\n </VersioningConfiguration>\n `\n enableVersioningResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?versioning\", enableVersioningHeaders, versioningConfiguration)\n if enableVersioningResponse.Code != 200 {\n versioningStatusOK = false\n }\n }\n if expirationCurrentVersions > 0 || expirationNonCurrentVersions > 0 {\n lifecyclePolicyHeaders := map[string][]string{}\n lifecyclePolicyHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n lifecyclePolicyConfiguration := `\n <LifecycleConfiguration>\n <Rule>\n <ID>expiration</ID>\n <Prefix></Prefix>\n <Status>Enabled</Status>\n `\n if expirationCurrentVersions > 0 && expirationNonCurrentVersions > 0 {\n // Enable expiration for both current and non current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n } else {\n if expirationCurrentVersions > 0 {\n // Enable expiration for current versions only\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n }\n if expirationNonCurrentVersions > 0 {\n // Enable expiration for non current versions only\n // To fix a bug in ECS 3.0 where an expiration for non current version can't be set if there's no expiration set for current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>1000000</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n }\n }\n lifecyclePolicyConfiguration += `\n </Rule>\n </LifecycleConfiguration>\n `\n lifecyclePolicyResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?lifecycle\", lifecyclePolicyHeaders, lifecyclePolicyConfiguration)\n if lifecyclePolicyResponse.Code != 200 {\n lifecyclePolicyStatusOK = false\n }\n }\n if versioningStatusOK && lifecyclePolicyStatusOK {\n rendering.JSON(w, http.StatusOK, \"\")\n } else {\n message := \"\"\n if !versioningStatusOK {\n message += \" Versioning can't be enabled.\"\n }\n if !lifecyclePolicyStatusOK {\n message += \" Expiration can't be set.\"\n }\n rendering.JSON(w, http.StatusOK, message)\n }\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, s3.AccessKey, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func NewRequest(c *RESTClient) *Request {\n\tvar pathPrefix string\n\tif c.base != nil {\n\t\tpathPrefix = path.Join(\"/\", c.base.Path, c.versionedAPIPath)\n\t} else {\n\t\tpathPrefix = path.Join(\"/\", c.versionedAPIPath)\n\t}\n\n\tr := &Request{\n\t\tc: c,\n\t\tpathPrefix: pathPrefix,\n\t}\n\n\tauthMethod := 0\n\n\tfor _, fn := range []func() bool{c.content.HasBasicAuth, c.content.HasTokenAuth, c.content.HasKeyAuth} {\n\t\tif fn() {\n\t\t\tauthMethod++\n\t\t}\n\t}\n\n\tif authMethod > 1 {\n\t\tr.err = fmt.Errorf(\n\t\t\t\"username/password or bearer token or secretID/secretKey may be set, but should use only one of them\",\n\t\t)\n\n\t\treturn r\n\t}\n\n\tswitch {\n\tcase c.content.HasTokenAuth():\n\t\tr.SetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", c.content.BearerToken))\n\tcase c.content.HasKeyAuth():\n\t\ttokenString := auth.Sign(c.content.SecretID, c.content.SecretKey, \"marmotedu-sdk-go\", c.group+\".marmotedu.com\")\n\t\tr.SetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", tokenString))\n\tcase c.content.HasBasicAuth():\n\t\t// TODO: get token and set header\n\t\tr.SetHeader(\"Authorization\", \"Basic \"+basicAuth(c.content.Username, c.content.Password))\n\t}\n\n\t// set accept content\n\tswitch {\n\tcase len(c.content.AcceptContentTypes) > 0:\n\t\tr.SetHeader(\"Accept\", c.content.AcceptContentTypes)\n\tcase len(c.content.ContentType) > 0:\n\t\tr.SetHeader(\"Accept\", c.content.ContentType+\", */*\")\n\t}\n\n\treturn r\n}", "func getAllflavours(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tjson.NewEncoder(w).Encode(flavours)\r\n}", "func NewMavenJARListing(roots ...string) ([]MavenJAR, error) {\n\tpaths := make(chan string)\n\tresults := make(chan result)\n\n\tgo func() {\n\t\tfor _, root := range roots {\n\t\t\tp, err := filepath.EvalSymlinks(root)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\tresults <- result{err: fmt.Errorf(\"unable to resolve %s\\n%w\", root, err)}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif info.IsDir() {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif filepath.Ext(path) != \".jar\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tpaths <- path\n\t\t\t\treturn nil\n\t\t\t}); err != nil {\n\t\t\t\tresults <- result{err: fmt.Errorf(\"error walking path %s\\n%w\", root, err)}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tclose(paths)\n\t}()\n\n\tgo func() {\n\t\tvar workers sync.WaitGroup\n\t\tfor i := 0; i < 128; i++ {\n\t\t\tworkers.Add(1)\n\t\t\tgo worker(paths, results, &workers)\n\t\t}\n\n\t\tworkers.Wait()\n\t\tclose(results)\n\t}()\n\n\tvar m []MavenJAR\n\tfor r := range results {\n\t\tif r.err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create file listing: %s\", r.err)\n\t\t}\n\t\tm = append(m, r.value)\n\t}\n\tsort.Slice(m, func(i, j int) bool {\n\t\tif m[i].Name != m[j].Name {\n\t\t\treturn m[i].Name < m[j].Name\n\t\t}\n\n\t\tif m[i].Version != m[j].Version {\n\t\t\treturn m[i].Version < m[j].Version\n\t\t}\n\n\t\treturn m[i].SHA256 < m[j].SHA256\n\t})\n\n\treturn m, nil\n}", "func (dr downloadResponse) NewMetadata() Metadata {\n\tmd := Metadata{}\n\tfor k, v := range dr.rawResponse.Header {\n\t\tif len(k) > mdPrefixLen {\n\t\t\tif prefix := k[0:mdPrefixLen]; strings.EqualFold(prefix, mdPrefix) {\n\t\t\t\tmd[strings.ToLower(k[mdPrefixLen:])] = v[0]\n\t\t\t}\n\t\t}\n\t}\n\treturn md\n}", "func NewCreateInventoryOK(body *CreateResponseBody) *inventoryviews.InventoryView {\n\tv := &inventoryviews.InventoryView{\n\t\tID: body.ID,\n\t\tNumber: body.Number,\n\t\tCode: body.Code,\n\t\tType: body.Type,\n\t\tInventoryDate: body.InventoryDate,\n\t\tInAndOut: body.InAndOut,\n\t\tNote: body.Note,\n\t}\n\tv.Product = unmarshalProductResponseBodyToInventoryviewsProductView(body.Product)\n\tv.Warehouse = unmarshalWarehouseResponseBodyToInventoryviewsWarehouseView(body.Warehouse)\n\tv.Head = unmarshalHeadResponseBodyToInventoryviewsHeadView(body.Head)\n\tv.Founder = unmarshalFounderResponseBodyToInventoryviewsFounderView(body.Founder)\n\n\treturn v\n}", "func NewListImagesOK() *ListImagesOK {\n\treturn &ListImagesOK{}\n}", "func (hrsi *SubscriberItem) getHelmRepoIndex(client rest.HTTPClient, repoURL string) (indexFile *repo.IndexFile, hash string, err error) {\n\tcleanRepoURL := strings.TrimSuffix(repoURL, \"/\")\n\treq, err := http.NewRequest(http.MethodGet, cleanRepoURL+\"/index.yaml\", nil)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Can not build request: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tif hrsi.ChannelSecret != nil && hrsi.ChannelSecret.Data != nil {\n\t\tif authHeader, ok := hrsi.ChannelSecret.Data[\"authHeader\"]; ok {\n\t\t\treq.Header.Set(\"Authorization\", string(authHeader))\n\t\t} else if user, ok := hrsi.ChannelSecret.Data[\"user\"]; ok {\n\t\t\tif password, ok := hrsi.ChannelSecret.Data[\"password\"]; ok {\n\t\t\t\treq.SetBasicAuth(string(user), string(password))\n\t\t\t} else {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"password not found in secret for basic authentication\")\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(5).Info(req)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Http request failed: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tklog.V(5).Info(\"Get succeeded: \", cleanRepoURL)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to read body: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\thash = hashKey(body)\n\tindexfile, err := loadIndex(body)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to parse the indexfile: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\terr = hrsi.filterCharts(indexfile)\n\n\treturn indexfile, hash, err\n}", "func NewArtifact()(*Artifact) {\n m := &Artifact{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}", "func generateListObjectsV1Response(bucket, prefix, marker, delimiter, encodingType string, maxKeys int, resp ListObjectsInfo) ListObjectsResponse {\n\tvar contents []Object\n\tvar prefixes []CommonPrefix\n\tvar owner = Owner{}\n\tvar data = ListObjectsResponse{}\n\n\towner.ID = globalMinioDefaultOwnerID\n\tfor _, object := range resp.Objects {\n\t\tvar content = Object{}\n\t\tif object.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontent.Key = s3EncodeName(object.Name, encodingType)\n\t\tcontent.LastModified = object.ModTime.UTC().Format(timeFormatAMZLong)\n\t\tif object.ETag != \"\" {\n\t\t\tcontent.ETag = \"\\\"\" + object.ETag + \"\\\"\"\n\t\t}\n\t\tcontent.Size = object.Size\n\t\tcontent.StorageClass = object.StorageClass\n\t\tcontent.Owner = owner\n\t\tcontents = append(contents, content)\n\t}\n\tdata.Name = bucket\n\tdata.Contents = contents\n\n\tdata.EncodingType = encodingType\n\tdata.Prefix = s3EncodeName(prefix, encodingType)\n\tdata.Marker = s3EncodeName(marker, encodingType)\n\tdata.Delimiter = s3EncodeName(delimiter, encodingType)\n\tdata.MaxKeys = maxKeys\n\n\tdata.NextMarker = s3EncodeName(resp.NextMarker, encodingType)\n\tdata.IsTruncated = resp.IsTruncated\n\tfor _, prefix := range resp.Prefixes {\n\t\tvar prefixItem = CommonPrefix{}\n\t\tprefixItem.Prefix = s3EncodeName(prefix, encodingType)\n\t\tprefixes = append(prefixes, prefixItem)\n\t}\n\tdata.CommonPrefixes = prefixes\n\treturn data\n}", "func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {\n\to.Payload = payload\n\treturn o\n}", "func newKubeListRequest(values url.Values, site, resourceKind string) (*kubeproto.ListKubernetesResourcesRequest, error) {\n\tlimit, err := queryLimitAsInt32(values, \"limit\", defaults.MaxIterationLimit)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tsortBy := types.GetSortByFromString(values.Get(\"sort\"))\n\n\tstartKey := values.Get(\"startKey\")\n\treq := &kubeproto.ListKubernetesResourcesRequest{\n\t\tResourceType: resourceKind,\n\t\tLimit: limit,\n\t\tStartKey: startKey,\n\t\tSortBy: &sortBy,\n\t\tPredicateExpression: values.Get(\"query\"),\n\t\tSearchKeywords: client.ParseSearchKeywords(values.Get(\"search\"), ' '),\n\t\tUseSearchAsRoles: values.Get(\"searchAsRoles\") == \"yes\",\n\t\tTeleportCluster: site,\n\t\tKubernetesCluster: values.Get(\"kubeCluster\"),\n\t\tKubernetesNamespace: values.Get(\"kubeNamespace\"),\n\t}\n\treturn req, nil\n}", "func init() {\n\tmakeFunc := func(base func([]reflect.Value) []reflect.Value, fptr interface{}) {\n\t\tfn := reflect.ValueOf(fptr).Elem()\n\t\tv := reflect.MakeFunc(fn.Type(), base)\n\t\tfn.Set(v)\n\t}\n\n\t// getAll(Repository) (int, string)\n\tgetAll := func(in []reflect.Value) []reflect.Value {\n\t\tvalues := in[0].MethodByName(\"GetAll\").Call([]reflect.Value{})\n\t\t// values is []reflect.Value returned by reflect.Call.\n\t\t// Since GetAll only returns interface{}, we just want the first object in values\n\t\tjsonResponse := string(jsonEncode(values[0].Interface()))\n\t\treturn genericHandlerReturn(http.StatusFound, jsonResponse)\n\t}\n\n\tmakeFunc(getAll, &GetAllUnits)\n\n\t/*func AddUnit(rw http.ResponseWriter, u Unit, repo IUnitRepository) (int, string) {\n\t\trepo.Add(&u)\n\t\trw.Header().Set(\"Location\", fmt.Sprintf(\"/unit/%d\", u.Id))\n\t\treturn http.StatusCreated, \"\"\n\t}\n\t// add(http.ResponseWriter, entity, Repository) (int, string)\n\tadd := func(in []reflect.Value) []reflect.Value {\n\t\tin[2].MethodByName(\"Add\").Call([]reflect.Value{in[1]})\n\t\theader := in[0].MethodByName(\"Header\").Call(nil)\n\t\tlocation := reflect.ValueOf(\"Location\")\n\t\tlocationValue := reflect.ValueOf(fmt.Sprintf(\"/unit/%d\", in[1].FieldByName(\"Id\")))\n\t\treflect.ValueOf(header).MethodByName(\"Set\").Call([]reflect.Value{location, locationValue})\n\t\treturn genericHandlerReturn(http.StatusCreated, \"\")\n\t}\n\n\tmakeFunc(add, &AddUnit)\n\t*/\n\n\t// get(martini.Params, Repository) (int, string)\n\tget := func(in []reflect.Value) []reflect.Value {\n\t\tparams := in[0].Interface().(martini.Params)\n\t\tid, err := strconv.Atoi(params[\"id\"])\n\n\t\tif err != nil {\n\t\t\treturn notFoundGeneric()\n\t\t}\n\n\t\tinGet := []reflect.Value{reflect.ValueOf(id)}\n\t\tvalues := in[1].MethodByName(\"Get\").Call(inGet)\n\n\t\tif values[0].IsNil() {\n\t\t\treturn notFoundGeneric()\n\t\t}\n\n\t\tjsonResponse := string(jsonEncode(values[0].Interface()))\n\t\treturn []reflect.Value{reflect.ValueOf(http.StatusOK), reflect.ValueOf(jsonResponse)}\n\t}\n\n\tmakeFunc(get, &GetUnit)\n\n}", "func apiArchiveCreate(\n\tctx *ApiContext, req *http.Request, params httprouter.Params,\n) *ApiResponse {\n\tcollectionId := params.ByName(\"collection\")\n\tcollection, err := ctx.Repository.Use(collectionId)\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\n\tkey := params.ByName(\"id\") // Routing demands a rename here\n\tif key == \"\" {\n\t\treturn JsonError(\"Missing parameter: key\", 500)\n\t}\n\n\tarchive, err := collection.NextArchive(\"API created archive\")\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\n\t// Retrieve body\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\n\terr = archive.Put(key, body, \"initial upload\")\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\n\tdocuments, err := archive.Documents()\n\tif err != nil {\n\t\treturn JsonError(err, 500)\n\t}\n\n\treturn JsonSuccess(Archive{\n\t\tId: archive.Id,\n\t\tDocuments: documents,\n\t})\n}", "func NewDeleteArtifactOK() *DeleteArtifactOK {\n\treturn &DeleteArtifactOK{}\n}", "func New(entryText, dialog, class string,\n\tconfig map[string]string) Element {\n\tif config == nil {\n\t\tfmt.Println(\"Nil config for DownloadItemsBtn\")\n\t\treturn nil\n\t}\n\tauthToken, ok := config[\"authToken\"]\n\tif !ok {\n\t\tfmt.Println(\"No authToken in config for AboutMenuItem\")\n\t\treturn nil\n\t}\n\tstatusRoot, ok := config[\"statusRoot\"]\n\tif !ok {\n\t\tfmt.Println(\"No statusRoot in config for AboutMenuItem\")\n\t\treturn nil\n\t}\n\tprops := AboutMenuItemProps{\n\t\tclass: class,\n\t\tmenuEntry: entryText,\n\t\tdialog: dialog,\n\t\tauthToken: authToken,\n\t\tstatusRoot: statusRoot,\n\t}\n\treturn AboutMenuItem(props).Render()\n}", "func NewLister() Lister {\n\treturn _lister{\n\t\tioUtil: iioutil.New(),\n\t\tdotYmlUnmarshaller: dotyml.NewUnmarshaller(),\n\t}\n}", "func NewListComponentVersionsOK() *ListComponentVersionsOK {\n\treturn &ListComponentVersionsOK{}\n}", "func findNewArtifacts(ctx context.Context, invID invocations.ID, arts []*artifactCreationRequest) ([]*artifactCreationRequest, error) {\n\t// artifacts are not expected to exist in most cases, and this map would likely\n\t// be empty.\n\ttype state struct {\n\t\thash string\n\t\tsize int64\n\t}\n\tvar states map[string]state\n\tks := spanner.KeySets()\n\tfor _, a := range arts {\n\t\tks = spanner.KeySets(invID.Key(a.parentID(), a.artifactID), ks)\n\t}\n\tvar b spanutil.Buffer\n\terr := span.Read(ctx, \"Artifacts\", ks, []string{\"ParentId\", \"ArtifactId\", \"RBECASHash\", \"Size\"}).Do(\n\t\tfunc(row *spanner.Row) (err error) {\n\t\t\tvar pid, aid string\n\t\t\tvar hash string\n\t\t\tvar size int64\n\t\t\tif err = b.FromSpanner(row, &pid, &aid, &hash, &size); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif states == nil {\n\t\t\t\tstates = make(map[string]state)\n\t\t\t}\n\t\t\t// The artifact exists.\n\t\t\tstates[invID.Key(pid, aid).String()] = state{hash, size}\n\t\t\treturn\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, appstatus.Errorf(codes.Internal, \"%s\", err)\n\t}\n\n\tnewArts := make([]*artifactCreationRequest, 0, len(arts)-len(states))\n\tfor _, a := range arts {\n\t\tst, ok := states[invID.Key(a.parentID(), a.artifactID).String()]\n\t\tif ok && a.size != st.size {\n\t\t\treturn nil, appstatus.Errorf(codes.AlreadyExists, `%q: exists w/ different size: %d != %d`, a.name(invID), a.size, st.size)\n\t\t}\n\n\t\t// Save the hash, so that it can be reused in the post-verification\n\t\t// after rbecase.UpdateBlob().\n\t\tif a.hash == \"\" {\n\t\t\th := sha256.Sum256(a.data)\n\t\t\ta.hash = artifacts.AddHashPrefix(hex.EncodeToString(h[:]))\n\t\t}\n\n\t\tswitch {\n\t\tcase !ok:\n\t\t\tnewArts = append(newArts, a)\n\t\tcase a.hash != st.hash:\n\t\t\treturn nil, appstatus.Errorf(codes.AlreadyExists, `%q: exists w/ different hash`, a.name(invID))\n\t\tdefault:\n\t\t\t// artifact exists\n\t\t}\n\t}\n\treturn newArts, nil\n}", "func (hrsi *SubscriberItem) getHelmRepoIndex(client rest.HTTPClient, repoURL string) (indexFile *repo.IndexFile, hash string, err error) {\n\tcleanRepoURL := strings.TrimSuffix(repoURL, \"/\") + \"/index.yaml\"\n\treq, err := http.NewRequest(http.MethodGet, cleanRepoURL, nil)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Can not build request: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tif hrsi.ChannelSecret != nil && hrsi.ChannelSecret.Data != nil {\n\t\tif authHeader, ok := hrsi.ChannelSecret.Data[\"authHeader\"]; ok {\n\t\t\treq.Header.Set(\"Authorization\", string(authHeader))\n\t\t} else if user, ok := hrsi.ChannelSecret.Data[\"user\"]; ok {\n\t\t\tif password, ok := hrsi.ChannelSecret.Data[\"password\"]; ok {\n\t\t\t\treq.SetBasicAuth(string(user), string(password))\n\t\t\t} else {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"password not found in secret for basic authentication\")\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(5).Info(req)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Http request failed: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tklog.V(5).Info(\"Get succeeded: \", cleanRepoURL)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to read body: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\thash = hashKey(body)\n\tindexfile, err := loadIndex(body)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to parse the indexfile: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\terr = utils.FilterCharts(hrsi.Subscription, indexfile)\n\n\treturn indexfile, hash, err\n}", "func (*CreateArtifactRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_metadata_service_proto_rawDescGZIP(), []int{7}\n}", "func NewHartifactCache(cacheDir string) HartifactCache {\n\treturn &hartifactCache{\n\t\tcacher: &fileCacher{\n\t\t\tcacheDir: cacheDir,\n\t\t},\n\t}\n}", "func NewGetCatalogEntriesOK() *GetCatalogEntriesOK {\n\treturn &GetCatalogEntriesOK{}\n}", "func buildHeader(header restful.Header) spec.Header {\n\tresponseHeader := spec.Header{}\n\tresponseHeader.Type = header.Type\n\tresponseHeader.Description = header.Description\n\tresponseHeader.Format = header.Format\n\tresponseHeader.Default = header.Default\n\n\t// If type is \"array\" items field is required\n\tif header.Type == arrayType {\n\t\tresponseHeader.CollectionFormat = header.CollectionFormat\n\t\tresponseHeader.Items = buildHeadersItems(header.Items)\n\t}\n\n\treturn responseHeader\n}", "func NewListerWithOrderBy(tableName string, selectedColumns []string, orderByParams OrderByParams) Lister {\n\treturn &universalLister{\n\t\ttableName: tableName,\n\t\tselectedColumns: strings.Join(selectedColumns, \", \"),\n\t\torderByParams: orderByParams,\n\t}\n}", "func (c *client) Artifact(id int64, project, dir, url string) (err error) {\n\tvar art []BuildArtifact\n\tif project == ProjectPersonal {\n\t\terr = c.rpc.Call(\"RemoteApi.getArtifactsInPersonalBuild\", []interface{}{c.tok, int(id)}, &art)\n\t} else {\n\t\terr = c.rpc.Call(\"RemoteApi.getArtifactsInBuild\", []interface{}{c.tok, project, int(id)}, &art)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range art {\n\t\tif project == ProjectPersonal {\n\t\t\terr = c.rpc.Call(\"RemoteApi.getArtifactFileListingPersonal\", []interface{}{c.tok, int(id), art[i].Stage, art[i].Command, art[i].Name, \"\"},\n\t\t\t\t&art[i].Files)\n\t\t} else {\n\t\t\terr = c.rpc.Call(\"RemoteApi.getArtifactFileListing\", []interface{}{c.tok, project, int(id), art[i].Stage, art[i].Command, art[i].Name, \"\"},\n\t\t\t\t&art[i].Files)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\taf := NewArtifactFetcher(url, c.tok, dir)\n\tfor i := range art {\n\t\tif err = af.Fetch(&art[i], project); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (*ListArtifactsRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_metadata_service_proto_rawDescGZIP(), []int{9}\n}", "func NewInfo(createResponse string, modified *time.Time) (os.FileInfo, error) {\n\n\telements := strings.SplitN(createResponse, \" \", 3)\n\tif len(elements) != 3 {\n\t\treturn nil, fmt.Errorf(\"invalid download createResponse: %v\", createResponse)\n\t}\n\tisDir := strings.HasPrefix(elements[0], \"D\")\n\tmodeLiteral := string(elements[0][1:])\n\tmode, err := strconv.ParseInt(modeLiteral, 8, 64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"invalid mode: %v\", modeLiteral)\n\t}\n\tsizeLiteral := elements[1]\n\tsize, err := strconv.ParseInt(sizeLiteral, 10, 64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"invalid size: %v\", modeLiteral)\n\t}\n\tname := strings.Trim(elements[2], \"\\r\\n\")\n\tif modified == nil {\n\t\tnow := time.Now()\n\t\tmodified = &now\n\t}\n\treturn file.NewInfo(name, size, os.FileMode(mode), *modified, isDir), nil\n}", "func createEndpointListView(results []EndpointData, msg string, code int) ([]byte, error) {\n\n\tdocRoot := &respond.ResponseMessage{\n\t\tStatus: respond.StatusResponse{\n\t\t\tMessage: msg,\n\t\t\tCode: strconv.Itoa(code),\n\t\t},\n\t}\n\tdocRoot.Data = results\n\n\toutput, err := json.MarshalIndent(docRoot, \"\", \" \")\n\treturn output, err\n\n}", "func NewExporter(uri string, timeout time.Duration) *Exporter {\n\tcounters := make(map[string]*prometheus.CounterVec)\n\tgauges := make(map[string]*prometheus.GaugeVec)\n\n\tfor name, info := range counterVecMetrics {\n\t\tlog.Printf(\"Registering %s\", name)\n\t\tcounters[name] = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tHelp: info.help,\n\t\t}, append([]string{\"cluster\", \"node\"}, info.labels...))\n\t}\n\n\tfor name, info := range gaugeVecMetrics {\n\t\tlog.Printf(\"Registering %s\", name)\n\t\tgauges[name] = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tHelp: info.help,\n\t\t}, append([]string{\"cluster\", \"node\"}, info.labels...))\n\t}\n\n\tfor name, help := range counterMetrics {\n\t\tcounters[name] = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t}, []string{\"cluster\", \"node\"})\n\t}\n\n\tfor name, help := range gaugeMetrics {\n\t\tgauges[name] = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t}, []string{\"cluster\", \"node\"})\n\t}\n\n\t// Init our exporter.\n\treturn &Exporter{\n\t\tURI: uri,\n\n\t\tup: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"up\",\n\t\t\tHelp: \"Was the Elasticsearch instance query successful?\",\n\t\t}),\n\n\t\tcounters: counters,\n\t\tgauges: gauges,\n\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: func(netw, addr string) (net.Conn, error) {\n\t\t\t\t\tc, err := net.DialTimeout(netw, addr, timeout)\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\tif err := c.SetDeadline(time.Now().Add(timeout)); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn c, nil\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewGetEntriesOK() *GetEntriesOK {\n\treturn &GetEntriesOK{}\n}", "func CreateListDAGVersionsResponse() (response *ListDAGVersionsResponse) {\n\tresponse = &ListDAGVersionsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (a *ArkRestoresApiService) ListARKRestores(ctx _context.Context, orgId int32, id int32) ([]RestoreResponse, *_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 []RestoreResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/v1/orgs/{orgId}/clusters/{id}/restores\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"orgId\"+\"}\", _neturl.QueryEscape(parameterToString(orgId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(id, \"\")) , -1)\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\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\t\tvar v CommonError\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\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 setArtifactSorter(si *weles.ArtifactSorter) (so weles.ArtifactSorter) {\n\tif si == nil {\n\t\treturn weles.ArtifactSorter{\n\t\t\tSortOrder: weles.SortOrderAscending,\n\t\t\tSortBy: weles.ArtifactSortByID,\n\t\t}\n\t}\n\tif si.SortOrder == \"\" {\n\t\tso.SortOrder = weles.SortOrderAscending\n\t} else {\n\t\tso.SortOrder = si.SortOrder\n\t}\n\tif si.SortBy == \"\" {\n\t\tso.SortBy = weles.ArtifactSortByID\n\t} else {\n\t\tso.SortBy = si.SortBy\n\t}\n\treturn\n}", "func NewListRegistryOK() *ListRegistryOK {\n\treturn &ListRegistryOK{}\n}", "func NewApiResponseWithDefaults() *ApiResponse {\n this := ApiResponse{}\n return &this\n}", "func newFetch(g *Goproxy, name, tempDir string) (*fetch, error) {\n\tf := &fetch{\n\t\tg: g,\n\t\tname: name,\n\t\ttempDir: tempDir,\n\t}\n\n\tvar escapedModulePath string\n\tif strings.HasSuffix(name, \"/@latest\") {\n\t\tescapedModulePath = strings.TrimSuffix(name, \"/@latest\")\n\t\tf.ops = fetchOpsResolve\n\t\tf.moduleVersion = \"latest\"\n\t\tf.contentType = \"application/json; charset=utf-8\"\n\t} else if strings.HasSuffix(name, \"/@v/list\") {\n\t\tescapedModulePath = strings.TrimSuffix(name, \"/@v/list\")\n\t\tf.ops = fetchOpsList\n\t\tf.moduleVersion = \"latest\"\n\t\tf.contentType = \"text/plain; charset=utf-8\"\n\t} else {\n\t\tnameParts := strings.SplitN(name, \"/@v/\", 2)\n\t\tif len(nameParts) != 2 {\n\t\t\treturn nil, errors.New(\"missing /@v/\")\n\t\t}\n\n\t\tescapedModulePath = nameParts[0]\n\n\t\tnameExt := path.Ext(nameParts[1])\n\t\tescapedModuleVersion := strings.TrimSuffix(\n\t\t\tnameParts[1],\n\t\t\tnameExt,\n\t\t)\n\t\tswitch nameExt {\n\t\tcase \".info\":\n\t\t\tf.ops = fetchOpsDownloadInfo\n\t\t\tf.contentType = \"application/json; charset=utf-8\"\n\t\tcase \".mod\":\n\t\t\tf.ops = fetchOpsDownloadMod\n\t\t\tf.contentType = \"text/plain; charset=utf-8\"\n\t\tcase \".zip\":\n\t\t\tf.ops = fetchOpsDownloadZip\n\t\t\tf.contentType = \"application/zip\"\n\t\tcase \"\":\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"no file extension in filename %q\",\n\t\t\t\tescapedModuleVersion,\n\t\t\t)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"unexpected extension %q\",\n\t\t\t\tnameExt,\n\t\t\t)\n\t\t}\n\n\t\tvar err error\n\t\tf.moduleVersion, err = module.UnescapeVersion(\n\t\t\tescapedModuleVersion,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif f.moduleVersion == \"latest\" {\n\t\t\treturn nil, errors.New(\"invalid version\")\n\t\t} else if !semver.IsValid(f.moduleVersion) {\n\t\t\tif f.ops == fetchOpsDownloadInfo {\n\t\t\t\tf.ops = fetchOpsResolve\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"unrecognized version\")\n\t\t\t}\n\t\t}\n\t}\n\n\tvar err error\n\tf.modulePath, err = module.UnescapePath(escapedModulePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.modAtVer = fmt.Sprint(f.modulePath, \"@\", f.moduleVersion)\n\tf.requiredToVerify = g.goBinEnvGOSUMDB != \"off\" &&\n\t\t!globsMatchPath(g.goBinEnvGONOSUMDB, f.modulePath)\n\n\treturn f, nil\n}", "func ListArtifactCredentials(c *gin.Context) {\n\tresponse := ArtifactsCredentials{\n\t\tArtifactsCredential{\n\t\t\tName: \"helm-stable\",\n\t\t\tTypes: []string{\n\t\t\t\t\"helm/chart\",\n\t\t\t},\n\t\t},\n\t\tArtifactsCredential{\n\t\t\tName: \"embedded-artifact\",\n\t\t\tTypes: []string{\n\t\t\t\t\"embedded/base64\",\n\t\t\t},\n\t\t},\n\t}\n\tc.JSON(http.StatusOK, response)\n}", "func (p *FileInf) initDownload(fileList *fileListDl) error {\r\n\tvar err error\r\n\tif p.Progress {\r\n\t\tfmt.Printf(\"Download files from a folder '%s'.\\n\", fileList.SearchedFolder.Name)\r\n\t\tfmt.Printf(\"There are %d files and %d folders in the folder.\\n\", fileList.TotalNumberOfFiles, fileList.TotalNumberOfFolders-1)\r\n\t\tfmt.Println(\"Starting download.\")\r\n\t}\r\n\tidToName := map[string]interface{}{}\r\n\tfor i, e := range fileList.FolderTree.Folders {\r\n\t\tidToName[e] = fileList.FolderTree.Names[i]\r\n\t}\r\n\tfor _, e := range fileList.FileList {\r\n\t\tpath := p.Workdir\r\n\t\tfor _, dir := range e.FolderTree {\r\n\t\t\tpath = filepath.Join(path, idToName[dir].(string))\r\n\t\t}\r\n\t\terr = p.makeDirByCondition(path)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tfor _, file := range e.Files {\r\n\t\t\tfile.Path = path\r\n\t\t\tsize, _ := strconv.ParseInt(file.Size, 10, 64)\r\n\t\t\tp.Size = size\r\n\t\t\terr = p.makeFileByCondition(file)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"There were %d files and %d folders in the folder.\", fileList.TotalNumberOfFiles, fileList.TotalNumberOfFolders-1))\r\n\treturn nil\r\n}", "func New(w http.ResponseWriter, status int, data interface{}) error {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(status)\n\n\treturn json.NewEncoder(w).Encode(data)\n}", "func (a *RepoAPI) ls(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\tvar revision []string\n\tif rev := m.Get(\"revision\").Str(); rev != \"\" {\n\t\trevision = []string{rev}\n\t}\n\treturn rpc.Success(util.Map{\n\t\t\"entries\": a.mods.Repo.ListPath(m.Get(\"name\").Str(), m.Get(\"path\").Str(), revision...),\n\t})\n}", "func (*StoreArtifact_Response) Descriptor() ([]byte, []int) {\n\treturn file_artifactstore_ArtifactStore_proto_rawDescGZIP(), []int{0, 0}\n}", "func NewInfo(machines []string) *Info {\n\treturn &Info{\n\t\tClient: etcd.NewClient(machines),\n\t}\n}", "func (o *ArtifactListerPartialContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\t// response header Next\n\n\tnext := o.Next\n\tif next != \"\" {\n\t\trw.Header().Set(\"Next\", next)\n\t}\n\n\t// response header Previous\n\n\tprevious := o.Previous\n\tif previous != \"\" {\n\t\trw.Header().Set(\"Previous\", previous)\n\t}\n\n\t// response header RemainingRecords\n\n\tremainingRecords := swag.FormatUint64(o.RemainingRecords)\n\tif remainingRecords != \"\" {\n\t\trw.Header().Set(\"RemainingRecords\", remainingRecords)\n\t}\n\n\t// response header TotalRecords\n\n\ttotalRecords := swag.FormatUint64(o.TotalRecords)\n\tif totalRecords != \"\" {\n\t\trw.Header().Set(\"TotalRecords\", totalRecords)\n\t}\n\n\trw.WriteHeader(206)\n\tpayload := o.Payload\n\tif payload == nil {\n\t\tpayload = make([]*weles.ArtifactInfo, 0, 50)\n\t}\n\n\tif err := producer.Produce(rw, payload); err != nil {\n\t\tpanic(err) // let the recovery middleware deal with this\n\t}\n\n}", "func NewObjectsListOK() *ObjectsListOK {\n\n\treturn &ObjectsListOK{}\n}", "func newEtcdCacheEntry(key string, rsp *etcdResponse) *etcdCacheEntry {\n return &etcdCacheEntry{key: key, response:rsp, observers: make([]etcdObserver, 0)}\n}", "func newPerArtifactBuilder(b *Builder, a *latest.Artifact) (artifactBuilder, error) {\n\tswitch {\n\tcase a.DockerArtifact != nil:\n\t\treturn dockerbuilder.NewArtifactBuilder(b.localDocker, b.cfg, b.local.UseDockerCLI, b.local.UseBuildkit, b.pushImages, b.artifactStore, b.sourceDependencies), nil\n\n\tcase a.BazelArtifact != nil:\n\t\treturn bazel.NewArtifactBuilder(b.localDocker, b.cfg, b.pushImages), nil\n\n\tcase a.JibArtifact != nil:\n\t\treturn jib.NewArtifactBuilder(b.localDocker, b.cfg, b.pushImages, b.skipTests, b.artifactStore), nil\n\n\tcase a.CustomArtifact != nil:\n\t\t// required artifacts as environment variables\n\t\tdependencies := util.EnvPtrMapToSlice(docker.ResolveDependencyImages(a.Dependencies, b.artifactStore, true), \"=\")\n\t\treturn custom.NewArtifactBuilder(b.localDocker, b.cfg, b.pushImages, b.skipTests, append(b.retrieveExtraEnv(), dependencies...)), nil\n\n\tcase a.BuildpackArtifact != nil:\n\t\treturn buildpacks.NewArtifactBuilder(b.localDocker, b.pushImages, b.mode, b.artifactStore), nil\n\n\tcase a.KoArtifact != nil:\n\t\treturn ko.NewArtifactBuilder(b.localDocker, b.pushImages, b.mode, b.insecureRegistries), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected type %q for local artifact:\\n%s\", misc.ArtifactType(a), misc.FormatArtifact(a))\n\t}\n}", "func (h *ArchiveHandler) New(parseMethod func([]byte) int64, archiveFileName string) {\r\n\th.parseMethod = parseMethod\r\n\th.resultsFileName = archiveFileName\r\n\th.newValueChannel = make(chan int64)\r\n\th.newDataChannel = make(chan mainData)\r\n\th.getDataChannel = make(chan bool)\r\n\th.sourceURL = readArchive(h.resultsFileName).SourceURL\r\n}", "func (client *GalleryImageVersionsClient) listByGalleryImageCreateRequest(ctx context.Context, resourceGroupName string, galleryName string, galleryImageName string, options *GalleryImageVersionsListByGalleryImageOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryName}\", url.PathEscape(galleryName))\n\turlPath = strings.ReplaceAll(urlPath, \"{galleryImageName}\", url.PathEscape(galleryImageName))\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\", \"2020-09-30\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (api objectAPIHandlers) headObjectInArchiveFileHandler(ctx context.Context, objectAPI ObjectLayer, bucket, object string, w http.ResponseWriter, r *http.Request) {\n\tif crypto.S3.IsRequested(r.Header) || crypto.S3KMS.IsRequested(r.Header) { // If SSE-S3 or SSE-KMS present -> AWS fails with undefined error\n\t\twriteErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(ErrBadRequest))\n\t\treturn\n\t}\n\tif _, ok := crypto.IsRequested(r.Header); !objectAPI.IsEncryptionSupported() && ok {\n\t\twriteErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadRequest), r.URL)\n\t\treturn\n\t}\n\n\tzipPath, object, err := splitZipExtensionPath(object)\n\tif err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\tgetObjectInfo := objectAPI.GetObjectInfo\n\tif api.CacheAPI() != nil {\n\t\tgetObjectInfo = api.CacheAPI().GetObjectInfo\n\t}\n\n\topts, err := getOpts(ctx, r, bucket, zipPath)\n\tif err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\tif s3Error := checkRequestAuthType(ctx, r, policy.GetObjectAction, bucket, zipPath); s3Error != ErrNone {\n\t\tif getRequestAuthType(r) == authTypeAnonymous {\n\t\t\t// As per \"Permission\" section in\n\t\t\t// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html\n\t\t\t// If the object you request does not exist,\n\t\t\t// the error Amazon S3 returns depends on\n\t\t\t// whether you also have the s3:ListBucket\n\t\t\t// permission.\n\t\t\t// * If you have the s3:ListBucket permission\n\t\t\t// on the bucket, Amazon S3 will return an\n\t\t\t// HTTP status code 404 (\"no such key\")\n\t\t\t// error.\n\t\t\t// * if you don’t have the s3:ListBucket\n\t\t\t// permission, Amazon S3 will return an HTTP\n\t\t\t// status code 403 (\"access denied\") error.`\n\t\t\tif globalPolicySys.IsAllowed(policy.Args{\n\t\t\t\tAction: policy.ListBucketAction,\n\t\t\t\tBucketName: bucket,\n\t\t\t\tConditionValues: getConditionValues(r, \"\", \"\", nil),\n\t\t\t\tIsOwner: false,\n\t\t\t}) {\n\t\t\t\t_, err = getObjectInfo(ctx, bucket, zipPath, opts)\n\t\t\t\tif toAPIError(ctx, err).Code == \"NoSuchKey\" {\n\t\t\t\t\ts3Error = ErrNoSuchKey\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twriteErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(s3Error))\n\t\treturn\n\t}\n\n\tvar rs *HTTPRangeSpec\n\n\t// Validate pre-conditions if any.\n\topts.CheckPrecondFn = func(oi ObjectInfo) bool {\n\t\treturn checkPreconditions(ctx, w, r, oi, opts)\n\t}\n\n\tzipObjInfo, err := getObjectInfo(ctx, bucket, zipPath, opts)\n\tif err != nil {\n\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\tvar zipInfo []byte\n\n\tif z, ok := zipObjInfo.UserDefined[archiveInfoMetadataKey]; ok {\n\t\tzipInfo = []byte(z)\n\t} else {\n\t\tzipInfo, err = updateObjectMetadataWithZipInfo(ctx, objectAPI, bucket, zipPath, opts)\n\t}\n\tif err != nil {\n\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\treturn\n\t}\n\n\tfile, err := zipindex.FindSerialized(zipInfo, object)\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\twriteErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchKey), r.URL)\n\t\t} else {\n\t\t\twriteErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)\n\t\t}\n\t\treturn\n\t}\n\n\tobjInfo := ObjectInfo{\n\t\tBucket: bucket,\n\t\tName: file.Name,\n\t\tSize: int64(file.UncompressedSize64),\n\t\tModTime: zipObjInfo.ModTime,\n\t}\n\n\t// Set standard object headers.\n\tif err = setObjectHeaders(w, objInfo, nil, opts); err != nil {\n\t\twriteErrorResponseHeadersOnly(w, toAPIError(ctx, err))\n\t\treturn\n\t}\n\n\t// Set any additional requested response headers.\n\tsetHeadGetRespHeaders(w, r.URL.Query())\n\n\t// Successful response.\n\tif rs != nil {\n\t\tw.WriteHeader(http.StatusPartialContent)\n\t} else {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}", "func compareRequest2() {\n\tvar artifactList1, artifactList2 []ArtifactRecord\n\tvar artifactName1, artifactName2 string = \"111\", \"222\"\n\tvar listTitle1, listTitle2 string\n\tvar repoCount int\n\tvar err error\n\n\tif len(os.Args[1:]) == 1 {\n\t\tfmt.Println(_COMPARE_HELP_CONTENT)\n\t\treturn\n\t}\n\n\t// At least one additional argument.\n\t//scanner := bufio.NewScanner(os.Stdin)\n\trepoCount = 0\n\tfor i := 2; i < len(os.Args) && repoCount < 2; i++ {\n\t\t// Check if \"help\" is the second argument.\n\t\tartifact_arg := os.Args[i]\n\t\tswitch strings.ToLower(artifact_arg) {\n\t\tcase \"--help\", \"-help\", \"-h\":\n\t\t\tfmt.Println(_COMPARE_HELP_CONTENT)\n\t\t\treturn\n\t\tcase \"--dir\":\n\t\t\t////fmt.Println (len (os.Args[:i]))\n\t\t\tif len(os.Args[i:]) == 1 {\n\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing next argument: a directory was expected for argument %d\", i))\n\t\t\t\treturn // we are done. exit.\n\t\t\t} else {\n\t\t\t\tdirectory := os.Args[i+1]\n\t\t\t\ti++\n\t\t\t\tif !isDirectory(directory) {\n\t\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Argument %d: '%s' is not a directory\", i, directory))\n\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t}\n\t\t\t\tswitch repoCount {\n\t\t\t\tcase 0:\n\t\t\t\t\tartifactList1, _ = createEnvelopeFromDirectory(directory, false)\n\t\t\t\t\tartifactName1 = directory\n\t\t\t\t\tlistTitle1 = \"Directory**\"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\tcase 1:\n\t\t\t\t\tartifactList2, _ = createEnvelopeFromDirectory(directory, false)\n\t\t\t\t\tartifactName2 = directory\n\t\t\t\t\tlistTitle2 = \"Directory++\"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"--env\":\n\t\t\tif len(os.Args[i:]) == 1 {\n\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing next argument: a directory was expected for argument %d\", i))\n\t\t\t\treturn // we are done. exit.\n\t\t\t} else {\n\t\t\t\tpart_uuid := os.Args[i+1]\n\t\t\t\ti++\n\t\t\t\tif !isValidUUID(part_uuid) {\n\t\t\t\t\tdisplayErrorMsg(fmt.Sprintf(\"'%s' is not valid uuid\", part_uuid))\n\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t}\n\t\t\t\tswitch repoCount {\n\t\t\t\tcase 0:\n\t\t\t\t\t//artifactList1, err = getPartArtifacts(part_uuid)\n\t\t\t\t\tartifactList1, err = getEnvelopeArtifactsFromLedger(part_uuid)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t\t}\n\t\t\t\t\tartifactName1, _ = getAliasUsingValue(part_uuid)\n\t\t\t\t\tif len(artifactName1) < 1 {\n\t\t\t\t\t\tartifactName1 = trimUUID(part_uuid, 5)\n\t\t\t\t\t}\n\t\t\t\t\tlistTitle1 = \" Ledger** \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\tcase 1:\n\t\t\t\t\t// artifactList2, err = getPartArtifacts(part_uuid)\n\t\t\t\t\tartifactList2, err = getEnvelopeArtifactsFromLedger(part_uuid)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\t\t\treturn // we are done. exit.\n\t\t\t\t\t}\n\t\t\t\t\tartifactName2, _ = getAliasUsingValue(part_uuid)\n\t\t\t\t\tif len(artifactName2) < 1 {\n\t\t\t\t\t\tartifactName2 = trimUUID(part_uuid, 5)\n\t\t\t\t\t}\n\t\t\t\t\tlistTitle2 = \" Ledger++ \"\n\t\t\t\t\trepoCount++ // we can accept up to two repositories (director and/or part)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tdisplayErrorMsg(fmt.Sprintf(\"'%s' is not a valid argument.\\n\", os.Args[i]))\n\t\t\treturn // we are done. exit.\n\t\t} // switch strings.ToLower(artifact_arg)\n\t} // for i :=\n\n\tif repoCount < 2 { // make sure we have two repositories to compare.\n\n\t\tdisplayErrorMsg(fmt.Sprintf(\"Missing two repositories to compare. Try: %s %s --help\",\n\t\t\tfilepath.Base(os.Args[0]), os.Args[1]))\n\t\treturn\n\t}\n\t// check if any artifacts to display\n\tif len(artifactList1) == 0 {\n\t\tfmt.Printf(\"No artifacts are contained within repo %s\\n\", artifactName1)\n\t\treturn\n\t}\n\t// check if any artifacts to display.\n\tif len(artifactList2) == 0 {\n\t\tfmt.Printf(\"No artifacts are contained within repo %s\\n\", artifactName2)\n\t\treturn\n\t}\n\n\t// Display comparison table\n\tconst equalStr = \"=\"\n\tconst notEqualStr = \"X\"\n\tconst noMatchStr = \" - \"\n\n\t/*******************************************\n\tconst padding = 0\n\t//w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, ' ', tabwriter.Debug)\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, padding, ' ', 0)\n\t// writer := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\tfmt.Println()\n\n\t//fmt.Println(\" \tComparing ...\")\n\tfmt.Fprintf(w, \" \\t %s\\t%s\\t%s\\t%s \\t\\n\", \"----------------------\", \" -----------\", \" \", \" -----------\")\n\t//fmt.Fprintf(w, \" \\t %s \\t%s\\t%s\\t\\n\", \" Artifacts\", \" Directory*\", \" Ledger*\")\n\tfmt.Fprintf(w, \" \\t %s\\t%s\\t%s\\t%s\\t\\n\", \" Artifacts\", listTitle1, \" \", listTitle2)\n\t//fmt.Fprintf(w, \" \\t %s\\t%s %s %s \\t\\n\", \" Artifacts\", listTitle1, \" \", listTitle2)\n\tfmt.Fprintf(w, \" \\t %s\\t%s\\t%s\\t%s \\t\\n\", \"----------------------\", \" -----------\", \" \", \" -----------\")\n\t//fmt.Fprintf(w, \" \\t %s\\t%s %s %s \\t\\n\", \"----------------------\", \" -----------\", \" \", \" -----------\")\n\t*********************************************/\n\tfmt.Println()\n\tconst padding = 0\n\t//w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, ' ', tabwriter.Debug)\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, padding, ' ', 0)\n\n\theader := []string{\" Artifacts \", listTitle1, \"\", listTitle2}\n\tPrintRow(w, PaintRowUniformly(DefaultText, AnonymizeRow(header))) // header separator\n\tPrintRow(w, PaintRowUniformly(CyanText, header))\n\tPrintRow(w, PaintRowUniformly(DefaultText, AnonymizeRow(header))) // header separator\n\n\tvar colors []Color\n\n\tfor i := 0; i < len(artifactList1); i++ {\n\t\tfor k := 0; k < len(artifactList2); k++ {\n\t\t\t// check that it is not the envelope container\n\t\t\tif artifactList1[i].ContentType == \"envelope\" || artifactList2[k].ContentType == \"envelope\" {\n\t\t\t\tif artifactList1[i].ContentType == _ENVELOPE_TYPE {\n\t\t\t\t\tartifactList1[i]._verified = true\n\t\t\t\t}\n\t\t\t\tif artifactList2[k].ContentType == _ENVELOPE_TYPE {\n\t\t\t\t\tartifactList2[k]._verified = true\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// See if we have a match (that is not the main envelope)\n\t\t\tif artifactList1[i].Checksum == artifactList2[k].Checksum {\n\t\t\t\t// we have a match\n\t\t\t\tcolors = []Color{DefaultText, DefaultText, GreenText, DefaultText}\n\t\t\t\t////fmt.Fprintf(w, \"\\t %s\\t %s\\t %s\\t %s\\n\", id, namea, artifacts[i].Type, path)\n\t\t\t\t//fmt.Fprintf(w, \" \\t %s \\t %s \\t %s \\t %s\\t\\n\", artifactList1[i].Name, trimUUID(artifactList1[i].Checksum, 5), equalStr, trimUUID(artifactList2[k].Checksum, 5))\n\t\t\t\tPrintRow(w, PaintRow(colors, []string{\n\t\t\t\t\tartifactList1[i].Name,\n\t\t\t\t\t\" \" + trimUUID(artifactList1[i].Checksum, 5),\n\t\t\t\t\tequalStr,\n\t\t\t\t\t\" \" + trimUUID(artifactList2[k].Checksum, 5)}))\n\t\t\t\t////fmt.Fprintf(w, \" \\t %s \\t %s %s %s\\t\\n\", artifactList1[i].Name, trimUUID(artifactList1[i].Checksum, 5), equalStr, trimUUID(artifactList2[k].Checksum, 5))\n\t\t\t\tartifactList1[i]._verified = true\n\t\t\t\tartifactList2[k]._verified = true\n\t\t\t}\n\t\t}\n\t}\n\t// Now run through the first list to see if any unverified.\n\tfor i := 0; i < len(artifactList1); i++ {\n\t\tif !artifactList1[i]._verified {\n\t\t\tcolors = []Color{DefaultText, DefaultText, RedText, RedText}\n\t\t\tPrintRow(w, PaintRow(colors, []string{\n\t\t\t\tartifactList1[i].Name,\n\t\t\t\t\" \" + trimUUID(artifactList1[i].Checksum, 5),\n\t\t\t\tnotEqualStr,\n\t\t\t\tnoMatchStr}))\n\t\t\t//fmt.Fprintf(w, \" \\t %s \\t %s \\t %s \\t %s\\t\\n\", artifactList1[i].Name, trimUUID(artifactList1[i].Checksum, 5), notEqualStr, noMatchStr)\n\t\t}\n\t}\n\n\t// Now run through the second list to see if any unmatched.\n\tfor k := 0; k < len(artifactList2); k++ {\n\t\tif !artifactList2[k]._verified {\n\t\t\t////id_2 := part_list_2[k].Checksum\n\t\t\t////id_2 = id_2[:5]\n\t\t\t//fmt.Fprintf(w, \" \\t %s \\t %s \\t %s \\t %s\\t\\n\", artifactList2[k].Name2, noMatchStr, notEqualStr, trimUUID(artifactList2[k].Checksum, 5))\n\t\t\t//fmt.Fprintf(w, \" \\t %s \\t %s \\t %s \\t %s\\t\\n\", artifactList2[k].Name2, noMatchStr, notEqualStr, trimUUID(artifactList2[k].Checksum, 5))\n\t\t\tcolors = []Color{DefaultText, RedText, RedText, DefaultText}\n\t\t\tPrintRow(w, PaintRow(colors, []string{\n\t\t\t\tartifactList2[k].Name2,\n\t\t\t\tnoMatchStr,\n\t\t\t\tnotEqualStr,\n\t\t\t\t\" \" + trimUUID(artifactList2[k].Checksum, 5)}))\n\t\t}\n\t}\n\t// Write out comparison table.\n\t//fmt.Fprintf(w, \" \\t %s \\t%s\\t%s\\t\\n\", \"----------------------\", \" -----------\", \" -----------\")\n\t//fmt.Fprintf(w, \" \\t %s\\t%s\\t%s\\t%s \\t\\n\", \"----------------------\", \" -----------\", \" \", \" -----------\")\n\t//fmt.Fprintf(w, \" \\t %s\\t%s\\t%s\\t%s \\t\\n\", \"----------------------\", \" -----------\", \" \", \" -----------\")\n\tPrintRow(w, PaintRowUniformly(DefaultText, AnonymizeRow(header)))\n\tw.Flush()\n\tfmt.Printf(\" **%s%s%s List\\n\", _CYAN_FG, artifactName1, _COLOR_END)\n\tfmt.Printf(\" ++%s%s%s List\\n\", _CYAN_FG, artifactName2, _COLOR_END)\n\tfmt.Println()\n}", "func (r *LocalRegistry) List(artHome string, extended bool) {\n\t// get a table writer for the stdout\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.Debug)\n\t// print the header row\n\tvar err error\n\tif extended {\n\t\t_, err = fmt.Fprintln(w, i18n.String(artHome, i18n.LBL_LS_HEADER_PLUS))\n\t} else {\n\t\t_, err = fmt.Fprintln(w, i18n.String(artHome, i18n.LBL_LS_HEADER))\n\t}\n\tcore.CheckErr(err, \"failed to write table header\")\n\tvar (\n\t\ts *data.Seal\n\t\tauthor string\n\t)\n\t// repository, tag, package id, created, size\n\tfor _, repo := range r.Repositories {\n\t\tfor _, a := range repo.Packages {\n\t\t\ts, err = r.GetSeal(a)\n\t\t\tif err != nil {\n\t\t\t\tauthor = \"unknown\"\n\t\t\t} else {\n\t\t\t\tauthor = s.Manifest.Author\n\t\t\t}\n\t\t\t// if the package is dangling (no tags)\n\t\t\tif len(a.Tags) == 0 {\n\t\t\t\tif extended {\n\t\t\t\t\t_, err = fmt.Fprintln(w, fmt.Sprintf(\"%s\\t %s\\t %s\\t %s\\t %s\\t %s\\t %s\\t\",\n\t\t\t\t\t\trepo.Repository,\n\t\t\t\t\t\t\"<none>\",\n\t\t\t\t\t\ta.Id[0:12],\n\t\t\t\t\t\ta.Type,\n\t\t\t\t\t\ttoElapsedLabel(a.Created),\n\t\t\t\t\t\ta.Size,\n\t\t\t\t\t\tauthor),\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t_, err = fmt.Fprintln(w, fmt.Sprintf(\"%s\\t %s\\t %s\\t %s\\t %s\\t %s\\t\",\n\t\t\t\t\t\trepo.Repository,\n\t\t\t\t\t\t\"<none>\",\n\t\t\t\t\t\ta.Id[0:12],\n\t\t\t\t\t\ta.Type,\n\t\t\t\t\t\ttoElapsedLabel(a.Created),\n\t\t\t\t\t\ta.Size),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcore.CheckErr(err, \"failed to write output\")\n\t\t\t}\n\t\t\tfor _, tag := range a.Tags {\n\t\t\t\tif extended {\n\t\t\t\t\t_, err = fmt.Fprintln(w, fmt.Sprintf(\"%s\\t %s\\t %s\\t %s\\t %s\\t %s\\t %s\\t\",\n\t\t\t\t\t\trepo.Repository,\n\t\t\t\t\t\ttag,\n\t\t\t\t\t\ta.Id[0:12],\n\t\t\t\t\t\ta.Type,\n\t\t\t\t\t\ttoElapsedLabel(a.Created),\n\t\t\t\t\t\ta.Size,\n\t\t\t\t\t\tauthor),\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\t_, err = fmt.Fprintln(w, fmt.Sprintf(\"%s\\t %s\\t %s\\t %s\\t %s\\t %s\\t\",\n\t\t\t\t\t\trepo.Repository,\n\t\t\t\t\t\ttag,\n\t\t\t\t\t\ta.Id[0:12],\n\t\t\t\t\t\ta.Type,\n\t\t\t\t\t\ttoElapsedLabel(a.Created),\n\t\t\t\t\t\ta.Size),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcore.CheckErr(err, \"failed to write output\")\n\t\t\t}\n\t\t}\n\t}\n\terr = w.Flush()\n\tcore.CheckErr(err, \"failed to flush output\")\n}", "func ListTodosOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.TodosController) (http.ResponseWriter, app.TodoCollection) {\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// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/todos/\"),\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"TodosTest\"), rw, req, prms)\n\tlistCtx, _err := app.NewListTodosContext(goaCtx, req, service)\n\tif _err != nil {\n\t\tpanic(\"invalid test data \" + _err.Error()) // bug\n\t}\n\n\t// Perform action\n\t_err = ctrl.List(listCtx)\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.TodoCollection\n\tif resp != nil {\n\t\tvar ok bool\n\t\tmt, ok = resp.(app.TodoCollection)\n\t\tif !ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.TodoCollection\", 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 CreateDescribeAssetListResponse() (response *DescribeAssetListResponse) {\n\tresponse = &DescribeAssetListResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*SetDefaultArchiveConfigResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_bucketsd_pb_bucketsd_proto_rawDescGZIP(), []int{43}\n}", "func NewAddItemOK() *AddItemOK {\n\n\treturn &AddItemOK{}\n}" ]
[ "0.5894261", "0.5560803", "0.53907716", "0.49320006", "0.48386315", "0.47734094", "0.47326544", "0.4720476", "0.46708527", "0.46335799", "0.45692658", "0.45435777", "0.45155922", "0.45027113", "0.44864592", "0.44673875", "0.44423497", "0.44338384", "0.4429001", "0.4428382", "0.44179443", "0.44116515", "0.44055325", "0.44053033", "0.4390779", "0.4387632", "0.4369974", "0.43593854", "0.4354404", "0.43394265", "0.4318646", "0.4315497", "0.4311377", "0.43105295", "0.43101034", "0.4284161", "0.42700008", "0.42677465", "0.42676294", "0.42653072", "0.42575294", "0.42532384", "0.4243418", "0.4234523", "0.4223661", "0.42195922", "0.42165393", "0.42143553", "0.42094156", "0.42083368", "0.42075405", "0.4198035", "0.4197217", "0.41835922", "0.41815978", "0.41714606", "0.41678682", "0.4166767", "0.41652715", "0.41631934", "0.41617504", "0.4154354", "0.4153103", "0.41521552", "0.4145738", "0.41435507", "0.41430432", "0.41388518", "0.41325378", "0.41303265", "0.4124948", "0.4124319", "0.41187125", "0.41184866", "0.41173503", "0.4115162", "0.41141263", "0.40833846", "0.40750182", "0.40719435", "0.406841", "0.40654957", "0.40569115", "0.4055674", "0.40514436", "0.4051001", "0.40485236", "0.40482917", "0.40456077", "0.4042142", "0.404083", "0.40382972", "0.4034609", "0.40324876", "0.40322423", "0.40320644", "0.403071", "0.4029191", "0.40244803", "0.4022548" ]
0.69606286
0
WithNext adds the next to the artifact lister o k response
func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK { o.Next = next return o }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}", "func (o *ArtifactListerOK) SetNext(next string) {\n\to.Next = next\n}", "func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}", "func (o *ArtifactListerPartialContent) SetNext(next string) {\n\to.Next = next\n}", "func (page *ResourceListResultPage) Next() error {\n\tnext, err := page.fn(page.rlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.rlr = next\n\treturn nil\n}", "func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}", "func (page *AppListResultPage) Next() error {\n\tnext, err := page.fn(page.alr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.alr = next\n\treturn nil\n}", "func (s Service) Next(msg *Message, data interface{}, useMeta map[string]string) error {\n\terr := msg.RawMessage.Ack(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Chain == nil {\n\t\treturn ErrorChainIsEmpty\n\t}\n\n\tchain := SetCurrentItemSuccess(msg.Chain)\n\n\tnextIndex := getCurrentChainIndex(chain)\n\tif nextIndex == -1 {\n\t\treturn ErrorNextIsNotDefined\n\t}\n\n\tnextElement := chain[nextIndex]\n\n\tmeta := Meta{}\n\tmeta.Merge(msg.Meta, useMeta)\n\n\tvar items []interface{}\n\n\tif nextElement.IsMultiple {\n\t\tval := reflect.ValueOf(data)\n\n\t\tif val.Kind() != reflect.Slice {\n\t\t\treturn ErrorDataIsNotArray\n\t\t}\n\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\titems = append(items, val.Index(i).Interface())\n\t\t}\n\t} else {\n\t\titems = append(items, data)\n\t}\n\n\tfor _, item := range items {\n\t\tb, err := json.Marshal(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := InitialMessage{\n\t\t\tCatch: msg.InitialMessage.Catch,\n\t\t\tConfig: msg.Config,\n\t\t\tMeta: meta,\n\t\t\tChain: chain,\n\t\t\tData: b,\n\t\t}\n\n\t\tif err := s.Publish(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (page *ExportTaskListResultPage) Next() error {\n\tnext, err := page.fn(page.etlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.etlr = next\n\treturn nil\n}", "func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}", "func (page *JobResponseListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (client DatasetClient) listNextResults(ctx context.Context, lastResults DatasetListResponse) (result DatasetListResponse, err error) {\n req, err := lastResults.datasetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }", "func (page *ImportTaskListResultPage) Next() error {\n\tnext, err := page.fn(page.itlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.itlr = next\n\treturn nil\n}", "func (iter *JobResponseListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (i *UploadShrinker) Next() *FileUpload {\n\tvar n int\n\tvar err error\n\n\tif i.Done() {\n\t\treturn nil\n\t}\n\n\tif n, err = i.f.Read(i.buff); err != nil && err != io.EOF {\n\t\ti.err = err\n\t\treturn nil\n\t}\n\n\ti.fu.Chunk = i.chunk\n\ti.fu.Content = i.buff[:n]\n\ti.chunk++\n\n\treturn i.fu\n}", "func (page *ProviderOperationsMetadataListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (client PublishedBlueprintsClient) listNextResults(ctx context.Context, lastResults PublishedBlueprintList) (result PublishedBlueprintList, err error) {\n\treq, err := lastResults.publishedBlueprintListPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"blueprint.PublishedBlueprintsClient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"blueprint.PublishedBlueprintsClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"blueprint.PublishedBlueprintsClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (applications *Applications) Next() (*Result, error) {\n\tif applications.NextURL != \"\" {\n\t\tbody, err := applications.getCursor(applications.NextURL)\n\t\tif err != nil {\n\t\t\tresult := &Result{}\n\t\t\tjson.Unmarshal(body, result)\n\t\t\treturn result, err\n\t\t}\n\t\treturn nil, nil\n\t}\n\treturn nil, errors.New(\"next cursor not available\")\n}", "func (page *DefinitionListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *VaultListResultPage) Next() error {\n\tnext, err := page.fn(page.vlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.vlr = next\n\treturn nil\n}", "func (page *SetDefinitionListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (h *Sagify) SetNext(next job.Handler) {\n\th.next = next\n}", "func (page *AppCollectionListResultPage) Next() error {\n\tnext, err := page.fn(page.aclr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.aclr = next\n\treturn nil\n}", "func (c *listObjCache) next(smap *cluster.Smap, smsg cmn.SelectMsg, bck *cluster.Bck, pageSize uint) (result fetchResult) {\n\tcmn.Assert(smsg.UUID != \"\")\n\tif smap.CountTargets() == 0 {\n\t\treturn fetchResult{err: fmt.Errorf(\"no targets registered\")}\n\t}\n\tentries := c.allTargetsEntries(smsg, smap, bck)\n\tcmn.Assert(len(entries) > 0)\n\tentries[0].parent.mtx.Lock()\n\tresult = c.initResultsFromEntries(entries, smsg, pageSize, smsg.UUID)\n\tif result.allOK && result.err == nil {\n\t\tresult = c.fetchAll(entries, smsg, pageSize)\n\t}\n\tentries[0].parent.mtx.Unlock()\n\n\tc.mtx.Lock()\n\tdelete(c.reqs, smsg.ListObjectsCacheID(bck.Bck))\n\tc.mtx.Unlock()\n\treturn result\n}", "func WithNext(next *url.URL) Opt {\n\treturn func(opts *Options) {\n\t\topts.Next = next\n\t}\n}", "func (iter *MonitoredResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ProviderOperationsMetadataListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (page *ExemptionListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *ExportTaskListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (page *StorageInsightListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *StorageInsightListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *DefinitionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter * ServerListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (p *PaginatedResult) next(ctx context.Context, into interface{}) bool {\n\tif !p.first {\n\t\tif p.nextLink == \"\" {\n\t\t\treturn false\n\t\t}\n\t\tp.err = p.goTo(ctx, p.nextLink)\n\t\tif p.err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\tp.first = false\n\n\tp.err = decodeResp(p.res, into)\n\treturn p.err == nil\n}", "func (iter *SetDefinitionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (p *Playlist) Next() {\n\tp.ch <- \"next\"\n}", "func (iter *MonitorResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func Next() (int, Response) {\n\treturn 0, Response{}\n}", "func Next() {\n\tgo next()\n}", "func (r *ObjectsListingXact) Next() (entry *cmn.BucketEntry, err error) {\n\tres, err := r.NextN(1)\n\tif len(res) == 0 {\n\t\treturn nil, err\n\t}\n\tdebug.Assert(len(res) == 1)\n\treturn res[0], err\n}", "func (page *VirtualMachineListResultPageClient) Next() error {\n\treturn page.vmlrp.Next()\n}", "func (page *MonitoredResourceListResponsePage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *NamespaceListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (si *StatusIndicators) Next() {\n\tfor _, i := range *si {\n\t\ti.Next()\n\t}\n}", "func (o *StdOutOutput) SetNext(next Output) {\n\to.next = next\n}", "func (f *MutateFilter) SetNext(next Filter) {\n\tf.next = next\n}", "func (page *CampaignsListResultPage) Next() error {\n\tnext, err := page.fn(page.clr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.clr = next\n\treturn nil\n}", "func (page *ServiceProviderListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func Next(rt http.RoundTripper) Option {\n\treturn func(p *proxy) { p.next = rt }\n}", "func (iter *UsageAggregationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *RegistrationDefinitionListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ImportTaskListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (f *FrontPage) next() *Article {\n\ta := &Article{SnapshotID: f.SnapshotID}\n\treturn a\n}", "func (client UsageDetailsClient) listByDepartmentNextResults(ctx context.Context, lastResults UsageDetailsListResult) (result UsageDetailsListResult, err error) {\n\treq, err := lastResults.usageDetailsListResultPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListByDepartmentSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListByDepartmentResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (client JobClient) listByAccountNextResults(ctx context.Context, lastResults JobResourceDescriptionList) (result JobResourceDescriptionList, err error) {\n req, err := lastResults.jobResourceDescriptionListPreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListByAccountSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListByAccountResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }", "func (l *Headers) SetNext(h http.Handler) {\n\tl.next = h\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *OperationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *VirtualMachineScaleSetListResultPageClient) Next() error {\n\treturn page.vmsslrp.Next()\n}", "func (page *UsageAggregationListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (client DeploymentsClient) listNextResults(ctx context.Context, lastResults DeploymentResourceCollection) (result DeploymentResourceCollection, err error) {\n\treq, err := lastResults.deploymentResourceCollectionPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (page *DevicesQueryResultPage) Next() error {\n\tnext, err := page.fn(page.dqr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dqr = next\n\treturn nil\n}", "func (iter *ExemptionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (client IotHubResourceClient) listByResourceGroupNextResults(ctx context.Context, lastResults IotHubDescriptionListResult) (result IotHubDescriptionListResult, err error) {\n\treq, err := lastResults.iotHubDescriptionListResultPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"listByResourceGroupNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListByResourceGroupSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"listByResourceGroupNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListByResourceGroupResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"listByResourceGroupNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (g *GZipper) SetNext(h http.Handler) {\n\tg.next = h\n}", "func (page *ListPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (client MSIXPackagesClient) listNextResults(ctx context.Context, lastResults MSIXPackageList) (result MSIXPackageList, err error) {\n\treq, err := lastResults.mSIXPackageListPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"desktopvirtualization.MSIXPackagesClient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"desktopvirtualization.MSIXPackagesClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"desktopvirtualization.MSIXPackagesClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (iter *MonitoringTagRulesListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (r *Route) Next() Backend {\n return r.Backend(r.Index())\n}", "func (iter *ResourceSkusResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (r Response) Next() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"next\",\n\t}\n}", "func (client ProductsClient) listNextResults(ctx context.Context, lastResults ProductList) (result ProductList, err error) {\n\treq, err := lastResults.productListPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (client UsageDetailsClient) listNextResults(ctx context.Context, lastResults UsageDetailsListResult) (result UsageDetailsListResult, err error) {\n\treq, err := lastResults.usageDetailsListResultPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}", "func (iter *ServiceProviderListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (s *ServeSeq) Next(h http.Handler) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.handlers = append(s.handlers, h)\n}", "func (h *HandlersApp01sqVendor) ListNext(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar offset int\n\tvar cTable int\n\n\tlog.Printf(\"hndlrVendor.ListNext(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListNext(Error:405) - Not GET\\n\")\n\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Calculate the offset.\n\tcTable, err = h.db.TableCount()\n\tif err != nil {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListLast(Error:400) - %s\\n\", util.ErrorString(err))\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t}\n\toffset, _ = strconv.Atoi(r.FormValue(\"offset\"))\n\toffset += h.rowsPerPage\n\tif offset < 0 || offset > cTable {\n\t\toffset = 0\n\t}\n\n\t// Display the row in the form.\n\th.ListShow(w, offset, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.ListNext()\\n\")\n\n}", "func (iter *RegisteredAsnListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *NamespaceListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *ServiceOperationListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *OperationListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (page *ConsumerGroupListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *EndpointHealthDataListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (page *ServiceListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *RegisteredAsnListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (page *DataPolicyManifestListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (iter *VMResourcesListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}" ]
[ "0.6979718", "0.68528485", "0.64260054", "0.6225338", "0.59516895", "0.59293854", "0.5898971", "0.5891204", "0.58812654", "0.58260477", "0.58181405", "0.5816745", "0.5740617", "0.57280815", "0.5722505", "0.5693756", "0.5689263", "0.5613842", "0.5594273", "0.5591945", "0.55668503", "0.5565321", "0.5563148", "0.55625904", "0.5541825", "0.5538411", "0.55212367", "0.55169857", "0.54952186", "0.54952186", "0.54948086", "0.5485354", "0.5485354", "0.5480896", "0.54639", "0.546114", "0.5452876", "0.54468226", "0.54407966", "0.54206014", "0.541288", "0.5408162", "0.54047", "0.5392223", "0.5385865", "0.53838253", "0.538305", "0.53727925", "0.5370679", "0.5368086", "0.5365191", "0.53636825", "0.5363587", "0.5361296", "0.5357951", "0.53538245", "0.5349524", "0.5348104", "0.53467697", "0.53465647", "0.53465647", "0.53465647", "0.53465647", "0.53465647", "0.53465647", "0.53465647", "0.53328496", "0.5329531", "0.5323222", "0.53207153", "0.53104854", "0.5305813", "0.5300875", "0.52956015", "0.52927715", "0.52918804", "0.5288855", "0.52865523", "0.5276206", "0.5276019", "0.5272929", "0.52717215", "0.5271696", "0.52686197", "0.52682537", "0.5267817", "0.5267178", "0.5265445", "0.5265445", "0.5265445", "0.5265445", "0.5265445", "0.5265445", "0.5265445", "0.5253614", "0.5248328", "0.52461797", "0.52439415", "0.52288985", "0.5223364" ]
0.76724315
0
SetNext sets the next to the artifact lister o k response
func (o *ArtifactListerOK) SetNext(next string) { o.Next = next }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *ArtifactListerPartialContent) SetNext(next string) {\n\to.Next = next\n}", "func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {\n\to.Next = next\n\treturn o\n}", "func (h *Sagify) SetNext(next job.Handler) {\n\th.next = next\n}", "func (o *StdOutOutput) SetNext(next Output) {\n\to.next = next\n}", "func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}", "func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}", "func (f *MutateFilter) SetNext(next Filter) {\n\tf.next = next\n}", "func (c *layerCache) setNext(next Layer) error {\n\tc.next = next\n\treturn nil\n}", "func (g *GZipper) SetNext(h http.Handler) {\n\tg.next = h\n}", "func (l *Headers) SetNext(h http.Handler) {\n\tl.next = h\n}", "func (tn *MergeNode) SetNext(t *TaskNode) {\n\t// make sure we have a cpy of this in the parent map\n\ttn.floe.registerNode(t)\n\ttn.next = t\n}", "func (page *ExportTaskListResultPage) Next() error {\n\tnext, err := page.fn(page.etlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.etlr = next\n\treturn nil\n}", "func (m *BaseStatement) SetNext(next Statement) {\n\tm.next = next\n}", "func (p *Playlist) Next() {\n\tp.ch <- \"next\"\n}", "func (page *ResourceListResultPage) Next() error {\n\tnext, err := page.fn(page.rlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.rlr = next\n\treturn nil\n}", "func (nu *NodeUpdate) SetNext(n *Node) *NodeUpdate {\n\treturn nu.SetNextID(n.ID)\n}", "func (page *SetDefinitionListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (nuo *NodeUpdateOne) SetNext(n *Node) *NodeUpdateOne {\n\treturn nuo.SetNextID(n.ID)\n}", "func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}", "func (o *Links) SetNext(v string) {\n\to.Next = &v\n}", "func (page *ImportTaskListResultPage) Next() error {\n\tnext, err := page.fn(page.itlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.itlr = next\n\treturn nil\n}", "func (p *RelPublisher) SetNextSlot(ns px.SlotID) {\n}", "func (lt *LineTask) SetNext(v *LineTask) {\n\tif lt == v {\n\t\tpanic(fmt.Errorf(\"try to self loop: %v\", lt))\n\t}\n\tif lt.next != nil {\n\t\tlt.next.SetBefore(nil)\n\t\tlt.next = nil\n\t\tlt.NextID = ZERO\n\t}\n\tlt.next = v\n\tif v != nil {\n\t\tif lt.TaskType == OnPassing && v.TaskType == OnDeparture {\n\t\t\tpanic(fmt.Errorf(\"try to set Dept to Pass : %v -> %v\", v, lt))\n\t\t}\n\t\tif lt.ToNode() != v.FromNode() {\n\t\t\tpanic(fmt.Errorf(\"try to set far task : %v -> %v\", v, lt))\n\t\t}\n\t\tlt.NextID = v.ID\n\t\tv.SetBefore(lt)\n\t} else {\n\t\tlt.NextID = ZERO\n\t}\n\tlt.RailLine.ReRouting = true\n\tlt.Change()\n}", "func (iter *ExportTaskListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (iter *SetDefinitionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (c *Comics) Next() string {\n\tnext := c.Num + 1\n\n\treturn fmt.Sprintf(\"/?id=%d\", next)\n}", "func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}", "func (b *BadRequest) SetNext(_h http.Handler) {\n}", "func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (o *VolumeModifyIterAsyncResponseResult) NextTag() string {\n\tvar r string\n\tif o.NextTagPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NextTagPtr\n\treturn r\n}", "func (validationType *ValidationType) SetNext(next Validation) {\n\tvalidationType.Next = next\n}", "func (s Service) Next(msg *Message, data interface{}, useMeta map[string]string) error {\n\terr := msg.RawMessage.Ack(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Chain == nil {\n\t\treturn ErrorChainIsEmpty\n\t}\n\n\tchain := SetCurrentItemSuccess(msg.Chain)\n\n\tnextIndex := getCurrentChainIndex(chain)\n\tif nextIndex == -1 {\n\t\treturn ErrorNextIsNotDefined\n\t}\n\n\tnextElement := chain[nextIndex]\n\n\tmeta := Meta{}\n\tmeta.Merge(msg.Meta, useMeta)\n\n\tvar items []interface{}\n\n\tif nextElement.IsMultiple {\n\t\tval := reflect.ValueOf(data)\n\n\t\tif val.Kind() != reflect.Slice {\n\t\t\treturn ErrorDataIsNotArray\n\t\t}\n\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\titems = append(items, val.Index(i).Interface())\n\t\t}\n\t} else {\n\t\titems = append(items, data)\n\t}\n\n\tfor _, item := range items {\n\t\tb, err := json.Marshal(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := InitialMessage{\n\t\t\tCatch: msg.InitialMessage.Catch,\n\t\t\tConfig: msg.Config,\n\t\t\tMeta: meta,\n\t\t\tChain: chain,\n\t\t\tData: b,\n\t\t}\n\n\t\tif err := s.Publish(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (page *AppListResultPage) Next() error {\n\tnext, err := page.fn(page.alr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.alr = next\n\treturn nil\n}", "func Next(rt http.RoundTripper) Option {\n\treturn func(p *proxy) { p.next = rt }\n}", "func (client DatasetClient) listNextResults(ctx context.Context, lastResults DatasetListResponse) (result DatasetListResponse, err error) {\n req, err := lastResults.datasetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }", "func (page *JobResponseListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (c *listObjCache) next(smap *cluster.Smap, smsg cmn.SelectMsg, bck *cluster.Bck, pageSize uint) (result fetchResult) {\n\tcmn.Assert(smsg.UUID != \"\")\n\tif smap.CountTargets() == 0 {\n\t\treturn fetchResult{err: fmt.Errorf(\"no targets registered\")}\n\t}\n\tentries := c.allTargetsEntries(smsg, smap, bck)\n\tcmn.Assert(len(entries) > 0)\n\tentries[0].parent.mtx.Lock()\n\tresult = c.initResultsFromEntries(entries, smsg, pageSize, smsg.UUID)\n\tif result.allOK && result.err == nil {\n\t\tresult = c.fetchAll(entries, smsg, pageSize)\n\t}\n\tentries[0].parent.mtx.Unlock()\n\n\tc.mtx.Lock()\n\tdelete(c.reqs, smsg.ListObjectsCacheID(bck.Bck))\n\tc.mtx.Unlock()\n\treturn result\n}", "func (page *VirtualMachineScaleSetListResultPageClient) Next() error {\n\treturn page.vmsslrp.Next()\n}", "func (cycle *Cycle) Next() {\n\tif !cycle.showing {\n\t\treturn\n\t}\n\n\tif cycle.selected == -1 {\n\t\tif len(cycle.items) > 1 {\n\t\t\tcycle.selected = 1\n\t\t} else {\n\t\t\tcycle.selected = 0\n\t\t}\n\t} else {\n\t\tcycle.selected++\n\t}\n\n\tcycle.selected = misc.Mod(cycle.selected, len(cycle.items))\n\tcycle.highlight()\n}", "func (applications *Applications) Next() (*Result, error) {\n\tif applications.NextURL != \"\" {\n\t\tbody, err := applications.getCursor(applications.NextURL)\n\t\tif err != nil {\n\t\t\tresult := &Result{}\n\t\t\tjson.Unmarshal(body, result)\n\t\t\treturn result, err\n\t\t}\n\t\treturn nil, nil\n\t}\n\treturn nil, errors.New(\"next cursor not available\")\n}", "func (iter *ImportTaskListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (c *CompletionManager) Next() {\n\tif c.verticalScroll+int(c.max)-1 == c.selected {\n\t\tc.verticalScroll++\n\t}\n\tc.selected++\n\tc.update()\n}", "func (page *AppCollectionListResultPage) Next() error {\n\tnext, err := page.fn(page.aclr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.aclr = next\n\treturn nil\n}", "func (page *VaultListResultPage) Next() error {\n\tnext, err := page.fn(page.vlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.vlr = next\n\treturn nil\n}", "func Next() {\n\tgo next()\n}", "func (iter *JobResponseListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (page *VirtualMachineListResultPageClient) Next() error {\n\treturn page.vmlrp.Next()\n}", "func (page *CampaignsListResultPage) Next() error {\n\tnext, err := page.fn(page.clr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.clr = next\n\treturn nil\n}", "func (iter *MonitorResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (si *StatusIndicators) Next() {\n\tfor _, i := range *si {\n\t\ti.Next()\n\t}\n}", "func (page *DefinitionListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (r Response) Next() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"next\",\n\t}\n}", "func (client FeatureStateClient) listStatesetNextResults(ctx context.Context, lastResults StatesetListResponse) (result StatesetListResponse, err error) {\n req, err := lastResults.statesetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"listStatesetNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListStatesetSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"listStatesetNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListStatesetResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"listStatesetNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }", "func (c *Client) PlaylistNext() error {\n\t_, err := c.Exec(\"playlist-next\", \"weak\")\n\treturn err\n}", "func (i *UploadShrinker) Next() *FileUpload {\n\tvar n int\n\tvar err error\n\n\tif i.Done() {\n\t\treturn nil\n\t}\n\n\tif n, err = i.f.Read(i.buff); err != nil && err != io.EOF {\n\t\ti.err = err\n\t\treturn nil\n\t}\n\n\ti.fu.Chunk = i.chunk\n\ti.fu.Content = i.buff[:n]\n\ti.chunk++\n\n\treturn i.fu\n}", "func (resp *IntegrationList) GetNextOffset() (*int64, error) {\n\tif core.IsNil(resp.Next) {\n\t\treturn nil, nil\n\t}\n\toffset, err := core.GetQueryParam(resp.Next.Href, \"offset\")\n\tif err != nil || offset == nil {\n\t\treturn nil, err\n\t}\n\tvar offsetValue int64\n\toffsetValue, err = strconv.ParseInt(*offset, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn core.Int64Ptr(offsetValue), nil\n}", "func (wk *WebmKeeper) Next() ([]byte, error) {\n\tel, err := next(wk.p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = wk.handleRandomAccessPoint(el); err != nil {\n\t\treturn nil, err\n\t}\n\n\twk.elemBuf.Reset()\n\tel.WriteTo(wk.elemBuf)\n\tb := make([]byte, wk.elemBuf.Len())\n\tcopy(b, wk.elemBuf.Bytes())\n\n\twk.body.Write(b)\n\treturn b, nil\n}", "func (it *PatchDeploymentIterator) Next() (*osconfigpb.PatchDeployment, error) {\n\tvar item *osconfigpb.PatchDeployment\n\tif err := it.nextFunc(); err != nil {\n\t\treturn item, err\n\t}\n\titem = it.items[0]\n\tit.items = it.items[1:]\n\treturn item, nil\n}", "func (page *VirtualMachineScaleSetVMListResultPageClient) Next() error {\n\treturn page.vmssvlrp.Next()\n}", "func (s *SliceIter) Next() {\n\tval := reflect.ValueOf(s.slice)\n\tval = val.Slice(1, val.Len())\n\ts.slice = val.Interface()\n}", "func (d *Decoder) Next() error {\n\treturn errTODO\n}", "func (r *ObjectsListingXact) Next() (entry *cmn.BucketEntry, err error) {\n\tres, err := r.NextN(1)\n\tif len(res) == 0 {\n\t\treturn nil, err\n\t}\n\tdebug.Assert(len(res) == 1)\n\treturn res[0], err\n}", "func (client ApplicationsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"nextLink\": nextLink,\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.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/{nextLink}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (iter *MonitoredResourceListResponseIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (iter *VaultListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (d *FTSSimulator) Next(p *redisearch.Document) bool {\n\t// Switch to the next document\n\tif d.recordIndex >= uint64(len(d.records)) {\n\t\td.recordIndex = 0\n\t}\n\treturn d.populateDocument(p)\n}", "func (page *ProviderOperationsMetadataListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (resp *ListEnterprisesResponse) GetNextNextDocid() (*string, error) {\n\tif core.IsNil(resp.NextURL) {\n\t\treturn nil, nil\n\t}\n\tnext_docid, err := core.GetQueryParam(resp.NextURL, \"next_docid\")\n\tif err != nil || next_docid == nil {\n\t\treturn nil, err\n\t}\n\treturn next_docid, nil\n}", "func (c *Collection) Next(params ...interface{}) bool {\n\tif c.err != nil {\n\t\treturn false\n\t}\n\n\tif c.Name == \"ALL_MEDIA_AUTO_COLLECTION\" {\n\t\tif c.all == nil {\n\t\t\tc.all = &SavedMedia{\n\t\t\t\tinsta: c.insta,\n\t\t\t\tendpoint: urlFeedSavedPosts,\n\t\t\t}\n\t\t}\n\t\tr := c.all.Next()\n\t\tc.NextID = c.all.NextID\n\t\tc.MoreAvailable = c.all.MoreAvailable\n\t\tc.NumResults = c.all.NumResults\n\t\tc.Items = []Item{}\n\t\tfor _, i := range c.all.Items {\n\t\t\tc.Items = append(c.Items, i.Media)\n\t\t}\n\n\t\tc.err = c.all.err\n\t\treturn r\n\t}\n\tif len(c.Items) == 0 {\n\t\tif err := c.Sync(); err != nil {\n\t\t\tc.err = err\n\t\t\treturn false\n\t\t}\n\t}\n\tinsta := c.insta\n\tbody, _, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: fmt.Sprintf(urlCollectionFeedPosts, c.ID),\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"next_max_id\": c.GetNextID(),\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tc.err = err\n\t\treturn false\n\t}\n\ttmp := SavedMedia{}\n\terr = json.Unmarshal(body, &tmp)\n\n\tc.NextID = tmp.NextID\n\tc.MoreAvailable = tmp.MoreAvailable\n\tc.NumResults = tmp.NumResults\n\n\tc.Items = []Item{}\n\tfor _, i := range tmp.Items {\n\t\tc.Items = append(c.Items, i.Media)\n\t}\n\tc.setValues()\n\n\tif !c.MoreAvailable {\n\t\tc.err = ErrNoMore\n\t}\n\treturn c.MoreAvailable\n}", "func (iter * ServerListResultIterator) Next() error {\n return iter.NextWithContext(context.Background())\n }", "func (this *Iter) SetNextQuery(query *Query) {\n\tthis.nextPageQuery = query\n}", "func (o *IscsiInterfaceGetIterResponseResult) SetNextTag(newValue string) *IscsiInterfaceGetIterResponseResult {\n\to.NextTagPtr = &newValue\n\treturn o\n}", "func (o *VolumeModifyIterAsyncResponseResult) SetNextTag(newValue string) *VolumeModifyIterAsyncResponseResult {\n\to.NextTagPtr = &newValue\n\treturn o\n}", "func (it *Iterator) Next() {\n\tit.listIter.Next()\n}", "func (p *Player) Next() { p.Player.Call(INTERFACE+\".Player.Next\", 0) }", "func (o *IscsiInitiatorGetIterResponseResult) NextTag() string {\n\tvar r string\n\tif o.NextTagPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NextTagPtr\n\treturn r\n}", "func (page *MonitoredResourceListResponsePage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (s *SearchForAssets) NextToken(nextToken string) *SearchForAssets {\n\ts.p.NextToken = nextToken\n\treturn s\n}", "func (cl *APIClient) RequestNextResponsePage(rr *R.Response) (*R.Response, error) {\n\tmycmd := cl.toUpperCaseKeys(rr.GetCommand())\n\tif _, ok := mycmd[\"LAST\"]; ok {\n\t\treturn nil, errors.New(\"Parameter LAST in use. Please remove it to avoid issues in requestNextPage\")\n\t}\n\tfirst := 0\n\tif v, ok := mycmd[\"FIRST\"]; ok {\n\t\tfirst, _ = fmt.Sscan(\"%s\", v)\n\t}\n\ttotal := rr.GetRecordsTotalCount()\n\tlimit := rr.GetRecordsLimitation()\n\tfirst += limit\n\tif first < total {\n\t\tmycmd[\"FIRST\"] = fmt.Sprintf(\"%d\", first)\n\t\tmycmd[\"LIMIT\"] = fmt.Sprintf(\"%d\", limit)\n\t\treturn cl.Request(mycmd), nil\n\t}\n\treturn nil, errors.New(\"Could not find further existing pages\")\n}", "func (resp *TagsSubscriptionList) GetNextOffset() (*int64, error) {\n\tif core.IsNil(resp.Next) {\n\t\treturn nil, nil\n\t}\n\toffset, err := core.GetQueryParam(resp.Next.Href, \"offset\")\n\tif err != nil || offset == nil {\n\t\treturn nil, err\n\t}\n\tvar offsetValue int64\n\toffsetValue, err = strconv.ParseInt(*offset, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn core.Int64Ptr(offsetValue), nil\n}", "func (o *Ga4ghSearchCallSetsResponse) SetNextPageToken(v string) {\n\to.NextPageToken = &v\n}", "func (page *DevicesQueryResultPage) Next() error {\n\tnext, err := page.fn(page.dqr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dqr = next\n\treturn nil\n}", "func (p *PaginatedResult) next(ctx context.Context, into interface{}) bool {\n\tif !p.first {\n\t\tif p.nextLink == \"\" {\n\t\t\treturn false\n\t\t}\n\t\tp.err = p.goTo(ctx, p.nextLink)\n\t\tif p.err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\tp.first = false\n\n\tp.err = decodeResp(p.res, into)\n\treturn p.err == nil\n}", "func (w *watcher) Next() ([]*config.KeyValue, error) {\n\t<-w.exit\n\treturn nil, nil\n}", "func (resp *ConfigurationMetadataPaginatedCollection) GetNextOffset() (*int64, error) {\n\tif core.IsNil(resp.Next) {\n\t\treturn nil, nil\n\t}\n\toffset, err := core.GetQueryParam(resp.Next.Href, \"offset\")\n\tif err != nil || offset == nil {\n\t\treturn nil, err\n\t}\n\tvar offsetValue int64\n\toffsetValue, err = strconv.ParseInt(*offset, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn core.Int64Ptr(offsetValue), nil\n}", "func (page *MonitorResourceListResponsePage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (p *PodsWidget) SelectNext() {\n\tp.ScrollDown()\n}", "func (o *IscsiInitiatorGetIterResponseResult) SetNextTag(newValue string) *IscsiInitiatorGetIterResponseResult {\n\to.NextTagPtr = &newValue\n\treturn o\n}", "func (list *thingList) getNext() (grokeddit.Thing, error) {\n\tif !list.hasNext() {\n\t\treturn grokeddit.Thing{}, errors.New(\"No more things to iterate\")\n\t}\n\n\tif !list.currentThings.hasNext() {\n\t\tnextChunk := <-list.chunkChannel\n\n\t\t// set this variable now, a channel check can only be\n\t\t// done if async request is active.\n\t\tlist.moreThings = nextChunk.moreThings\n\t\tif nextChunk.moreThings {\n\t\t\tlist.fetchNextBlockAsync()\n\t\t}\n\n\t\tif nextChunk.retrievalError != nil {\n\t\t\treturn grokeddit.Thing{}, errors.New(\"Unable to fetch more things: \" + nextChunk.retrievalError.Error())\n\t\t}\n\n\t\tlist.currentThings.setArray(nextChunk.nextThings)\n\t}\n\n\treturn list.currentThings.getNext()\n}", "func (resp *SourceList) GetNextOffset() (*int64, error) {\n\tif core.IsNil(resp.Next) {\n\t\treturn nil, nil\n\t}\n\toffset, err := core.GetQueryParam(resp.Next.Href, \"offset\")\n\tif err != nil || offset == nil {\n\t\treturn nil, err\n\t}\n\tvar offsetValue int64\n\toffsetValue, err = strconv.ParseInt(*offset, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn core.Int64Ptr(offsetValue), nil\n}", "func (iter *RegistrationDefinitionListIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (ic *FilesCursor) Next() bool {\n\tif ic.itemIndex >= len(ic.currentResponse.Contents) && ic.currentResponse.NextMarker == \"\" {\n\t\treturn false\n\t}\n\n\tif ic.itemIndex < len(ic.currentResponse.Contents) {\n\t\tic.currentFile = ic.currentResponse.Contents[ic.itemIndex]\n\t\tic.itemIndex++\n\t} else {\n\t\tic.input.Marker = ic.currentResponse.NextMarker\n\t\tres, err := ic.container.GetContainerContentsSync(ic.input)\n\t\tif err != nil {\n\t\t\tic.currentError = err\n\t\t\treturn false\n\t\t}\n\t\tres.Release()\n\t\tic.currentResponse = res.Output.(*v3io.GetContainerContentsOutput)\n\t\tic.itemIndex = 0\n\t\treturn ic.Next()\n\t}\n\n\treturn true\n}", "func (si *CycleIndicator) Next() {\n\tsi.index = (si.index + 1) % len(si.Indicators)\n}", "func (p *Parser) Next() {\n\tp.curr = p.peek\n\tp.peek = p.l.NextToken()\n}", "func (iter *DefinitionListResultIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (nuo *NodeUpdateOne) SetNextID(id string) *NodeUpdateOne {\n\tif nuo.next == nil {\n\t\tnuo.next = make(map[string]struct{})\n\t}\n\tnuo.next[id] = struct{}{}\n\treturn nuo\n}", "func (nu *NodeUpdate) SetNextID(id string) *NodeUpdate {\n\tif nu.next == nil {\n\t\tnu.next = make(map[string]struct{})\n\t}\n\tnu.next[id] = struct{}{}\n\treturn nu\n}", "func (page *NamespaceListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}", "func (resp *SecretMetadataPaginatedCollection) GetNextOffset() (*int64, error) {\n\tif core.IsNil(resp.Next) {\n\t\treturn nil, nil\n\t}\n\toffset, err := core.GetQueryParam(resp.Next.Href, \"offset\")\n\tif err != nil || offset == nil {\n\t\treturn nil, err\n\t}\n\tvar offsetValue int64\n\toffsetValue, err = strconv.ParseInt(*offset, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn core.Int64Ptr(offsetValue), nil\n}", "func (pagedList *PagedList) GetNextPage() (*Embed, error) {\n\treturn pagedList.GetPage(pagedList.PageNumber + 1)\n}" ]
[ "0.7701029", "0.72452474", "0.7027993", "0.6908621", "0.6683921", "0.65661", "0.65639925", "0.6407066", "0.6395918", "0.63333994", "0.6148755", "0.6133274", "0.61207384", "0.61169827", "0.6032635", "0.60308045", "0.60295266", "0.601939", "0.60086924", "0.5988711", "0.5885545", "0.58668506", "0.58617955", "0.5851676", "0.577626", "0.57622594", "0.5746874", "0.5740132", "0.57366914", "0.5725162", "0.5720566", "0.57117766", "0.5706386", "0.5701513", "0.56990653", "0.5697304", "0.5666256", "0.56523365", "0.5646482", "0.5644864", "0.5643035", "0.56125677", "0.5589309", "0.55816525", "0.557501", "0.55631685", "0.55439353", "0.551579", "0.550631", "0.5505448", "0.55025434", "0.5477744", "0.5471786", "0.5466389", "0.5459568", "0.5458632", "0.54549444", "0.5453094", "0.5452461", "0.5443878", "0.54416126", "0.5441365", "0.5434351", "0.54271144", "0.54182017", "0.5410998", "0.5403971", "0.54028404", "0.5393932", "0.539343", "0.53874123", "0.53860044", "0.5385351", "0.53790414", "0.5370263", "0.5368643", "0.5368139", "0.5360453", "0.53576773", "0.535647", "0.5354446", "0.5349378", "0.53387564", "0.5337844", "0.5336259", "0.5334607", "0.5330227", "0.53279483", "0.53230995", "0.532249", "0.5322005", "0.53196055", "0.53102654", "0.5304882", "0.53040904", "0.53025085", "0.5298832", "0.52978075", "0.52926946", "0.52907145" ]
0.8355537
0